diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ApplicationMasterServiceProtoTestBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ApplicationMasterServiceProtoTestBase.java index 45210188b518c..67999b746161f 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ApplicationMasterServiceProtoTestBase.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ApplicationMasterServiceProtoTestBase.java @@ -26,7 +26,7 @@ import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; -import org.junit.After; +import org.junit.jupiter.api.AfterEach; /** * Test Base for Application Master Service Protocol. @@ -52,7 +52,7 @@ protected void startupHAAndSetupClient() throws Exception { .createRMProxy(this.conf, ApplicationMasterProtocol.class); } - @After + @AfterEach public void shutDown() { if(this.amClient != null) { RPC.stopProxy(this.amClient); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java index 53005aa4b7514..eff68990ea8a8 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java @@ -29,10 +29,10 @@ import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse; import org.apache.hadoop.yarn.api.records.CollectorInfo; import org.apache.hadoop.yarn.api.records.ApplicationAccessType; -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.io.IOException; import java.util.ArrayList; @@ -40,7 +40,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import org.apache.hadoop.yarn.server.resourcemanager.HATestUtil; -import org.junit.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ha.ClientBaseWithFixes; @@ -128,8 +127,8 @@ import org.apache.hadoop.yarn.server.resourcemanager.security.RMDelegationTokenSecretManager; import org.apache.hadoop.yarn.server.security.ApplicationACLsManager; import org.apache.hadoop.yarn.util.Records; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; /** @@ -164,7 +163,7 @@ public abstract class ProtocolHATestBase extends ClientBaseWithFixes { protected Thread failoverThread = null; private volatile boolean keepRunning; - @Before + @BeforeEach public void setup() throws IOException { failoverThread = null; keepRunning = true; @@ -181,7 +180,7 @@ public void setup() throws IOException { conf.setBoolean(YarnConfiguration.YARN_MINICLUSTER_USE_RPC, true); } - @After + @AfterEach public void teardown() throws Exception { keepRunning = false; if (failoverThread != null) { @@ -205,8 +204,8 @@ protected void explicitFailover() throws IOException { int newActiveRMIndex = (activeRMIndex + 1) % 2; getAdminService(activeRMIndex).transitionToStandby(req); getAdminService(newActiveRMIndex).transitionToActive(req); - assertEquals("Failover failed", newActiveRMIndex, - cluster.getActiveRMIndex()); + assertEquals(newActiveRMIndex, + cluster.getActiveRMIndex(), "Failover failed"); } protected YarnClient createAndStartYarnClient(Configuration conf) { @@ -219,8 +218,8 @@ protected YarnClient createAndStartYarnClient(Configuration conf) { protected void verifyConnections() throws InterruptedException, YarnException { - assertTrue("NMs failed to connect to the RM", - cluster.waitForNodeManagersToConnect(5000)); + assertTrue(cluster.waitForNodeManagersToConnect(5000), + "NMs failed to connect to the RM"); verifyClientConnection(); } @@ -284,7 +283,7 @@ protected void startHACluster(int numOfNMs, boolean overrideClientRMService, cluster.resetStartFailoverFlag(false); cluster.init(conf); cluster.start(); - assertFalse("RM never turned active", -1 == cluster.getActiveRMIndex()); + assertFalse(-1 == cluster.getActiveRMIndex(), "RM never turned active"); verifyConnections(); // Do the failover @@ -406,7 +405,7 @@ public GetNewApplicationResponse getNewApplication( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // create the GetNewApplicationResponse with fake applicationId GetNewApplicationResponse response = @@ -421,7 +420,7 @@ public GetApplicationReportResponse getApplicationReport( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // create a fake application report ApplicationReport report = createFakeAppReport(); @@ -436,7 +435,7 @@ public GetClusterMetricsResponse getClusterMetrics( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // create GetClusterMetricsResponse with fake YarnClusterMetrics GetClusterMetricsResponse response = @@ -451,7 +450,7 @@ public GetApplicationsResponse getApplications( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // create GetApplicationsResponse with fake applicationList GetApplicationsResponse response = @@ -466,7 +465,7 @@ public GetClusterNodesResponse getClusterNodes( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // create GetClusterNodesResponse with fake ClusterNodeLists GetClusterNodesResponse response = @@ -480,7 +479,7 @@ public GetQueueInfoResponse getQueueInfo(GetQueueInfoRequest request) resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // return fake QueueInfo return GetQueueInfoResponse.newInstance(createFakeQueueInfo()); @@ -492,7 +491,7 @@ public GetQueueUserAclsInfoResponse getQueueUserAcls( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // return fake queueUserAcls return GetQueueUserAclsInfoResponse @@ -506,7 +505,7 @@ public GetApplicationAttemptReportResponse getApplicationAttemptReport( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // return fake ApplicationAttemptReport return GetApplicationAttemptReportResponse @@ -520,7 +519,7 @@ public GetApplicationAttemptsResponse getApplicationAttempts( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // return fake ApplicationAttemptReports return GetApplicationAttemptsResponse @@ -534,7 +533,7 @@ public GetContainerReportResponse getContainerReport( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // return fake containerReport return GetContainerReportResponse @@ -547,7 +546,7 @@ public GetContainersResponse getContainers(GetContainersRequest request) resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); // return fake ContainerReports return GetContainersResponse.newInstance(createFakeContainerReports()); @@ -559,7 +558,7 @@ public SubmitApplicationResponse submitApplication( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return super.submitApplication(request); } @@ -570,7 +569,7 @@ public KillApplicationResponse forceKillApplication( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return KillApplicationResponse.newInstance(true); } @@ -581,7 +580,7 @@ public MoveApplicationAcrossQueuesResponse moveApplicationAcrossQueues( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return Records.newRecord(MoveApplicationAcrossQueuesResponse.class); } @@ -592,7 +591,7 @@ public GetDelegationTokenResponse getDelegationToken( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return GetDelegationTokenResponse.newInstance(createFakeToken()); } @@ -603,7 +602,7 @@ public RenewDelegationTokenResponse renewDelegationToken( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return RenewDelegationTokenResponse .newInstance(createNextExpirationTime()); @@ -615,7 +614,7 @@ public CancelDelegationTokenResponse cancelDelegationToken( resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return CancelDelegationTokenResponse.newInstance(); } @@ -741,7 +740,7 @@ public RegisterNodeManagerResponse registerNodeManager( IOException { resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return super.registerNodeManager(request); } @@ -750,7 +749,7 @@ public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) throws YarnException, IOException { resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return super.nodeHeartbeat(request); } } @@ -767,7 +766,7 @@ public AllocateResponse allocate(AllocateRequest request) throws YarnException, IOException { resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return createFakeAllocateResponse(); } @@ -777,7 +776,7 @@ public RegisterApplicationMasterResponse registerApplicationMaster( IOException { resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return createFakeRegisterApplicationMasterResponse(); } @@ -787,7 +786,7 @@ public FinishApplicationMasterResponse finishApplicationMaster( IOException { resetStartFailoverFlag(true); // make sure failover has been triggered - Assert.assertTrue(waittingForFailOver()); + assertTrue(waittingForFailOver()); return createFakeFinishApplicationMasterResponse(); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationClientProtocolOnHA.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationClientProtocolOnHA.java index 89b7c9868aa5d..d3f138e550d86 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationClientProtocolOnHA.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationClientProtocolOnHA.java @@ -20,7 +20,6 @@ import java.util.List; -import java.util.concurrent.TimeUnit; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; @@ -42,39 +41,39 @@ import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.util.Records; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Timeout(180) public class TestApplicationClientProtocolOnHA extends ProtocolHATestBase { private YarnClient client = null; - @Before + @BeforeEach public void initiate() throws Exception { startHACluster(1, true, false, false); Configuration conf = new YarnConfiguration(this.conf); client = createAndStartYarnClient(conf); } - @After + @AfterEach public void shutDown() { if (client != null) { client.stop(); } } - @Rule - public Timeout timeout = new Timeout(180, TimeUnit.SECONDS); - @Test public void testGetApplicationReportOnHA() throws Exception { ApplicationReport report = client.getApplicationReport(cluster.createFakeAppId()); - Assert.assertTrue(report != null); - Assert.assertEquals(cluster.createFakeAppReport(), report); + assertTrue(report != null); + assertEquals(cluster.createFakeAppReport(), report); } @Test @@ -82,16 +81,16 @@ public void testGetNewApplicationOnHA() throws Exception { ApplicationId appId = client.createApplication().getApplicationSubmissionContext() .getApplicationId(); - Assert.assertTrue(appId != null); - Assert.assertEquals(cluster.createFakeAppId(), appId); + assertTrue(appId != null); + assertEquals(cluster.createFakeAppId(), appId); } @Test public void testGetClusterMetricsOnHA() throws Exception { YarnClusterMetrics clusterMetrics = client.getYarnClusterMetrics(); - Assert.assertTrue(clusterMetrics != null); - Assert.assertEquals(cluster.createFakeYarnClusterMetrics(), + assertTrue(clusterMetrics != null); + assertEquals(cluster.createFakeYarnClusterMetrics(), clusterMetrics); } @@ -99,35 +98,35 @@ public void testGetClusterMetricsOnHA() throws Exception { public void testGetApplicationsOnHA() throws Exception { List reports = client.getApplications(); - Assert.assertTrue(reports != null); - Assert.assertFalse(reports.isEmpty()); - Assert.assertEquals(cluster.createFakeAppReports(), + assertTrue(reports != null); + assertFalse(reports.isEmpty()); + assertEquals(cluster.createFakeAppReports(), reports); } @Test public void testGetClusterNodesOnHA() throws Exception { List reports = client.getNodeReports(NodeState.RUNNING); - Assert.assertTrue(reports != null); - Assert.assertFalse(reports.isEmpty()); - Assert.assertEquals(cluster.createFakeNodeReports(), + assertTrue(reports != null); + assertFalse(reports.isEmpty()); + assertEquals(cluster.createFakeNodeReports(), reports); } @Test public void testGetQueueInfoOnHA() throws Exception { QueueInfo queueInfo = client.getQueueInfo("root"); - Assert.assertTrue(queueInfo != null); - Assert.assertEquals(cluster.createFakeQueueInfo(), + assertTrue(queueInfo != null); + assertEquals(cluster.createFakeQueueInfo(), queueInfo); } @Test public void testGetQueueUserAclsOnHA() throws Exception { List queueUserAclsList = client.getQueueAclsInfo(); - Assert.assertTrue(queueUserAclsList != null); - Assert.assertFalse(queueUserAclsList.isEmpty()); - Assert.assertEquals(cluster.createFakeQueueUserACLInfoList(), + assertTrue(queueUserAclsList != null); + assertFalse(queueUserAclsList.isEmpty()); + assertEquals(cluster.createFakeQueueUserACLInfoList(), queueUserAclsList); } @@ -136,17 +135,17 @@ public void testGetApplicationAttemptReportOnHA() throws Exception { ApplicationAttemptReport report = client.getApplicationAttemptReport(cluster .createFakeApplicationAttemptId()); - Assert.assertTrue(report != null); - Assert.assertEquals(cluster.createFakeApplicationAttemptReport(), report); + assertTrue(report != null); + assertEquals(cluster.createFakeApplicationAttemptReport(), report); } @Test public void testGetApplicationAttemptsOnHA() throws Exception { List reports = client.getApplicationAttempts(cluster.createFakeAppId()); - Assert.assertTrue(reports != null); - Assert.assertFalse(reports.isEmpty()); - Assert.assertEquals(cluster.createFakeApplicationAttemptReports(), + assertTrue(reports != null); + assertFalse(reports.isEmpty()); + assertEquals(cluster.createFakeApplicationAttemptReports(), reports); } @@ -154,17 +153,17 @@ public void testGetApplicationAttemptsOnHA() throws Exception { public void testGetContainerReportOnHA() throws Exception { ContainerReport report = client.getContainerReport(cluster.createFakeContainerId()); - Assert.assertTrue(report != null); - Assert.assertEquals(cluster.createFakeContainerReport(), report); + assertTrue(report != null); + assertEquals(cluster.createFakeContainerReport(), report); } @Test public void testGetContainersOnHA() throws Exception { List reports = client.getContainers(cluster.createFakeApplicationAttemptId()); - Assert.assertTrue(reports != null); - Assert.assertFalse(reports.isEmpty()); - Assert.assertEquals(cluster.createFakeContainerReports(), + assertTrue(reports != null); + assertFalse(reports.isEmpty()); + assertEquals(cluster.createFakeContainerReports(), reports); } @@ -181,7 +180,7 @@ public void testSubmitApplicationOnHA() throws Exception { capability.setVirtualCores(1); appContext.setResource(capability); ApplicationId appId = client.submitApplication(appContext); - Assert.assertTrue(getActiveRM().getRMContext().getRMApps() + assertTrue(getActiveRM().getRMContext().getRMApps() .containsKey(appId)); } @@ -198,7 +197,7 @@ public void testForceKillApplicationOnHA() throws Exception { @Test public void testGetDelegationTokenOnHA() throws Exception { Token token = client.getRMDelegationToken(new Text(" ")); - Assert.assertEquals(token, cluster.createFakeToken()); + assertEquals(token, cluster.createFakeToken()); } @Test @@ -208,7 +207,7 @@ public void testRenewDelegationTokenOnHA() throws Exception { long newExpirationTime = ClientRMProxy.createRMProxy(this.conf, ApplicationClientProtocol.class) .renewDelegationToken(request).getNextExpirationTime(); - Assert.assertEquals(newExpirationTime, cluster.createNextExpirationTime()); + assertEquals(newExpirationTime, cluster.createNextExpirationTime()); } @Test diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolForTimelineV2.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolForTimelineV2.java index 6daf52f354606..c215537119bf5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolForTimelineV2.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolForTimelineV2.java @@ -21,7 +21,6 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.concurrent.TimeUnit; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; import org.apache.hadoop.yarn.api.records.ContainerId; @@ -32,20 +31,21 @@ import org.apache.hadoop.yarn.server.resourcemanager.HATestUtil; import org.apache.hadoop.yarn.server.timelineservice.storage.FileSystemTimelineWriterImpl; import org.apache.hadoop.yarn.server.timelineservice.storage.TimelineWriter; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Tests Application Master Protocol with timeline service v2 enabled. */ +@Timeout(180) public class TestApplicationMasterServiceProtocolForTimelineV2 extends ApplicationMasterServiceProtoTestBase { - public Timeout timeout = new Timeout(180, TimeUnit.SECONDS); - - @Before + @BeforeEach public void initialize() throws Exception { HATestUtil.setRpcAddressForRM(RM1_NODE_ID, RM1_PORT_BASE + 200, conf); HATestUtil.setRpcAddressForRM(RM2_NODE_ID, RM2_PORT_BASE + 200, conf); @@ -66,10 +66,10 @@ public void testAllocateForTimelineV2OnHA() ResourceBlacklistRequest.newInstance(new ArrayList(), new ArrayList())); AllocateResponse response = getAMClient().allocate(request); - Assert.assertEquals(response, this.cluster.createFakeAllocateResponse()); - Assert.assertNotNull(response.getCollectorInfo()); - Assert.assertEquals("host:port", + assertEquals(response, this.cluster.createFakeAllocateResponse()); + assertNotNull(response.getCollectorInfo()); + assertEquals("host:port", response.getCollectorInfo().getCollectorAddr()); - Assert.assertNotNull(response.getCollectorInfo().getCollectorToken()); + assertNotNull(response.getCollectorInfo().getCollectorToken()); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolOnHA.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolOnHA.java index 0309c6321a855..006ca4063ab41 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolOnHA.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestApplicationMasterServiceProtocolOnHA.java @@ -21,8 +21,6 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.concurrent.TimeUnit; -import org.junit.Assert; import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; @@ -35,18 +33,17 @@ import org.apache.hadoop.yarn.api.records.ResourceBlacklistRequest; import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.exceptions.YarnException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import static org.junit.jupiter.api.Assertions.assertEquals; +@Timeout(180) public class TestApplicationMasterServiceProtocolOnHA extends ApplicationMasterServiceProtoTestBase { - @Rule - public Timeout timeout = new Timeout(180, TimeUnit.SECONDS); - @Before + @BeforeEach public void initialize() throws Exception { startHACluster(0, false, false, true); super.startupHAAndSetupClient(); @@ -59,7 +56,7 @@ public void testRegisterApplicationMasterOnHA() throws YarnException, RegisterApplicationMasterRequest.newInstance("localhost", 0, ""); RegisterApplicationMasterResponse response = getAMClient().registerApplicationMaster(request); - Assert.assertEquals(response, + assertEquals(response, this.cluster.createFakeRegisterApplicationMasterResponse()); } @@ -71,7 +68,7 @@ public void testFinishApplicationMasterOnHA() throws YarnException, FinalApplicationStatus.SUCCEEDED, "", ""); FinishApplicationMasterResponse response = getAMClient().finishApplicationMaster(request); - Assert.assertEquals(response, + assertEquals(response, this.cluster.createFakeFinishApplicationMasterResponse()); } @@ -83,6 +80,6 @@ public void testAllocateOnHA() throws YarnException, IOException { ResourceBlacklistRequest.newInstance(new ArrayList(), new ArrayList())); AllocateResponse response = getAMClient().allocate(request); - Assert.assertEquals(response, this.cluster.createFakeAllocateResponse()); + assertEquals(response, this.cluster.createFakeAllocateResponse()); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestFederationRMFailoverProxyProvider.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestFederationRMFailoverProxyProvider.java index 11a93076dea35..165569df4c736 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestFederationRMFailoverProxyProvider.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestFederationRMFailoverProxyProvider.java @@ -44,11 +44,13 @@ import org.apache.hadoop.yarn.server.federation.utils.FederationStateStoreFacade; import org.apache.hadoop.yarn.server.resourcemanager.HATestUtil; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; @@ -68,7 +70,7 @@ public class TestFederationRMFailoverProxyProvider { private GetClusterMetricsResponse threadResponse; - @Before + @BeforeEach public void setUp() throws IOException, YarnException { conf = new YarnConfiguration(); @@ -82,18 +84,20 @@ public void setUp() throws IOException, YarnException { .getSubClusters(any(GetSubClustersInfoRequest.class)); } - @After + @AfterEach public void tearDown() throws Exception { stateStore.close(); stateStore = null; } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testFederationRMFailoverProxyProvider() throws Exception { testProxyProvider(true); } - @Test (timeout=60000) + @Test + @Timeout(value = 60) public void testFederationRMFailoverProxyProviderWithoutFlushFacadeCache() throws Exception { testProxyProvider(false); @@ -203,8 +207,8 @@ public void run() { } private void checkResponse(GetClusterMetricsResponse response) { - Assert.assertNotNull(response.getClusterMetrics()); - Assert.assertEquals(0, + assertNotNull(response.getClusterMetrics()); + assertEquals(0, response.getClusterMetrics().getNumActiveNodeManagers()); } @@ -267,7 +271,7 @@ public Object run() { }); final ProxyInfo currentProxy = provider.getProxy(); - Assert.assertEquals("user1", provider.getLastProxyUGI().getUserName()); + assertEquals("user1", provider.getLastProxyUGI().getUserName()); user2.doAs(new PrivilegedExceptionAction() { @Override @@ -276,7 +280,7 @@ public Object run() { return null; } }); - Assert.assertEquals("user1", provider.getLastProxyUGI().getUserName()); + assertEquals("user1", provider.getLastProxyUGI().getUserName()); provider.close(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestHedgingRequestRMFailoverProxyProvider.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestHedgingRequestRMFailoverProxyProvider.java index b55cad8e686db..f0aedf622ec76 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestHedgingRequestRMFailoverProxyProvider.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestHedgingRequestRMFailoverProxyProvider.java @@ -28,8 +28,10 @@ import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.MiniYARNCluster; import org.apache.hadoop.yarn.server.resourcemanager.HATestUtil; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class TestHedgingRequestRMFailoverProxyProvider { @@ -73,7 +75,7 @@ public void testHedgingRequestProxyProvider() throws Exception { long end = System.currentTimeMillis(); System.out.println("Client call succeeded at " + end); // should return the response fast - Assert.assertTrue(end - start <= 10000); + assertTrue(end - start <= 10000); // transition rm5 to standby cluster.getResourceManager(4).getRMContext().getRMAdminService() @@ -92,15 +94,15 @@ private void validateActiveRM(YarnClient client) throws IOException { try { // client will retry until the rm becomes active. client.getApplicationReport(null); - Assert.fail(); + fail(); } catch (YarnException e) { - Assert.assertTrue(e instanceof ApplicationNotFoundException); + assertTrue(e instanceof ApplicationNotFoundException); } // now make a valid call. try { client.getAllQueues(); } catch (YarnException e) { - Assert.fail(e.toString()); + fail(e.toString()); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestMemoryPageUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestMemoryPageUtils.java index 4783c73d669e0..b25617233253a 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestMemoryPageUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestMemoryPageUtils.java @@ -18,12 +18,12 @@ package org.apache.hadoop.yarn.client; import org.apache.hadoop.yarn.client.util.MemoryPageUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * The purpose of this class is to test diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestNoHaRMFailoverProxyProvider.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestNoHaRMFailoverProxyProvider.java index fb9c65b6c2bb7..f6de0d5b01f85 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestNoHaRMFailoverProxyProvider.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestNoHaRMFailoverProxyProvider.java @@ -24,8 +24,8 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.server.MiniYARNCluster; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.Closeable; import java.io.IOException; @@ -34,7 +34,8 @@ import java.net.InetSocketAddress; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.times; @@ -65,7 +66,7 @@ public void close() throws IOException { } } - @Before + @BeforeEach public void setUp() throws IOException, YarnException { conf = new YarnConfiguration(); } @@ -87,9 +88,8 @@ public void testRestartedRM() throws Exception { rmClient.init(yarnConf); rmClient.start(); List nodeReports = rmClient.getNodeReports(); - assertEquals( - "The proxy didn't get expected number of node reports", - NUMNODEMANAGERS, nodeReports.size()); + assertEquals(NUMNODEMANAGERS, nodeReports.size(), + "The proxy didn't get expected number of node reports"); } finally { if (rmClient != null) { rmClient.stop(); @@ -118,9 +118,8 @@ public void testConnectingToRM() throws Exception { rmClient.init(yarnConf); rmClient.start(); List nodeReports = rmClient.getNodeReports(); - assertEquals( - "The proxy didn't get expected number of node reports", - NUMNODEMANAGERS, nodeReports.size()); + assertEquals(NUMNODEMANAGERS, nodeReports.size(), + "The proxy didn't get expected number of node reports"); } finally { if (rmClient != null) { rmClient.stop(); @@ -155,23 +154,20 @@ public void testDefaultFPPGetOneProxy() throws Exception { // Initialize failover proxy provider and get proxy from it. fpp.init(conf, mockRMProxy, protocol); FailoverProxyProvider.ProxyInfo actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // Invoke fpp.getProxy() multiple times and // validate the returned proxy is always mockProxy1 actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // verify that mockRMProxy.getProxy() is invoked once only. verify(mockRMProxy, times(1)) @@ -181,9 +177,9 @@ public void testDefaultFPPGetOneProxy() throws Exception { // Perform Failover and get proxy again from failover proxy provider fpp.performFailover(actualProxy1.proxy); FailoverProxyProvider.ProxyInfo actualProxy2 = fpp.getProxy(); - assertEquals("AutoRefreshRMFailoverProxyProvider " + - "doesn't generate expected proxy after failover", - mockProxy1, actualProxy2.proxy); + assertEquals(mockProxy1, actualProxy2.proxy, + "AutoRefreshRMFailoverProxyProvider " + + "doesn't generate expected proxy after failover"); // verify that mockRMProxy.getProxy() didn't get invoked again after // performFailover() @@ -225,23 +221,20 @@ public void testAutoRefreshIPChange() throws Exception { // Initialize proxy provider and get proxy from it. fpp.init(conf, mockRMProxy, protocol); FailoverProxyProvider.ProxyInfo actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // Invoke fpp.getProxy() multiple times and // validate the returned proxy is always mockProxy1 actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // verify that mockRMProxy.getProxy() is invoked once only. verify(mockRMProxy, times(1)) @@ -260,13 +253,13 @@ public void testAutoRefreshIPChange() throws Exception { // Perform Failover and get proxy again from failover proxy provider fpp.performFailover(actualProxy1.proxy); FailoverProxyProvider.ProxyInfo actualProxy2 = fpp.getProxy(); - assertEquals("AutoRefreshNoHARMFailoverProxyProvider " + - "doesn't generate expected proxy after failover", - mockProxy2, actualProxy2.proxy); + assertEquals(mockProxy2, actualProxy2.proxy, + "AutoRefreshNoHARMFailoverProxyProvider " + + "doesn't generate expected proxy after failover"); // check the proxy is different with the one we created before. - assertNotEquals("AutoRefreshNoHARMFailoverProxyProvider " + - "shouldn't generate same proxy after failover", - actualProxy1.proxy, actualProxy2.proxy); + assertNotEquals(actualProxy1.proxy, actualProxy2.proxy, + "AutoRefreshNoHARMFailoverProxyProvider " + + "shouldn't generate same proxy after failover"); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestRMFailoverProxyProvider.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestRMFailoverProxyProvider.java index 25bd7a2200c7e..1ad4ef0713281 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestRMFailoverProxyProvider.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestRMFailoverProxyProvider.java @@ -23,8 +23,8 @@ import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.Closeable; import java.io.IOException; @@ -33,9 +33,9 @@ import java.net.InetSocketAddress; import java.util.concurrent.atomic.AtomicInteger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.times; @@ -68,7 +68,7 @@ public void close() throws IOException { } } - @Before + @BeforeEach public void setUp() throws IOException, YarnException { conf = new YarnConfiguration(); conf.setClass(YarnConfiguration.CLIENT_FAILOVER_NO_HA_PROXY_PROVIDER, @@ -110,23 +110,20 @@ public void testFailoverChange() throws Exception { // Initialize failover proxy provider and get proxy from it. fpp.init(conf, mockRMProxy, protocol); FailoverProxyProvider.ProxyInfo actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "ConfiguredRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // Invoke fpp.getProxy() multiple times and // validate the returned proxy is always mockProxy1 actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "ConfiguredRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "ConfiguredRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // verify that mockRMProxy.getProxy() is invoked once only. verify(mockRMProxy, times(1)) @@ -145,14 +142,14 @@ public void testFailoverChange() throws Exception { // Perform Failover and get proxy again from failover proxy provider fpp.performFailover(actualProxy1.proxy); FailoverProxyProvider.ProxyInfo actualProxy2 = fpp.getProxy(); - assertEquals("ConfiguredRMFailoverProxyProvider " + - "doesn't generate expected proxy after failover", - mockProxy2, actualProxy2.proxy); + assertEquals(mockProxy2, actualProxy2.proxy, + "ConfiguredRMFailoverProxyProvider " + + "doesn't generate expected proxy after failover"); // check the proxy is different with the one we created before. - assertNotEquals("ConfiguredRMFailoverProxyProvider " + - "shouldn't generate same proxy after failover", - actualProxy1.proxy, actualProxy2.proxy); + assertNotEquals(actualProxy1.proxy, actualProxy2.proxy, + "ConfiguredRMFailoverProxyProvider " + + "shouldn't generate same proxy after failover"); // verify that mockRMProxy.getProxy() has been one with each address verify(mockRMProxy, times(1)) @@ -175,9 +172,9 @@ public void testFailoverChange() throws Exception { FailoverProxyProvider.ProxyInfo actualProxy3 = fpp.getProxy(); // check the proxy is the same as the one we created before. - assertEquals("ConfiguredRMFailoverProxyProvider " + - "doesn't generate expected proxy after failover", - mockProxy1, actualProxy3.proxy); + assertEquals(mockProxy1, actualProxy3.proxy, + "ConfiguredRMFailoverProxyProvider " + + "doesn't generate expected proxy after failover"); // verify that mockRMProxy.getProxy() has still only been invoked twice verify(mockRMProxy, times(1)) @@ -228,23 +225,20 @@ public void testAutoRefreshFailoverChange() throws Exception { // Initialize failover proxy provider and get proxy from it. fpp.init(conf, mockRMProxy, protocol); FailoverProxyProvider.ProxyInfo actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // Invoke fpp.getProxy() multiple times and // validate the returned proxy is always mockProxy1 actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); actualProxy1 = fpp.getProxy(); - assertEquals( + assertEquals(mockProxy1, actualProxy1.proxy, "AutoRefreshRMFailoverProxyProvider doesn't generate " + - "expected proxy", - mockProxy1, actualProxy1.proxy); + "expected proxy"); // verify that mockRMProxy.getProxy() is invoked once only. verify(mockRMProxy, times(1)) @@ -263,14 +257,14 @@ public void testAutoRefreshFailoverChange() throws Exception { // Perform Failover and get proxy again from failover proxy provider fpp.performFailover(actualProxy1.proxy); FailoverProxyProvider.ProxyInfo actualProxy2 = fpp.getProxy(); - assertEquals("AutoRefreshRMFailoverProxyProvider " + - "doesn't generate expected proxy after failover", - mockProxy2, actualProxy2.proxy); + assertEquals(mockProxy2, actualProxy2.proxy, + "AutoRefreshRMFailoverProxyProvider " + + "doesn't generate expected proxy after failover"); // check the proxy is different with the one we created before. - assertNotEquals("AutoRefreshRMFailoverProxyProvider " + - "shouldn't generate same proxy after failover", - actualProxy1.proxy, actualProxy2.proxy); + assertNotEquals(actualProxy1.proxy, actualProxy2.proxy, + "AutoRefreshRMFailoverProxyProvider " + + "shouldn't generate same proxy after failover"); // verify that mockRMProxy.getProxy() has been one with each address verify(mockRMProxy, times(1)) @@ -293,9 +287,9 @@ public void testAutoRefreshFailoverChange() throws Exception { FailoverProxyProvider.ProxyInfo actualProxy3 = fpp.getProxy(); // check the proxy is the same as the one we created before. - assertEquals("ConfiguredRMFailoverProxyProvider " + - "doesn't generate expected proxy after failover", - mockProxy1, actualProxy3.proxy); + assertEquals(mockProxy1, actualProxy3.proxy, + "ConfiguredRMFailoverProxyProvider " + + "doesn't generate expected proxy after failover"); // verify that mockRMProxy.getProxy() is still only been invoked thrice verify(mockRMProxy, times(1)) diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceManagerAdministrationProtocolPBClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceManagerAdministrationProtocolPBClientImpl.java index 08a6e0c78ec9e..dfdd8aa53fa29 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceManagerAdministrationProtocolPBClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceManagerAdministrationProtocolPBClientImpl.java @@ -47,14 +47,14 @@ import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceResponse; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test ResourceManagerAdministrationProtocolPBClientImpl. Test a methods and the proxy without logic. @@ -72,7 +72,7 @@ public class TestResourceManagerAdministrationProtocolPBClientImpl { * Start resource manager server */ - @BeforeClass + @BeforeAll public static void setUpResourceManager() throws IOException, InterruptedException { Configuration.addDefaultResource("config-with-security.xml"); @@ -104,7 +104,7 @@ public void run() { }.start(); boolean rmStarted = rmStartedSignal.await(60000L, TimeUnit.MILLISECONDS); - Assert.assertTrue("ResourceManager failed to start up.", rmStarted); + assertTrue(rmStarted, "ResourceManager failed to start up."); LOG.info("ResourceManager RMAdmin address: {}.", configuration.get(YarnConfiguration.RM_ADMIN_ADDRESS)); @@ -197,7 +197,7 @@ public void testRefreshServiceAcls() throws Exception { * Stop server */ - @AfterClass + @AfterAll public static void tearDownResourceManager() throws InterruptedException { if (resourceManager != null) { LOG.info("Stopping ResourceManager..."); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceTrackerOnHA.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceTrackerOnHA.java index e3f86fc4715ea..b6e5e5df8e1df 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceTrackerOnHA.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestResourceTrackerOnHA.java @@ -20,9 +20,7 @@ import java.io.IOException; -import java.util.concurrent.TimeUnit; import org.apache.hadoop.test.GenericTestUtils; -import org.junit.Assert; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.yarn.api.records.NodeId; @@ -33,26 +31,25 @@ import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; import org.apache.hadoop.yarn.server.api.records.NodeStatus; import org.apache.hadoop.yarn.util.YarnVersionInfo; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Timeout(180) public class TestResourceTrackerOnHA extends ProtocolHATestBase { private ResourceTracker resourceTracker = null; - @Rule - public Timeout timeout = new Timeout(180, TimeUnit.SECONDS); - - @Before + @BeforeEach public void initiate() throws Exception { startHACluster(0, false, true, false); this.resourceTracker = getRMClient(); } - @After + @AfterEach public void shutDown() { if(this.resourceTracker != null) { RPC.stopProxy(this.resourceTracker); @@ -69,7 +66,7 @@ public void testResourceTrackerOnHA() throws Exception { RegisterNodeManagerRequest.newInstance(nodeId, 0, resource, YarnVersionInfo.getVersion(), null, null); resourceTracker.registerNodeManager(request); - Assert.assertTrue(waitForNodeManagerToConnect(200, nodeId)); + assertTrue(waitForNodeManagerToConnect(200, nodeId)); // restart the failover thread, and make sure nodeHeartbeat works failoverThread = createAndStartFailoverThread(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestYarnApiClasses.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestYarnApiClasses.java index 0e3bc877ab542..f8caf73d2e995 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestYarnApiClasses.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestYarnApiClasses.java @@ -28,9 +28,13 @@ import org.apache.hadoop.yarn.api.records.ResourceRequest; import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestYarnApiClasses { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestAMRMClientAsync.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestAMRMClientAsync.java index 3cd4414c9373e..4f4bf32f326c0 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestAMRMClientAsync.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestAMRMClientAsync.java @@ -19,6 +19,8 @@ package org.apache.hadoop.yarn.client.api.async.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyFloat; import static org.mockito.ArgumentMatchers.anyInt; @@ -57,8 +59,8 @@ import org.apache.hadoop.yarn.exceptions.ApplicationAttemptNotFoundException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; @@ -71,7 +73,8 @@ public class TestAMRMClientAsync { LoggerFactory.getLogger(TestAMRMClientAsync.class); @SuppressWarnings("unchecked") - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testAMRMClientAsync() throws Exception { Configuration conf = new Configuration(); final AtomicBoolean heartbeatBlock = new AtomicBoolean(true); @@ -147,11 +150,11 @@ public Resource answer(InvocationOnMock invocation) } // allocated containers should come before completed containers - Assert.assertEquals(null, callbackHandler.takeCompletedContainers()); + assertNull(callbackHandler.takeCompletedContainers()); // wait for the allocated containers from the first heartbeat's response while (callbackHandler.takeAllocatedContainers() == null) { - Assert.assertEquals(null, callbackHandler.takeCompletedContainers()); + assertNull(callbackHandler.takeCompletedContainers()); Thread.sleep(10); } @@ -166,13 +169,14 @@ public Resource answer(InvocationOnMock invocation) } asyncClient.stop(); - - Assert.assertEquals(null, callbackHandler.takeAllocatedContainers()); - Assert.assertEquals(null, callbackHandler.takeCompletedContainers()); - Assert.assertEquals(null, callbackHandler.takeChangedContainers()); + + assertNull(callbackHandler.takeAllocatedContainers()); + assertNull(callbackHandler.takeCompletedContainers()); + assertNull(callbackHandler.takeChangedContainers()); } - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testAMRMClientAsyncException() throws Exception { String exStr = "TestException"; YarnException mockException = mock(YarnException.class); @@ -180,7 +184,8 @@ public void testAMRMClientAsyncException() throws Exception { runHeartBeatThrowOutException(mockException); } - @Test(timeout=10000) + @Test + @Timeout(value = 10) public void testAMRMClientAsyncRunTimeException() throws Exception { String exStr = "TestRunTimeException"; RuntimeException mockRunTimeException = mock(RuntimeException.class); @@ -210,23 +215,23 @@ private void runHeartBeatThrowOutException(Exception ex) throws Exception{ } } } - Assert.assertTrue(callbackHandler.savedException.getMessage().contains( + assertTrue(callbackHandler.savedException.getMessage().contains( ex.getMessage())); asyncClient.stop(); // stopping should have joined all threads and completed all callbacks - Assert.assertTrue(callbackHandler.callbackCount > 0); + assertTrue(callbackHandler.callbackCount > 0); } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testAMRMClientAsyncShutDown() throws Exception { Configuration conf = new Configuration(); TestCallbackHandler callbackHandler = new TestCallbackHandler(); @SuppressWarnings("unchecked") AMRMClient client = mock(AMRMClientImpl.class); - createAllocateResponse(new ArrayList(), - new ArrayList(), null); + createAllocateResponse(new ArrayList<>(), new ArrayList<>(), null); when(client.allocate(anyFloat())).thenThrow( new ApplicationAttemptNotFoundException("app not found, shut down")); @@ -243,7 +248,8 @@ public void testAMRMClientAsyncShutDown() throws Exception { asyncClient.stop(); } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testAMRMClientAsyncShutDownWithWaitFor() throws Exception { Configuration conf = new Configuration(); final TestCallbackHandler callbackHandler = new TestCallbackHandler(); @@ -269,13 +275,14 @@ public Boolean get() { asyncClient.stop(); // stopping should have joined all threads and completed all callbacks - Assert.assertTrue(callbackHandler.callbackCount == 0); + assertTrue(callbackHandler.callbackCount == 0); verify(client, times(1)).allocate(anyFloat()); asyncClient.stop(); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testCallAMRMClientAsyncStopFromCallbackHandler() throws YarnException, IOException, InterruptedException { Configuration conf = new Configuration(); @@ -309,7 +316,8 @@ public void testCallAMRMClientAsyncStopFromCallbackHandler() } } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testCallAMRMClientAsyncStopFromCallbackHandlerWithWaitFor() throws YarnException, IOException, InterruptedException { Configuration conf = new Configuration(); @@ -340,7 +348,7 @@ public Boolean get() { asyncClient.registerApplicationMaster("localhost", 1234, null); asyncClient.waitFor(checker); - Assert.assertTrue(checker.get()); + assertTrue(checker.get()); } void runCallBackThrowOutException(TestCallbackHandler2 callbackHandler) throws @@ -385,7 +393,8 @@ void runCallBackThrowOutException(TestCallbackHandler2 callbackHandler) throws verify(callbackHandler, times(1)).onError(any(Exception.class)); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testCallBackThrowOutException() throws YarnException, IOException, InterruptedException { // test exception in callback with app calling stop() on app.onError() @@ -393,7 +402,8 @@ public void testCallBackThrowOutException() throws YarnException, runCallBackThrowOutException(callbackHandler); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testCallBackThrowOutExceptionNoStop() throws YarnException, IOException, InterruptedException { // test exception in callback with app not calling stop() on app.onError() diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestNMClientAsync.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestNMClientAsync.java index 40038b1cabe5c..1a8b8f5040362 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestNMClientAsync.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/async/impl/TestNMClientAsync.java @@ -18,6 +18,9 @@ package org.apache.hadoop.yarn.client.api.async.impl; +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.anyBoolean; import static org.mockito.Mockito.doNothing; @@ -41,7 +44,6 @@ import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.util.Records; -import org.junit.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.service.ServiceOperations; @@ -60,8 +62,9 @@ import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; import org.apache.hadoop.yarn.ipc.RPCUtil; -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; public class TestNMClientAsync { @@ -89,12 +92,13 @@ private TestData(int expectedSuccess, int expectedFailure) { } } - @After + @AfterEach public void teardown() { ServiceOperations.stop(asyncClient); } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testNMClientAsync() throws Exception { Configuration conf = new Configuration(); conf.setInt(YarnConfiguration.NM_CLIENT_ASYNC_THREAD_POOL_MAX_SIZE, 10); @@ -105,8 +109,8 @@ public void testNMClientAsync() throws Exception { asyncClient = new MockNMClientAsync1(expectedSuccess, expectedFailure); asyncClient.init(conf); - Assert.assertEquals("The max thread pool size is not correctly set", - 10, asyncClient.maxThreadPoolSize); + assertEquals(10, asyncClient.maxThreadPoolSize, + "The max thread pool size is not correctly set"); asyncClient.start(); @@ -149,25 +153,24 @@ public void testNMClientAsync() throws Exception { .errorMsgs) { System.out.println(errorMsg); } - Assert.assertEquals("Error occurs in CallbackHandler", 0, + assertEquals(0, ((TestCallbackHandler1) asyncClient.getCallbackHandler()) - .errorMsgs.size()); + .errorMsgs.size(), "Error occurs in CallbackHandler"); for (String errorMsg : ((MockNMClientAsync1) asyncClient).errorMsgs) { System.out.println(errorMsg); } - Assert.assertEquals("Error occurs in ContainerEventProcessor", 0, - ((MockNMClientAsync1) asyncClient).errorMsgs.size()); + assertEquals(0, ((MockNMClientAsync1) asyncClient).errorMsgs.size(), + "Error occurs in ContainerEventProcessor"); // When the callback functions are all executed, the event processor threads // may still not terminate and the containers may still not removed. while (asyncClient.containers.size() > 0) { Thread.sleep(10); } asyncClient.stop(); - Assert.assertFalse( - "The thread of Container Management Event Dispatcher is still alive", - asyncClient.eventDispatcherThread.isAlive()); - Assert.assertTrue("The thread pool is not shut down", - asyncClient.threadPool.isShutdown()); + assertFalse(asyncClient.eventDispatcherThread.isAlive(), + "The thread of Container Management Event Dispatcher is still alive"); + assertTrue(asyncClient.threadPool.isShutdown(), + "The thread pool is not shut down"); } private class MockNMClientAsync1 extends NMClientAsyncImpl { @@ -697,7 +700,7 @@ public boolean isStopFailureCallsExecuted() { private void assertAtomicIntegerArray(AtomicIntegerArray array) { for (int i = 0; i < array.length(); ++i) { - Assert.assertEquals(1, array.get(i)); + assertEquals(1, array.get(i)); } } } @@ -764,7 +767,8 @@ private NMClient mockNMClient(int mode) return client; } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testOutOfOrder() throws Exception { CyclicBarrier barrierA = new CyclicBarrier(2); CyclicBarrier barrierB = new CyclicBarrier(2); @@ -790,9 +794,8 @@ public void run() { asyncClient.stopContainerAsync(container.getId(), container.getNodeId()); barrierC.await(); - Assert.assertFalse("Starting and stopping should be out of order", - ((TestCallbackHandler2) asyncClient.getCallbackHandler()) - .exceptionOccurred.get()); + assertFalse(((TestCallbackHandler2) asyncClient.getCallbackHandler()) + .exceptionOccurred.get(), "Starting and stopping should be out of order"); } private class MockNMClientAsync2 extends NMClientAsyncImpl { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/BaseAMRMClientTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/BaseAMRMClientTest.java index 382a119cde406..beafbdb62cf6a 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/BaseAMRMClientTest.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/BaseAMRMClientTest.java @@ -43,8 +43,8 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import java.io.IOException; import java.nio.ByteBuffer; @@ -53,8 +53,8 @@ import java.util.HashMap; import java.util.List; -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; /** * Base class for testing AMRMClient. @@ -83,7 +83,7 @@ public class BaseAMRMClientTest { protected String[] nodes; protected String[] racks; - @Before + @BeforeEach public void setup() throws Exception { conf = new YarnConfiguration(); createClusterAndStartApplication(conf); @@ -120,12 +120,12 @@ protected void createClusterAndStartApplication(Configuration conf) yarnClient.start(); // get node info - assertTrue("All node managers did not connect to the RM within the " - + "allotted 5-second timeout", - yarnCluster.waitForNodeManagersToConnect(5000L)); + assertTrue(yarnCluster.waitForNodeManagersToConnect(5000L), + "All node managers did not connect to the RM within the " + + "allotted 5-second timeout"); nodeReports = yarnClient.getNodeReports(NodeState.RUNNING); - assertEquals("Not all node managers were reported running", - nodeCount, nodeReports.size()); + assertEquals(nodeCount, nodeReports.size(), + "Not all node managers were reported running"); priority = Priority.newInstance(1); priority2 = Priority.newInstance(2); @@ -194,7 +194,7 @@ Collections. emptyMap(), ClientRMProxy.getAMRMTokenService(conf)); } - @After + @AfterEach public void teardown() throws YarnException, IOException { if (yarnClient != null && attemptId != null) { yarnClient.killApplication(attemptId.getApplicationId()); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSClient.java index dcb8a17d36774..ed4ea604f59ed 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSClient.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSClient.java @@ -19,6 +19,9 @@ package org.apache.hadoop.yarn.client.api.impl; 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.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -28,8 +31,6 @@ import java.util.HashMap; import java.util.List; -import org.junit.Assert; - import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.ApplicationHistoryProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportRequest; @@ -58,7 +59,8 @@ import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.client.api.AHSClient; import org.apache.hadoop.yarn.exceptions.YarnException; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; public class TestAHSClient { @@ -71,7 +73,8 @@ public void testClientStop() { client.stop(); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGetApplications() throws YarnException, IOException { Configuration conf = new Configuration(); final AHSClient client = new MockAHSClient(); @@ -82,14 +85,15 @@ public void testGetApplications() throws YarnException, IOException { ((MockAHSClient) client).getReports(); List reports = client.getApplications(); - Assert.assertEquals(reports, expectedReports); + assertEquals(reports, expectedReports); reports = client.getApplications(); assertThat(reports).hasSize(4); client.stop(); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGetApplicationReport() throws YarnException, IOException { Configuration conf = new Configuration(); final AHSClient client = new MockAHSClient(); @@ -100,15 +104,16 @@ public void testGetApplicationReport() throws YarnException, IOException { ((MockAHSClient) client).getReports(); ApplicationId applicationId = ApplicationId.newInstance(1234, 5); ApplicationReport report = client.getApplicationReport(applicationId); - Assert.assertEquals(report, expectedReports.get(0)); - Assert.assertEquals(report.getApplicationId().toString(), expectedReports + assertEquals(report, expectedReports.get(0)); + assertEquals(report.getApplicationId().toString(), expectedReports .get(0).getApplicationId().toString()); - Assert.assertEquals(report.getSubmitTime(), expectedReports.get(0) + assertEquals(report.getSubmitTime(), expectedReports.get(0) .getSubmitTime()); client.stop(); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGetApplicationAttempts() throws YarnException, IOException { Configuration conf = new Configuration(); final AHSClient client = new MockAHSClient(); @@ -118,15 +123,16 @@ public void testGetApplicationAttempts() throws YarnException, IOException { ApplicationId applicationId = ApplicationId.newInstance(1234, 5); List reports = client.getApplicationAttempts(applicationId); - Assert.assertNotNull(reports); - Assert.assertEquals(reports.get(0).getApplicationAttemptId(), + assertNotNull(reports); + assertEquals(reports.get(0).getApplicationAttemptId(), ApplicationAttemptId.newInstance(applicationId, 1)); - Assert.assertEquals(reports.get(1).getApplicationAttemptId(), + assertEquals(reports.get(1).getApplicationAttemptId(), ApplicationAttemptId.newInstance(applicationId, 2)); client.stop(); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGetApplicationAttempt() throws YarnException, IOException { Configuration conf = new Configuration(); final AHSClient client = new MockAHSClient(); @@ -141,13 +147,14 @@ public void testGetApplicationAttempt() throws YarnException, IOException { ApplicationAttemptId.newInstance(applicationId, 1); ApplicationAttemptReport report = client.getApplicationAttemptReport(appAttemptId); - Assert.assertNotNull(report); - Assert.assertEquals(report.getApplicationAttemptId().toString(), + assertNotNull(report); + assertEquals(report.getApplicationAttemptId().toString(), expectedReports.get(0).getCurrentApplicationAttemptId().toString()); client.stop(); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGetContainers() throws YarnException, IOException { Configuration conf = new Configuration(); final AHSClient client = new MockAHSClient(); @@ -158,15 +165,16 @@ public void testGetContainers() throws YarnException, IOException { ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(applicationId, 1); List reports = client.getContainers(appAttemptId); - Assert.assertNotNull(reports); - Assert.assertEquals(reports.get(0).getContainerId(), + assertNotNull(reports); + assertEquals(reports.get(0).getContainerId(), (ContainerId.newContainerId(appAttemptId, 1))); - Assert.assertEquals(reports.get(1).getContainerId(), + assertEquals(reports.get(1).getContainerId(), (ContainerId.newContainerId(appAttemptId, 2))); client.stop(); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGetContainerReport() throws YarnException, IOException { Configuration conf = new Configuration(); final AHSClient client = new MockAHSClient(); @@ -181,8 +189,8 @@ public void testGetContainerReport() throws YarnException, IOException { ApplicationAttemptId.newInstance(applicationId, 1); ContainerId containerId = ContainerId.newContainerId(appAttemptId, 1); ContainerReport report = client.getContainerReport(containerId); - Assert.assertNotNull(report); - Assert.assertEquals(report.getContainerId().toString(), (ContainerId + assertNotNull(report); + assertEquals(report.getContainerId().toString(), (ContainerId .newContainerId(expectedReports.get(0).getCurrentApplicationAttemptId(), 1)) .toString()); client.stop(); @@ -240,9 +248,9 @@ public void start() { .thenReturn(mockContainerResponse); } catch (YarnException e) { - Assert.fail("Exception is not expected."); + fail("Exception is not expected."); } catch (IOException e) { - Assert.fail("Exception is not expected."); + fail("Exception is not expected."); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSv2ClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSv2ClientImpl.java index f4d7a5629778a..8d204d903b81b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSv2ClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAHSv2ClientImpl.java @@ -19,6 +19,7 @@ package org.apache.hadoop.yarn.client.api.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,9 +41,8 @@ import org.apache.hadoop.yarn.server.metrics.AppAttemptMetricsConstants; import org.apache.hadoop.yarn.server.metrics.ApplicationMetricsConstants; import org.apache.hadoop.yarn.server.metrics.ContainerMetricsConstants; -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 java.io.IOException; import java.util.HashMap; @@ -57,7 +57,7 @@ public class TestAHSv2ClientImpl { private AHSv2ClientImpl client; private TimelineReaderClient spyTimelineReaderClient; - @Before + @BeforeEach public void setup() { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true); @@ -116,7 +116,7 @@ public void testGetAppReport() throws IOException, YarnException { assertThat(report.getApplicationId()).isEqualTo(appId); assertThat(report.getAppNodeLabelExpression()). isEqualTo("test_node_label"); - Assert.assertTrue(report.getApplicationTags().contains("Test_APP_TAGS_1")); + assertTrue(report.getApplicationTags().contains("Test_APP_TAGS_1")); assertThat(report.getYarnApplicationState()). isEqualTo(YarnApplicationState.FINISHED); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClient.java index 33ceae6629977..2da782ea6db1c 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClient.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClient.java @@ -19,11 +19,14 @@ package org.apache.hadoop.yarn.client.api.impl; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.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.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -77,32 +80,36 @@ import org.apache.hadoop.yarn.server.resourcemanager.security.AMRMTokenSecretManager; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.eclipse.jetty.util.log.Log; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Test application master client class to resource manager. */ -@RunWith(value = Parameterized.class) public class TestAMRMClient extends BaseAMRMClientTest{ private final static int DEFAULT_ITERATION = 15; - public TestAMRMClient(String schedulerName, boolean autoUpdate) { - this.schedulerName = schedulerName; - this.autoUpdate = autoUpdate; + @Override + public void setup() throws Exception { + super.setup(); + } + + public void initTestAMRMClient(String pSchedulerName, boolean pAutoUpdate) + throws Exception { + this.schedulerName = pSchedulerName; + this.autoUpdate = pAutoUpdate; + setup(); } - @Parameterized.Parameters public static Collection data() { // Currently only capacity scheduler supports auto update. return Arrays.asList(new Object[][] { @@ -112,9 +119,12 @@ public static Collection data() { }); } - @Test (timeout = 60000) - public void testAMRMClientNoMatchingRequests() - throws IOException, YarnException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientNoMatchingRequests(String pSchedulerName, boolean pAutoUpdate) + throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClient amClient = AMRMClient.createAMRMClient(); amClient.init(conf); amClient.start(); @@ -123,11 +133,15 @@ public void testAMRMClientNoMatchingRequests() Resource testCapability1 = Resource.newInstance(1024, 2); List> matches = amClient.getMatchingRequests(priority, node, testCapability1); - assertEquals("Expected no matching requests.", matches.size(), 0); + assertEquals(matches.size(), 0, "Expected no matching requests."); } - - @Test (timeout=60000) - public void testAMRMClientMatchingFit() throws YarnException, IOException { + + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientMatchingFit(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClient amClient = null; try { // start am rm client @@ -267,9 +281,12 @@ public void testAMRMClientMatchingFit() throws YarnException, IOException { /** * Test fit of both GUARANTEED and OPPORTUNISTIC containers. */ - @Test (timeout=60000) - public void testAMRMClientMatchingFitExecType() - throws YarnException, IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientMatchingFitExecType(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClient amClient = null; try { // start am rm client @@ -403,10 +420,13 @@ private void verifyMatches( assertEquals(1, matches.size()); assertEquals(matchSize, matches.get(0).size()); } - - @Test (timeout=60000) - public void testAMRMClientMatchingFitInferredRack() - throws YarnException, IOException { + + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientMatchingFitInferredRack(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = null; try { // start am rm client @@ -451,8 +471,11 @@ public void testAMRMClientMatchingFitInferredRack() } } - @Test //(timeout=60000) - public void testAMRMClientMatchStorage() throws YarnException, IOException { + @ParameterizedTest //(timeout=60000) + @MethodSource("data") + public void testAMRMClientMatchStorage(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = null; try { // start am rm client @@ -599,8 +622,12 @@ private void triggerSchedulingWithNMHeartBeat() { } } - @Test (timeout=60000) - public void testAllocationWithBlacklist() throws YarnException, IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAllocationWithBlacklist(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = null; try { // start am rm client @@ -663,9 +690,13 @@ public void testAllocationWithBlacklist() throws YarnException, IOException { } } } - - @Test (timeout=60000) - public void testAMRMClientWithBlacklist() throws YarnException, IOException { + + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientWithBlacklist(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = null; try { // start am rm client @@ -738,21 +769,33 @@ private int getAllocatedContainersNumber( return allocatedContainerCount; } - @Test (timeout=60000) - @Ignore - public void testAMRMClient() throws YarnException, IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + @Disabled + public void testAMRMClient(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); initAMRMClientAndTest(false); } - @Test (timeout=60000) - @Ignore - public void testAMRMClientAllocReqId() throws YarnException, IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + @Disabled + public void testAMRMClientAllocReqId(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); initAMRMClientAndTest(true); } - @Test (timeout=60000) - @Ignore - public void testAMRMClientWithSaslEncryption() throws Exception { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + @Disabled + public void testAMRMClientWithSaslEncryption(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); // we have to create a new instance of MiniYARNCluster to avoid SASL qop // mismatches between client and server teardown(); @@ -772,7 +815,7 @@ protected void initAMRMClientAndTest(boolean useAllocReqId) //setting an instance NMTokenCache amClient.setNMTokenCache(new NMTokenCache()); //asserting we are not using the singleton instance cache - Assert.assertNotSame(NMTokenCache.getSingleton(), + assertNotSame(NMTokenCache.getSingleton(), amClient.getNMTokenCache()); amClient.init(conf); @@ -795,9 +838,13 @@ protected void initAMRMClientAndTest(boolean useAllocReqId) } } } - - @Test(timeout=30000) - public void testAskWithNodeLabels() { + + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 30) + public void testAskWithNodeLabels(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl client = new AMRMClientImpl(); @@ -828,7 +875,7 @@ public void testAskWithNodeLabels() { if (ResourceRequest.ANY.equals(req.getResourceName())) { assertEquals("y", req.getNodeLabelExpression()); } else { - Assert.assertNull(req.getNodeLabelExpression()); + assertNull(req.getNodeLabelExpression()); } } // set container with nodes and racks with labels @@ -839,7 +886,7 @@ public void testAskWithNodeLabels() { if (ResourceRequest.ANY.equals(req.getResourceName())) { assertEquals("y", req.getNodeLabelExpression()); } else { - Assert.assertNull(req.getNodeLabelExpression()); + assertNull(req.getNodeLabelExpression()); } } } @@ -853,9 +900,13 @@ private void verifyAddRequestFailed(AMRMClient client, } fail(); } - - @Test(timeout=30000) - public void testAskWithInvalidNodeLabels() { + + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 30) + public void testAskWithInvalidNodeLabels(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl client = new AMRMClientImpl(); @@ -865,27 +916,30 @@ public void testAskWithInvalidNodeLabels() { Priority.UNDEFINED, true, "x && y")); } - @Test(timeout=60000) - public void testAMRMClientWithContainerResourceChange() - throws YarnException, IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientWithContainerResourceChange(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); // Fair scheduler does not support resource change - Assume.assumeTrue(schedulerName.equals(CapacityScheduler.class.getName())); + assumeTrue(schedulerName.equals(CapacityScheduler.class.getName())); AMRMClient amClient = null; try { // start am rm client amClient = AMRMClient.createAMRMClient(); - Assert.assertNotNull(amClient); + assertNotNull(amClient); // asserting we are using the singleton instance cache - Assert.assertSame( + assertSame( NMTokenCache.getSingleton(), amClient.getNMTokenCache()); amClient.init(conf); amClient.start(); assertEquals(STATE.STARTED, amClient.getServiceState()); // start am nm client NMClientImpl nmClient = (NMClientImpl) NMClient.createNMClient(); - Assert.assertNotNull(nmClient); + assertNotNull(nmClient); // asserting we are using the singleton instance cache - Assert.assertSame( + assertSame( NMTokenCache.getSingleton(), nmClient.getNMTokenCache()); nmClient.init(conf); nmClient.start(); @@ -1040,12 +1094,15 @@ private void assertUpdatedContainers(AMRMClient amClient, Cont } } - Assert.assertEquals("Container resource change update failed", 1, updateResponse.size()); + assertEquals(1, updateResponse.size(), "Container resource change update failed"); } - @Test - public void testAMRMContainerPromotionAndDemotionWithAutoUpdate() + @ParameterizedTest + @MethodSource("data") + public void testAMRMContainerPromotionAndDemotionWithAutoUpdate( + String pSchedulerName, boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = (AMRMClientImpl) AMRMClient .createAMRMClient(); @@ -1054,7 +1111,7 @@ public void testAMRMContainerPromotionAndDemotionWithAutoUpdate() // start am nm client NMClientImpl nmClient = (NMClientImpl) NMClient.createNMClient(); - Assert.assertNotNull(nmClient); + assertNotNull(nmClient); nmClient.init(conf); nmClient.start(); assertEquals(STATE.STARTED, nmClient.getServiceState()); @@ -1176,23 +1233,26 @@ private void waitForNMContextUpdate(UpdatedContainer updatedContainer, } } - @Test(timeout=60000) - public void testAMRMClientWithContainerPromotion() - throws YarnException, IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientWithContainerPromotion( + String pSchedulerName, boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = (AMRMClientImpl) AMRMClient .createAMRMClient(); //asserting we are not using the singleton instance cache - Assert.assertSame(NMTokenCache.getSingleton(), + assertSame(NMTokenCache.getSingleton(), amClient.getNMTokenCache()); amClient.init(conf); amClient.start(); // start am nm client NMClientImpl nmClient = (NMClientImpl) NMClient.createNMClient(); - Assert.assertNotNull(nmClient); + assertNotNull(nmClient); // asserting we are using the singleton instance cache - Assert.assertSame( + assertSame( NMTokenCache.getSingleton(), nmClient.getNMTokenCache()); nmClient.init(conf); nmClient.start(); @@ -1317,22 +1377,25 @@ public void testAMRMClientWithContainerPromotion() amClient.ask.clear(); } - @Test(timeout=60000) - public void testAMRMClientWithContainerDemotion() - throws YarnException, IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientWithContainerDemotion( + String pSchedulerName, boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = (AMRMClientImpl) AMRMClient .createAMRMClient(); //asserting we are not using the singleton instance cache - Assert.assertSame(NMTokenCache.getSingleton(), + assertSame(NMTokenCache.getSingleton(), amClient.getNMTokenCache()); amClient.init(conf); amClient.start(); NMClientImpl nmClient = (NMClientImpl) NMClient.createNMClient(); - Assert.assertNotNull(nmClient); + assertNotNull(nmClient); // asserting we are using the singleton instance cache - Assert.assertSame( + assertSame( NMTokenCache.getSingleton(), nmClient.getNMTokenCache()); nmClient.init(conf); nmClient.start(); @@ -1760,8 +1823,11 @@ public Boolean get() { } }; - @Test - public void testWaitFor() throws InterruptedException { + @ParameterizedTest + @MethodSource("data") + public void testWaitFor(String pSchedulerName, boolean pAutoUpdate) + throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClientImpl amClient = null; CountDownSupplier countDownChecker = new CountDownSupplier(); @@ -1789,9 +1855,12 @@ private void sleep(int sleepTime) { } } - @Test(timeout = 60000) - public void testAMRMClientOnAMRMTokenRollOver() throws YarnException, - IOException { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testAMRMClientOnAMRMTokenRollOver(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); AMRMClient amClient = null; try { AMRMTokenSecretManager amrmTokenSecretManager = @@ -1809,7 +1878,7 @@ public void testAMRMClientOnAMRMTokenRollOver() throws YarnException, org.apache.hadoop.security.token.Token amrmToken_1 = getAMRMToken(); - Assert.assertNotNull(amrmToken_1); + assertNotNull(amrmToken_1); assertEquals(amrmToken_1.decodeIdentifier().getKeyId(), amrmTokenSecretManager.getMasterKey().getMasterKey().getKeyId()); @@ -1824,11 +1893,11 @@ public void testAMRMClientOnAMRMTokenRollOver() throws YarnException, org.apache.hadoop.security.token.Token amrmToken_2 = getAMRMToken(); - Assert.assertNotNull(amrmToken_2); + assertNotNull(amrmToken_2); assertEquals(amrmToken_2.decodeIdentifier().getKeyId(), amrmTokenSecretManager.getMasterKey().getMasterKey().getKeyId()); - Assert.assertNotEquals(amrmToken_1, amrmToken_2); + assertNotEquals(amrmToken_1, amrmToken_2); // can do the allocate call with latest AMRMToken AllocateResponse response = amClient.allocate(0.1f); @@ -1840,8 +1909,8 @@ public void testAMRMClientOnAMRMTokenRollOver() throws YarnException, AMRMTokenIdentifierForTest newVersionTokenIdentifier = new AMRMTokenIdentifierForTest(amrmToken_2.decodeIdentifier(), "message"); - assertEquals("Message is changed after set to newVersionTokenIdentifier", - "message", newVersionTokenIdentifier.getMessage()); + assertEquals("message", newVersionTokenIdentifier.getMessage(), + "Message is changed after set to newVersionTokenIdentifier"); org.apache.hadoop.security.token.Token newVersionToken = new org.apache.hadoop.security.token.Token ( newVersionTokenIdentifier.getBytes(), @@ -1936,8 +2005,12 @@ public ApplicationMasterProtocol run() { return result; } - @Test(timeout = 60000) - public void testGetMatchingFitWithProfiles() throws Exception { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testGetMatchingFitWithProfiles(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); teardown(); conf.setBoolean(YarnConfiguration.RM_RESOURCE_PROFILES_ENABLED, true); createClusterAndStartApplication(conf); @@ -2022,8 +2095,12 @@ public void testGetMatchingFitWithProfiles() throws Exception { } } - @Test(timeout = 60000) - public void testNoUpdateTrackingUrl() { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testNoUpdateTrackingUrl(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); try { AMRMClientImpl amClient = null; amClient = new AMRMClientImpl<>(); @@ -2056,8 +2133,12 @@ public void testNoUpdateTrackingUrl() { } } - @Test(timeout = 60000) - public void testUpdateTrackingUrl() { + @ParameterizedTest + @MethodSource("data") + @Timeout(value = 60) + public void testUpdateTrackingUrl(String pSchedulerName, + boolean pAutoUpdate) throws Exception { + initTestAMRMClient(pSchedulerName, pAutoUpdate); try { AMRMClientImpl amClient = null; amClient = new AMRMClientImpl<>(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientContainerRequest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientContainerRequest.java index 5f775524d6e78..ecac2cefbd82e 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientContainerRequest.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientContainerRequest.java @@ -18,7 +18,8 @@ package org.apache.hadoop.yarn.client.api.impl; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Collections; import java.util.List; @@ -34,7 +35,7 @@ import org.apache.hadoop.yarn.client.api.AMRMClient; import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest; import org.apache.hadoop.yarn.client.api.InvalidContainerRequestException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestAMRMClientContainerRequest { @@ -169,25 +170,26 @@ public void testDisableLocalityRelaxation() { client.addContainerRequest(bothLevelRequest2); } - @Test (expected = InvalidContainerRequestException.class) + @Test public void testDifferentLocalityRelaxationSamePriority() { - AMRMClientImpl client = - new AMRMClientImpl(); - Configuration conf = new Configuration(); - conf.setClass( - CommonConfigurationKeysPublic.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, - MyResolver.class, DNSToSwitchMapping.class); - client.init(conf); - - Resource capability = Resource.newInstance(1024, 1); - ContainerRequest request1 = - new ContainerRequest(capability, new String[] {"host1", "host2"}, - null, Priority.newInstance(1), false); - client.addContainerRequest(request1); - ContainerRequest request2 = - new ContainerRequest(capability, new String[] {"host3"}, - null, Priority.newInstance(1), true); - client.addContainerRequest(request2); + assertThrows(InvalidContainerRequestException.class, ()->{ + AMRMClientImpl client = new AMRMClientImpl(); + Configuration conf = new Configuration(); + conf.setClass( + CommonConfigurationKeysPublic.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, + MyResolver.class, DNSToSwitchMapping.class); + client.init(conf); + + Resource capability = Resource.newInstance(1024, 1); + ContainerRequest request1 = + new ContainerRequest(capability, new String[] {"host1", "host2"}, + null, Priority.newInstance(1), false); + client.addContainerRequest(request1); + ContainerRequest request2 = + new ContainerRequest(capability, new String[] {"host3"}, + null, Priority.newInstance(1), true); + client.addContainerRequest(request2); + }); } @Test @@ -229,25 +231,26 @@ public void testInvalidValidWhenOldRemoved() { } - @Test (expected = InvalidContainerRequestException.class) + @Test public void testLocalityRelaxationDifferentLevels() { - AMRMClientImpl client = - new AMRMClientImpl(); - Configuration conf = new Configuration(); - conf.setClass( - CommonConfigurationKeysPublic.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, - MyResolver.class, DNSToSwitchMapping.class); - client.init(conf); - - Resource capability = Resource.newInstance(1024, 1); - ContainerRequest request1 = - new ContainerRequest(capability, new String[] {"host1", "host2"}, - null, Priority.newInstance(1), false); - client.addContainerRequest(request1); - ContainerRequest request2 = - new ContainerRequest(capability, null, - new String[] {"rack1"}, Priority.newInstance(1), true); - client.addContainerRequest(request2); + assertThrows(InvalidContainerRequestException.class, () -> { + AMRMClientImpl client = + new AMRMClientImpl(); + Configuration conf = new Configuration(); + conf.setClass( + CommonConfigurationKeysPublic.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY, + MyResolver.class, DNSToSwitchMapping.class); + client.init(conf); + + Resource capability = Resource.newInstance(1024, 1); + ContainerRequest request1 = + new ContainerRequest(capability, new String[]{"host1", "host2"}, + null, Priority.newInstance(1), false); + client.addContainerRequest(request1); + ContainerRequest request2 = new ContainerRequest(capability, null, + new String[]{"rack1"}, Priority.newInstance(1), true); + client.addContainerRequest(request2); + }); } private static class MyResolver implements DNSToSwitchMapping { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java index 4adca73a3069e..02edda63f6c6b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java @@ -72,17 +72,21 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler; import org.apache.hadoop.yarn.server.resourcemanager.security.AMRMTokenSecretManager; import org.apache.hadoop.yarn.util.Records; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +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 TestAMRMClientOnRMRestart { static Configuration conf = new Configuration(); static final int rolling_interval_sec = 13; static final long am_expire_ms = 4000; - @BeforeClass + @BeforeAll public static void setup() throws Exception { conf.setBoolean( CommonConfigurationKeys.HADOOP_SECURITY_TOKEN_SERVICE_USE_IP, false); @@ -97,7 +101,7 @@ public static void setup() throws Exception { conf.set(YarnConfiguration.RM_SCHEDULER_ADDRESS, "0.0.0.0:0"); } - @AfterClass + @AfterAll public static void tearDown() { conf.setBoolean( CommonConfigurationKeys.HADOOP_SECURITY_TOKEN_SERVICE_USE_IP, true); @@ -116,7 +120,9 @@ public static void tearDown() { // Verify AM can recover increase request after resync // Step-5 : Allocater after resync command & new containerRequest(cRequest6) // Step-6 : RM allocates containers i.e cRequest4,cRequest5 and cRequest6 - @Test(timeout = 60000) + @Test + @Timeout(value = 60) + @SuppressWarnings("methodlength") public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { UserGroupInformation.setLoginUser(null); @@ -175,8 +181,8 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { AllocateResponse allocateResponse = amClient.allocate(0.1f); rm1.drainEvents(); - Assert.assertEquals("No of assignments must be 0", 0, allocateResponse - .getAllocatedContainers().size()); + assertEquals(0, allocateResponse.getAllocatedContainers().size(), + "No of assignments must be 0"); // Why 4 ask, why not 3 ask even h2 is blacklisted? // On blacklisting host,applicationmaster has to remove ask request from @@ -192,8 +198,8 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { allocateResponse = amClient.allocate(0.2f); rm1.drainEvents(); // 3 containers are allocated i.e for cRequest1, cRequest2 and cRequest3. - Assert.assertEquals("No of assignments must be 0", 3, allocateResponse - .getAllocatedContainers().size()); + assertEquals(3, allocateResponse.getAllocatedContainers().size(), + "No of assignments must be 0"); assertAsksAndReleases(0, 0, rm1); assertBlacklistAdditionsAndRemovals(0, 0, rm1); @@ -206,8 +212,8 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { allocateResponse = amClient.allocate(0.2f); rm1.drainEvents(); - Assert.assertEquals("No of assignments must be 0", 0, allocateResponse - .getAllocatedContainers().size()); + assertEquals(0, allocateResponse.getAllocatedContainers().size(), + "No of assignments must be 0"); assertAsksAndReleases(4, 0, rm1); assertBlacklistAdditionsAndRemovals(0, 0, rm1); @@ -241,8 +247,8 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { allocateResponse = amClient.allocate(0.3f); rm1.drainEvents(); - Assert.assertEquals("No of assignments must be 0", 0, allocateResponse - .getAllocatedContainers().size()); + assertEquals(0, allocateResponse.getAllocatedContainers().size(), + "No of assignments must be 0"); assertAsksAndReleases(3, pendingRelease, rm1); // Verify there is one increase and zero decrease assertChanges(1, 0, rm1); @@ -259,7 +265,7 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { // NM should be rebooted on heartbeat, even first heartbeat for nm2 NodeHeartbeatResponse hbResponse = nm1.nodeHeartbeat(true); - Assert.assertEquals(NodeAction.RESYNC, hbResponse.getNodeAction()); + assertEquals(NodeAction.RESYNC, hbResponse.getNodeAction()); // new NM to represent NM re-register nm1 = new MockNM("h1:1234", 10240, rm2.getResourceTrackerService()); @@ -311,8 +317,8 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { // Step-5 : Allocater after resync command allocateResponse = amClient.allocate(0.5f); rm2.drainEvents(); - Assert.assertEquals("No of assignments must be 0", 0, allocateResponse - .getAllocatedContainers().size()); + assertEquals(0, allocateResponse.getAllocatedContainers().size(), + "No of assignments must be 0"); assertAsksAndReleases(5, 0, rm2); // Verify there is no increase or decrease requests any more @@ -335,8 +341,7 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { } // Step-6 : RM allocates containers i.e cRequest4,cRequest5 and cRequest6 - Assert.assertEquals("Number of container should be 3", 3, - noAssignedContainer); + assertEquals(3, noAssignedContainer, "Number of container should be 3"); amClient.stop(); rm1.stop(); @@ -346,7 +351,8 @@ public void testAMRMClientResendsRequestsOnRMRestart() throws Exception { // Test verify for // 1. AM try to unregister without registering // 2. AM register to RM, and try to unregister immediately after RM restart - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testAMRMClientForUnregisterAMOnRMRestart() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); @@ -391,7 +397,7 @@ public void testAMRMClientForUnregisterAMOnRMRestart() throws Exception { // NM should be rebooted on heartbeat, even first heartbeat for nm2 NodeHeartbeatResponse hbResponse = nm1.nodeHeartbeat(true); - Assert.assertEquals(NodeAction.RESYNC, hbResponse.getNodeAction()); + assertEquals(NodeAction.RESYNC, hbResponse.getNodeAction()); // new NM to represent NM re-register nm1 = new MockNM("h1:1234", 10240, rm2.getResourceTrackerService()); @@ -420,7 +426,8 @@ public void testAMRMClientForUnregisterAMOnRMRestart() throws Exception { // Test verify for AM issued with rolled-over AMRMToken // is still able to communicate with restarted RM. - @Test(timeout = 30000) + @Test + @Timeout(value = 30) public void testAMRMClientOnAMRMTokenRollOverOnRMRestart() throws Exception { conf.setLong( YarnConfiguration.RM_AMRM_TOKEN_MASTER_KEY_ROLLING_INTERVAL_SECS, @@ -471,7 +478,7 @@ public void testAMRMClientOnAMRMTokenRollOverOnRMRestart() throws Exception { // DO NOTHING } } - Assert.assertTrue(amrmTokenSecretManagerForRM1.getMasterKey() + assertTrue(amrmTokenSecretManagerForRM1.getMasterKey() .getMasterKey().getKeyId() != token.decodeIdentifier().getKeyId()); amClient.allocate(0.1f); @@ -492,9 +499,8 @@ public void testAMRMClientOnAMRMTokenRollOverOnRMRestart() throws Exception { } Thread.sleep(500); } - Assert - .assertTrue(amrmTokenSecretManagerForRM1.getNextMasterKeyData() == null); - Assert.assertTrue(amrmTokenSecretManagerForRM1.getCurrnetMasterKeyData() + assertTrue(amrmTokenSecretManagerForRM1.getNextMasterKeyData() == null); + assertTrue(amrmTokenSecretManagerForRM1.getCurrnetMasterKeyData() .getMasterKey().getKeyId() == newToken.decodeIdentifier().getKeyId()); // start 2nd RM @@ -505,10 +511,9 @@ public void testAMRMClientOnAMRMTokenRollOverOnRMRestart() throws Exception { AMRMTokenSecretManager amrmTokenSecretManagerForRM2 = rm2.getRMContext().getAMRMTokenSecretManager(); - Assert.assertTrue(amrmTokenSecretManagerForRM2.getCurrnetMasterKeyData() + assertTrue(amrmTokenSecretManagerForRM2.getCurrnetMasterKeyData() .getMasterKey().getKeyId() == newToken.decodeIdentifier().getKeyId()); - Assert - .assertTrue(amrmTokenSecretManagerForRM2.getNextMasterKeyData() == null); + assertTrue(amrmTokenSecretManagerForRM2.getNextMasterKeyData() == null); try { UserGroupInformation testUser = @@ -524,10 +529,10 @@ public ApplicationMasterProtocol run() { rm2.getApplicationMasterService().getBindAddress(), conf); } }).allocate(Records.newRecord(AllocateRequest.class)); - Assert.fail("The old Token should not work"); + fail("The old Token should not work"); } catch (Exception ex) { - Assert.assertTrue(ex instanceof InvalidToken); - Assert.assertTrue(ex.getMessage().contains( + assertTrue(ex instanceof InvalidToken); + assertTrue(ex.getMessage().contains( "Invalid AMRMToken from " + token.decodeIdentifier().getApplicationAttemptId())); } @@ -665,24 +670,24 @@ public void updateRMProxy(MyResourceManager rm) { private static void assertBlacklistAdditionsAndRemovals( int expectedAdditions, int expectedRemovals, MyResourceManager rm) { - Assert.assertEquals(expectedAdditions, + assertEquals(expectedAdditions, rm.getMyFifoScheduler().lastBlacklistAdditions.size()); - Assert.assertEquals(expectedRemovals, + assertEquals(expectedRemovals, rm.getMyFifoScheduler().lastBlacklistRemovals.size()); } private static void assertAsksAndReleases(int expectedAsk, int expectedRelease, MyResourceManager rm) { - Assert.assertEquals(expectedAsk, rm.getMyFifoScheduler().lastAsk.size()); - Assert.assertEquals(expectedRelease, + assertEquals(expectedAsk, rm.getMyFifoScheduler().lastAsk.size()); + assertEquals(expectedRelease, rm.getMyFifoScheduler().lastRelease.size()); } private static void assertChanges( int expectedIncrease, int expectedDecrease, MyResourceManager rm) { - Assert.assertEquals( + assertEquals( expectedIncrease, rm.getMyFifoScheduler().lastIncrease.size()); - Assert.assertEquals( + assertEquals( expectedDecrease, rm.getMyFifoScheduler().lastDecrease.size()); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientPlacementConstraints.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientPlacementConstraints.java index 993391fb21175..a38832cfdaa58 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientPlacementConstraints.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientPlacementConstraints.java @@ -36,9 +36,9 @@ import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync; import org.apache.hadoop.yarn.client.api.async.impl.AMRMClientAsyncImpl; import org.apache.hadoop.yarn.conf.YarnConfiguration; -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 java.util.ArrayList; import java.util.Arrays; @@ -53,6 +53,8 @@ import static java.lang.Thread.sleep; import static org.apache.hadoop.yarn.api.resource.PlacementConstraints.NODE; import static org.apache.hadoop.yarn.api.resource.PlacementConstraints.PlacementTargets.allocationTag; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; /** * Test Placement Constraints and Scheduling Requests. @@ -63,7 +65,7 @@ public class TestAMRMClientPlacementConstraints extends BaseAMRMClientTest { private List rejectedSchedulingRequests = null; private Map, PlacementConstraint> pcMapping = null; - @Before + @BeforeEach public void setup() throws Exception { conf = new YarnConfiguration(); allocatedContainers = new ArrayList<>(); @@ -77,7 +79,8 @@ public void setup() throws Exception { PlacementConstraints.targetNotIn(NODE, allocationTag("bar")))); } - @Test(timeout=60000) + @Test + @Timeout(value = 60) public void testAMRMClientWithPlacementConstraintsByPlacementProcessor() throws Exception { // we have to create a new instance of MiniYARNCluster to avoid SASL qop @@ -92,7 +95,7 @@ public void testAMRMClientWithPlacementConstraintsByPlacementProcessor() AMRMClient.createAMRMClient(); amClient.setNMTokenCache(new NMTokenCache()); //asserting we are not using the singleton instance cache - Assert.assertNotSame(NMTokenCache.getSingleton(), + assertNotSame(NMTokenCache.getSingleton(), amClient.getNMTokenCache()); AMRMClientAsync asyncClient = new AMRMClientAsyncImpl<>(amClient, 1000, new TestCallbackHandler()); @@ -120,7 +123,7 @@ public void testAMRMClientWithPlacementConstraintsByPlacementProcessor() waitForContainerAllocation(allocatedContainers, rejectedSchedulingRequests, 6, 2); - Assert.assertEquals(6, allocatedContainers.size()); + assertEquals(6, allocatedContainers.size()); Map> containersPerNode = allocatedContainers.stream().collect( Collectors.groupingBy(Container::getNodeId)); @@ -128,19 +131,19 @@ public void testAMRMClientWithPlacementConstraintsByPlacementProcessor() Map, List> outstandingSchedRequests = ((AMRMClientImpl)amClient).getOutstandingSchedRequests(); // Check the outstanding SchedulingRequests - Assert.assertEquals(2, outstandingSchedRequests.size()); - Assert.assertEquals(1, outstandingSchedRequests.get( + assertEquals(2, outstandingSchedRequests.size()); + assertEquals(1, outstandingSchedRequests.get( new HashSet<>(Collections.singletonList("foo"))).size()); - Assert.assertEquals(1, outstandingSchedRequests.get( + assertEquals(1, outstandingSchedRequests.get( new HashSet<>(Collections.singletonList("bar"))).size()); // Ensure 2 containers allocated per node. // Each node should have a "foo" and a "bar" container. - Assert.assertEquals(3, containersPerNode.entrySet().size()); + assertEquals(3, containersPerNode.entrySet().size()); HashSet srcTags = new HashSet<>(Arrays.asList("foo", "bar")); containersPerNode.entrySet().forEach( x -> - Assert.assertEquals( + assertEquals( srcTags, x.getValue() .stream() @@ -149,8 +152,8 @@ public void testAMRMClientWithPlacementConstraintsByPlacementProcessor() ); // Ensure 2 rejected requests - 1 of "foo" and 1 of "bar" - Assert.assertEquals(2, rejectedSchedulingRequests.size()); - Assert.assertEquals(srcTags, + assertEquals(2, rejectedSchedulingRequests.size()); + assertEquals(srcTags, rejectedSchedulingRequests .stream() .map(x -> x.getRequest().getAllocationTags().iterator().next()) @@ -159,7 +162,8 @@ public void testAMRMClientWithPlacementConstraintsByPlacementProcessor() asyncClient.stop(); } - @Test(timeout=60000) + @Test + @Timeout(value = 60) public void testAMRMClientWithPlacementConstraintsByScheduler() throws Exception { // we have to create a new instance of MiniYARNCluster to avoid SASL qop @@ -174,7 +178,7 @@ public void testAMRMClientWithPlacementConstraintsByScheduler() AMRMClient.createAMRMClient(); amClient.setNMTokenCache(new NMTokenCache()); //asserting we are not using the singleton instance cache - Assert.assertNotSame(NMTokenCache.getSingleton(), + assertNotSame(NMTokenCache.getSingleton(), amClient.getNMTokenCache()); AMRMClientAsync asyncClient = new AMRMClientAsyncImpl<>(amClient, 1000, new TestCallbackHandler()); @@ -204,7 +208,7 @@ public void testAMRMClientWithPlacementConstraintsByScheduler() waitForContainerAllocation(allocatedContainers, rejectedSchedulingRequests, 7, 0); - Assert.assertEquals(7, allocatedContainers.size()); + assertEquals(7, allocatedContainers.size()); Map> containersPerNode = allocatedContainers.stream().collect( Collectors.groupingBy(Container::getNodeId)); @@ -212,20 +216,20 @@ public void testAMRMClientWithPlacementConstraintsByScheduler() Map, List> outstandingSchedRequests = ((AMRMClientImpl)amClient).getOutstandingSchedRequests(); // Check the outstanding SchedulingRequests - Assert.assertEquals(3, outstandingSchedRequests.size()); - Assert.assertEquals(1, outstandingSchedRequests.get( + assertEquals(3, outstandingSchedRequests.size()); + assertEquals(1, outstandingSchedRequests.get( new HashSet<>(Collections.singletonList("foo"))).size()); - Assert.assertEquals(1, outstandingSchedRequests.get( + assertEquals(1, outstandingSchedRequests.get( new HashSet<>(Collections.singletonList("bar"))).size()); - Assert.assertEquals(0, outstandingSchedRequests.get( + assertEquals(0, outstandingSchedRequests.get( new HashSet()).size()); // Each node should have a "foo" and a "bar" container. - Assert.assertEquals(3, containersPerNode.entrySet().size()); + assertEquals(3, containersPerNode.entrySet().size()); HashSet srcTags = new HashSet<>(Arrays.asList("foo", "bar")); containersPerNode.entrySet().forEach( x -> - Assert.assertEquals( + assertEquals( srcTags, x.getValue() .stream() @@ -235,7 +239,7 @@ public void testAMRMClientWithPlacementConstraintsByScheduler() ); // The rejected requests were not set by scheduler - Assert.assertEquals(0, rejectedSchedulingRequests.size()); + assertEquals(0, rejectedSchedulingRequests.size()); asyncClient.stop(); } @@ -258,8 +262,8 @@ public void testEmptyKeyOfOutstandingSchedRequests() { schedulingRequest(1, 1, 3, 1, 512, schedRequest))); Map, List> outstandingSchedRequests = ((AMRMClientImpl)amClient).getOutstandingSchedRequests(); - Assert.assertEquals(1, outstandingSchedRequests.size()); - Assert.assertEquals(3, outstandingSchedRequests + assertEquals(1, outstandingSchedRequests.size()); + assertEquals(3, outstandingSchedRequests .get(new HashSet()).size()); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMProxy.java index c02983da7c849..4b2bf9472bc82 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMProxy.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMProxy.java @@ -43,11 +43,18 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * End-to-End test cases for the AMRMProxy Service. */ @@ -60,7 +67,8 @@ public class TestAMRMProxy extends BaseAMRMProxyE2ETest { * This test validates register, allocate and finish of an application through * the AMRMPRoxy. */ - @Test(timeout = 120000) + @Test + @Timeout(value = 120) public void testAMRMProxyE2E() throws Exception { ApplicationMasterProtocol client; @@ -96,18 +104,17 @@ public void testAMRMProxyE2E() throws Exception { client.registerApplicationMaster(RegisterApplicationMasterRequest .newInstance(NetUtils.getHostname(), 1024, "")); - Assert.assertNotNull(responseRegister); - Assert.assertNotNull(responseRegister.getQueue()); - Assert.assertNotNull(responseRegister.getApplicationACLs()); - Assert.assertNotNull(responseRegister.getClientToAMTokenMasterKey()); - Assert - .assertNotNull(responseRegister.getContainersFromPreviousAttempts()); - Assert.assertNotNull(responseRegister.getSchedulerResourceTypes()); - Assert.assertNotNull(responseRegister.getMaximumResourceCapability()); + assertNotNull(responseRegister); + assertNotNull(responseRegister.getQueue()); + assertNotNull(responseRegister.getApplicationACLs()); + assertNotNull(responseRegister.getClientToAMTokenMasterKey()); + assertNotNull(responseRegister.getContainersFromPreviousAttempts()); + assertNotNull(responseRegister.getSchedulerResourceTypes()); + assertNotNull(responseRegister.getMaximumResourceCapability()); RMApp rmApp = cluster.getResourceManager().getRMContext().getRMApps().get(appId); - Assert.assertEquals(RMAppState.RUNNING, rmApp.getState()); + assertEquals(RMAppState.RUNNING, rmApp.getState()); LOG.info("testAMRMProxyE2E - Allocate Resources Application Master"); @@ -115,8 +122,8 @@ public void testAMRMProxyE2E() throws Exception { createAllocateRequest(rmClient.getNodeReports(NodeState.RUNNING)); AllocateResponse allocResponse = client.allocate(request); - Assert.assertNotNull(allocResponse); - Assert.assertEquals(0, allocResponse.getAllocatedContainers().size()); + assertNotNull(allocResponse); + assertEquals(0, allocResponse.getAllocatedContainers().size()); request.setAskList(new ArrayList()); request.setResponseId(request.getResponseId() + 1); @@ -125,8 +132,8 @@ public void testAMRMProxyE2E() throws Exception { // RM should allocate container within 2 calls to allocate() allocResponse = client.allocate(request); - Assert.assertNotNull(allocResponse); - Assert.assertEquals(2, allocResponse.getAllocatedContainers().size()); + assertNotNull(allocResponse); + assertEquals(2, allocResponse.getAllocatedContainers().size()); LOG.info("testAMRMPRoxy - Finish Application Master"); @@ -134,10 +141,10 @@ public void testAMRMProxyE2E() throws Exception { client.finishApplicationMaster(FinishApplicationMasterRequest .newInstance(FinalApplicationStatus.SUCCEEDED, "success", null)); - Assert.assertNotNull(responseFinish); + assertNotNull(responseFinish); Thread.sleep(500); - Assert.assertNotEquals(RMAppState.FINISHED, rmApp.getState()); + assertNotEquals(RMAppState.FINISHED, rmApp.getState()); } } @@ -147,7 +154,8 @@ public void testAMRMProxyE2E() throws Exception { * that the received token from AMRMProxy is different from the previous one * within 5 requests. */ - @Test(timeout = 120000) + @Test + @Timeout(value = 120) public void testAMRMProxyTokenRenewal() throws Exception { ApplicationMasterProtocol client; @@ -207,7 +215,7 @@ public void testAMRMProxyTokenRenewal() throws Exception { } - Assert.assertFalse(response.getAMRMToken().equals(lastToken)); + assertFalse(response.getAMRMToken().equals(lastToken)); LOG.info("testAMRMPRoxy - Finish Application Master"); @@ -221,7 +229,8 @@ public void testAMRMProxyTokenRenewal() throws Exception { * This test validates that an AM cannot register directly to the RM, with the * token provided by the AMRMProxy. */ - @Test(timeout = 120000) + @Test + @Timeout(value = 120) public void testE2ETokenSwap() throws Exception { ApplicationMasterProtocol client; @@ -246,9 +255,9 @@ public void testE2ETokenSwap() throws Exception { try { client.registerApplicationMaster(RegisterApplicationMasterRequest .newInstance(NetUtils.getHostname(), 1024, "")); - Assert.fail(); + fail(); } catch (IOException e) { - Assert.assertTrue( + assertTrue( e.getMessage().startsWith("Invalid AMRMToken from appattempt_")); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestNMClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestNMClient.java index ce24d75d629fb..643908c23085b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestNMClient.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestNMClient.java @@ -56,8 +56,9 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.util.Records; -import org.junit.Test; -import org.junit.function.ThrowingRunnable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.function.Executable; import java.io.IOException; import java.nio.ByteBuffer; @@ -69,11 +70,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeoutException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestNMClient { private static final String IS_NOT_HANDLED_BY_THIS_NODEMANAGER = @@ -197,7 +198,8 @@ public void tearDown() throws InterruptedException { yarnCluster.stop(); } - @Test (timeout = 180_000) + @Test + @Timeout(value = 180) public void testNMClientNoCleanupOnStop() throws YarnException, IOException, InterruptedException, TimeoutException { runTest(() -> { @@ -208,7 +210,8 @@ public void testNMClientNoCleanupOnStop() }); } - @Test (timeout = 200_000) + @Test + @Timeout(value = 200) public void testNMClient() throws YarnException, IOException, InterruptedException, TimeoutException { runTest(() -> { @@ -232,7 +235,7 @@ public void runTest( } private void stopNmClient() { - assertNotNull("Null nmClient", nmClient); + assertNotNull(nmClient, "Null nmClient"); // leave one unclosed assertEquals(1, nmClient.startedContainers.size()); // default true @@ -383,13 +386,13 @@ private void testGetContainerStatus(Container container, int index, // container status if (status.getState() == state) { assertEquals(container.getId(), status.getContainerId()); - assertTrue(index + ": " + status.getDiagnostics(), - status.getDiagnostics().contains(diagnostics)); + assertTrue(status.getDiagnostics().contains(diagnostics), + index + ": " + status.getDiagnostics()); - assertTrue("Exit Statuses are supposed to be in: " + exitStatuses + - ", but the actual exit status code is: " + - status.getExitStatus(), - exitStatuses.contains(status.getExitStatus())); + assertTrue(exitStatuses.contains(status.getExitStatus()), + "Exit Statuses are supposed to be in: " + exitStatuses + + ", but the actual exit status code is: " + + status.getExitStatus()); break; } } @@ -434,10 +437,11 @@ private void testReInitializeContainer( nmClient.reInitializeContainer(container.getId(), clc, autoCommit); } - private void assertYarnException(ThrowingRunnable runnable, String text) { + private void assertYarnException(Executable runnable, String text) { YarnException e = assertThrows(YarnException.class, runnable); - assertTrue(String.format("The thrown exception is not expected cause it has text [%s]" - + ", what not contains text [%s]", e.getMessage(), text), e.getMessage().contains(text)); + assertTrue(e.getMessage().contains(text), + String.format("The thrown exception is not expected cause it has text [%s]" + + ", what not contains text [%s]", e.getMessage(), text)); } private void sleep(int sleepTime) { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestOpportunisticContainerAllocationE2E.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestOpportunisticContainerAllocationE2E.java index 870862b9cd7af..a55620a09ef9f 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestOpportunisticContainerAllocationE2E.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestOpportunisticContainerAllocationE2E.java @@ -62,12 +62,12 @@ .AbstractYarnScheduler; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.Records; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.io.IOException; import java.nio.ByteBuffer; @@ -82,8 +82,11 @@ import java.util.TreeSet; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Class that tests the allocation of OPPORTUNISTIC containers through the @@ -118,7 +121,7 @@ public class TestOpportunisticContainerAllocationE2E { private long allocMB; private int allocVCores; - @BeforeClass + @BeforeAll public static void setup() throws Exception { // start minicluster conf = new YarnConfiguration(); @@ -159,7 +162,7 @@ public static void setup() throws Exception { racks = new String[]{rack}; } - @Before + @BeforeEach public void startApp() throws Exception { // submit new app ApplicationSubmissionContext appContext = @@ -223,7 +226,7 @@ public void startApp() throws Exception { //setting an instance NMTokenCache amClient.setNMTokenCache(new NMTokenCache()); //asserting we are not using the singleton instance cache - Assert.assertNotSame(NMTokenCache.getSingleton(), + assertNotSame(NMTokenCache.getSingleton(), amClient.getNMTokenCache()); amClient.init(conf); @@ -232,7 +235,7 @@ public void startApp() throws Exception { amClient.registerApplicationMaster("Host", 10000, ""); } - @After + @AfterEach public void cancelApp() throws YarnException, IOException { try { amClient @@ -248,7 +251,7 @@ public void cancelApp() throws YarnException, IOException { attemptId = null; } - @AfterClass + @AfterAll public static void tearDown() { if (yarnClient != null && yarnClient.getServiceState() == Service.STATE.STARTED) { @@ -260,7 +263,8 @@ public static void tearDown() { } } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testPromotionFromAcquired() throws YarnException, IOException { // setup container request assertEquals(0, amClient.ask.size()); @@ -288,7 +292,7 @@ public void testPromotionFromAcquired() throws YarnException, IOException { int iterationsLeft = 50; amClient.getNMTokenCache().clearCache(); - Assert.assertEquals(0, + assertEquals(0, amClient.getNMTokenCache().numberOfTokensInCache()); HashMap receivedNMTokens = new HashMap<>(); @@ -331,10 +335,10 @@ public void testPromotionFromAcquired() throws YarnException, IOException { c, UpdateContainerRequest.newInstance(c.getVersion(), c.getId(), ContainerUpdateType.PROMOTE_EXECUTION_TYPE, null, ExecutionType.OPPORTUNISTIC)); - Assert.fail("Should throw Exception.."); + fail("Should throw Exception.."); } catch (IllegalArgumentException e) { System.out.println("## " + e.getMessage()); - Assert.assertTrue(e.getMessage().contains( + assertTrue(e.getMessage().contains( "target should be GUARANTEED and original should be OPPORTUNISTIC")); } @@ -385,7 +389,8 @@ public void testPromotionFromAcquired() throws YarnException, IOException { amClient.ask.clear(); } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testDemotionFromAcquired() throws YarnException, IOException { // setup container request assertEquals(0, amClient.ask.size()); @@ -409,7 +414,7 @@ public void testDemotionFromAcquired() throws YarnException, IOException { int iterationsLeft = 50; amClient.getNMTokenCache().clearCache(); - Assert.assertEquals(0, + assertEquals(0, amClient.getNMTokenCache().numberOfTokensInCache()); HashMap receivedNMTokens = new HashMap<>(); @@ -452,10 +457,10 @@ public void testDemotionFromAcquired() throws YarnException, IOException { c, UpdateContainerRequest.newInstance(c.getVersion(), c.getId(), ContainerUpdateType.DEMOTE_EXECUTION_TYPE, null, ExecutionType.GUARANTEED)); - Assert.fail("Should throw Exception.."); + fail("Should throw Exception.."); } catch (IllegalArgumentException e) { System.out.println("## " + e.getMessage()); - Assert.assertTrue(e.getMessage().contains( + assertTrue(e.getMessage().contains( "target should be OPPORTUNISTIC and original should be GUARANTEED")); } @@ -506,7 +511,9 @@ public void testDemotionFromAcquired() throws YarnException, IOException { amClient.ask.clear(); } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) + @SuppressWarnings("methodlength") public void testMixedAllocationAndRelease() throws YarnException, IOException { // setup container request @@ -594,7 +601,7 @@ public void testMixedAllocationAndRelease() throws YarnException, Set releases = new TreeSet<>(); amClient.getNMTokenCache().clearCache(); - Assert.assertEquals(0, + assertEquals(0, amClient.getNMTokenCache().numberOfTokensInCache()); HashMap receivedNMTokens = new HashMap<>(); @@ -676,7 +683,8 @@ public void testMixedAllocationAndRelease() throws YarnException, /** * Tests allocation with requests comprising only opportunistic containers. */ - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testOpportunisticAllocation() throws YarnException, IOException { // setup container request assertEquals(0, amClient.ask.size()); @@ -708,7 +716,7 @@ public void testOpportunisticAllocation() throws YarnException, IOException { Set releases = new TreeSet<>(); amClient.getNMTokenCache().clearCache(); - Assert.assertEquals(0, + assertEquals(0, amClient.getNMTokenCache().numberOfTokensInCache()); HashMap receivedNMTokens = new HashMap<>(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestSharedCacheClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestSharedCacheClientImpl.java index 8111c7ebdf0f2..5d154679aae53 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestSharedCacheClientImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestSharedCacheClientImpl.java @@ -18,8 +18,9 @@ package org.apache.hadoop.yarn.client.api.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,11 +41,11 @@ import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.URL; import org.apache.hadoop.yarn.exceptions.YarnException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,7 +62,7 @@ public class TestSharedCacheClientImpl { private static String inputChecksumSHA256 = "f29bc64a9d3732b4b9035125fdb3285f5b6455778edca72414671e0ca3b2e0de"; - @BeforeClass + @BeforeAll public static void beforeClass() throws IOException { localFs = FileSystem.getLocal(new Configuration()); TEST_ROOT_DIR = @@ -70,7 +71,7 @@ public static void beforeClass() throws IOException { localFs.getWorkingDirectory()); } - @AfterClass + @AfterAll public static void afterClass() { try { if (localFs != null) { @@ -82,7 +83,7 @@ public static void afterClass() { } } - @Before + @BeforeEach public void setup() { cProtocol = mock(ClientSCMProtocol.class); client = new SharedCacheClientImpl() { @@ -100,7 +101,7 @@ protected void stopClientProxy() { client.start(); } - @After + @AfterEach public void cleanup() { if (client != null) { client.stop(); @@ -116,7 +117,7 @@ public void testUseCacheMiss() throws Exception { when(cProtocol.use(isA(UseSharedCacheResourceRequest.class))).thenReturn( response); URL newURL = client.use(mock(ApplicationId.class), "key"); - assertNull("The path is not null!", newURL); + assertNull(newURL, "The path is not null!"); } @Test @@ -129,15 +130,17 @@ public void testUseCacheHit() throws Exception { when(cProtocol.use(isA(UseSharedCacheResourceRequest.class))).thenReturn( response); URL newURL = client.use(mock(ApplicationId.class), "key"); - assertEquals("The paths are not equal!", useUrl, newURL); + assertEquals(useUrl, newURL, "The paths are not equal!"); } - @Test(expected = YarnException.class) + @Test public void testUseError() throws Exception { - String message = "Mock IOExcepiton!"; - when(cProtocol.use(isA(UseSharedCacheResourceRequest.class))).thenThrow( - new IOException(message)); - client.use(mock(ApplicationId.class), "key"); + assertThrows(YarnException.class, ()->{ + String message = "Mock IOExcepiton!"; + when(cProtocol.use(isA(UseSharedCacheResourceRequest.class))).thenThrow( + new IOException(message)); + client.use(mock(ApplicationId.class), "key"); + }); } @Test @@ -148,12 +151,14 @@ public void testRelease() throws Exception { client.release(mock(ApplicationId.class), "key"); } - @Test(expected = YarnException.class) + @Test public void testReleaseError() throws Exception { - String message = "Mock IOExcepiton!"; - when(cProtocol.release(isA(ReleaseSharedCacheResourceRequest.class))) - .thenThrow(new IOException(message)); - client.release(mock(ApplicationId.class), "key"); + assertThrows(YarnException.class, () -> { + String message = "Mock IOExcepiton!"; + when(cProtocol.release(isA(ReleaseSharedCacheResourceRequest.class))) + .thenThrow(new IOException(message)); + client.release(mock(ApplicationId.class), "key"); + }); } @Test @@ -163,10 +168,12 @@ public void testChecksum() throws Exception { assertEquals(inputChecksumSHA256, client.getFileChecksum(file)); } - @Test(expected = FileNotFoundException.class) + @Test public void testNonexistantFileChecksum() throws Exception { - Path file = new Path(TEST_ROOT_DIR, "non-existant-file"); - client.getFileChecksum(file); + assertThrows(FileNotFoundException.class, () -> { + Path file = new Path(TEST_ROOT_DIR, "non-existant-file"); + client.getFileChecksum(file); + }); } private Path makeFile(String filename) throws Exception { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClientWithReservation.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClientWithReservation.java index 073d7bc1c5be0..48385dfc47901 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClientWithReservation.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClientWithReservation.java @@ -52,11 +52,9 @@ .allocationfile.AllocationFileWriter; import org.apache.hadoop.yarn.util.Clock; import org.apache.hadoop.yarn.util.UTCClock; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.io.File; import java.io.IOException; @@ -66,13 +64,16 @@ import java.util.stream.Collectors; 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; /** * This class is to test class {@link YarnClient) and {@link YarnClientImpl} * with Reservation. */ -@RunWith(Parameterized.class) public class TestYarnClientWithReservation { protected final static String TEST_DIR = new File(System.getProperty("test.build.data", "/tmp")).getAbsolutePath(); @@ -85,13 +86,12 @@ public enum SchedulerType { private SchedulerType schedulerType; - @Parameterized.Parameters(name = "{0}") public static Collection getParameters() { return Arrays.stream(SchedulerType.values()).map( type -> new Object[]{type}).collect(Collectors.toList()); } - public TestYarnClientWithReservation(SchedulerType scheduler) { + public void initTestYarnClientWithReservation(SchedulerType scheduler) { this.schedulerType = scheduler; } @@ -170,21 +170,23 @@ private ReservationSubmissionRequest submitReservationTestHelper( reservationID, 4, arrival, deadline, duration); ReservationSubmissionResponse sResponse = client.submitReservation(sRequest); - Assert.assertNotNull(sResponse); - Assert.assertNotNull(reservationID); + assertNotNull(sResponse); + assertNotNull(reservationID); System.out.println("Submit reservation response: " + reservationID); return sRequest; } - @Before + @BeforeEach public void setup() { QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.setMiniClusterMode(true); } - @Test - public void testCreateReservation() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("getParameters") + public void testCreateReservation(SchedulerType scheduler) throws Exception { + initTestYarnClientWithReservation(scheduler); MiniYARNCluster cluster = setupMiniYARNCluster(); YarnClient client = setupYarnClient(cluster); try { @@ -207,11 +209,11 @@ public void testCreateReservation() throws Exception { sRequest.setReservationDefinition(rDef); try { client.submitReservation(sRequest); - Assert.fail("Reservation submission should fail if a duplicate " + fail("Reservation submission should fail if a duplicate " + "reservation id is used, but the reservation definition has been " + "updated."); } catch (Exception e) { - Assert.assertTrue(e instanceof YarnException); + assertTrue(e instanceof YarnException); } } finally { // clean-up @@ -222,8 +224,10 @@ public void testCreateReservation() throws Exception { } } - @Test - public void testUpdateReservation() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("getParameters") + public void testUpdateReservation(SchedulerType scheduler) throws Exception { + initTestYarnClientWithReservation(scheduler); MiniYARNCluster cluster = setupMiniYARNCluster(); YarnClient client = setupYarnClient(cluster); try { @@ -248,7 +252,7 @@ public void testUpdateReservation() throws Exception { ReservationUpdateRequest uRequest = ReservationUpdateRequest.newInstance(rDef, reservationID); ReservationUpdateResponse uResponse = client.updateReservation(uRequest); - Assert.assertNotNull(uResponse); + assertNotNull(uResponse); System.out.println("Update reservation response: " + uResponse); } finally { // clean-up @@ -279,8 +283,11 @@ private ReservationSubmissionRequest createSimpleReservationRequest( } - @Test - public void testListReservationsByReservationId() throws Exception{ + @ParameterizedTest(name = "{0}") + @MethodSource("getParameters") + public void testListReservationsByReservationId(SchedulerType scheduler) + throws Exception{ + initTestYarnClientWithReservation(scheduler); MiniYARNCluster cluster = setupMiniYARNCluster(); YarnClient client = setupYarnClient(cluster); try { @@ -296,11 +303,11 @@ public void testListReservationsByReservationId() throws Exception{ ReservationSystemTestUtil.reservationQ, reservationID.toString(), -1, -1, false); ReservationListResponse response = client.listReservations(request); - Assert.assertNotNull(response); - Assert.assertEquals(1, response.getReservationAllocationState().size()); - Assert.assertEquals(response.getReservationAllocationState().get(0) + assertNotNull(response); + assertEquals(1, response.getReservationAllocationState().size()); + assertEquals(response.getReservationAllocationState().get(0) .getReservationId().getId(), reservationID.getId()); - Assert.assertEquals(response.getReservationAllocationState().get(0) + assertEquals(response.getReservationAllocationState().get(0) .getResourceAllocationRequests().size(), 0); } finally { // clean-up @@ -311,8 +318,11 @@ public void testListReservationsByReservationId() throws Exception{ } } - @Test - public void testListReservationsByTimeInterval() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("getParameters") + public void testListReservationsByTimeInterval(SchedulerType scheduler) + throws Exception { + initTestYarnClientWithReservation(scheduler); MiniYARNCluster cluster = setupMiniYARNCluster(); YarnClient client = setupYarnClient(cluster); try { @@ -332,30 +342,30 @@ public void testListReservationsByTimeInterval() throws Exception { arrival + duration / 2, true); ReservationListResponse response = client.listReservations(request); - Assert.assertNotNull(response); - Assert.assertEquals(1, response.getReservationAllocationState().size()); - Assert.assertEquals(response.getReservationAllocationState().get(0) + assertNotNull(response); + assertEquals(1, response.getReservationAllocationState().size()); + assertEquals(response.getReservationAllocationState().get(0) .getReservationId().getId(), reservationID.getId()); // List reservations, search by time within reservation interval. request = ReservationListRequest.newInstance( ReservationSystemTestUtil.reservationQ, "", 1, Long.MAX_VALUE, true); response = client.listReservations(request); - Assert.assertNotNull(response); - Assert.assertEquals(1, response.getReservationAllocationState().size()); - Assert.assertEquals(response.getReservationAllocationState().get(0) + assertNotNull(response); + assertEquals(1, response.getReservationAllocationState().size()); + assertEquals(response.getReservationAllocationState().get(0) .getReservationId().getId(), reservationID.getId()); // Verify that the full resource allocations exist. - Assert.assertTrue(response.getReservationAllocationState().get(0) + assertTrue(response.getReservationAllocationState().get(0) .getResourceAllocationRequests().size() > 0); // Verify that the full RDL is returned. ReservationRequests reservationRequests = response.getReservationAllocationState().get(0) .getReservationDefinition().getReservationRequests(); - Assert.assertEquals("R_ALL", + assertEquals("R_ALL", reservationRequests.getInterpreter().toString()); - Assert.assertTrue(reservationRequests.getReservationResources().get(0) + assertTrue(reservationRequests.getReservationResources().get(0) .getDuration() == duration); } finally { // clean-up @@ -366,8 +376,11 @@ public void testListReservationsByTimeInterval() throws Exception { } } - @Test - public void testListReservationsByInvalidTimeInterval() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("getParameters") + public void testListReservationsByInvalidTimeInterval(SchedulerType scheduler) + throws Exception { + initTestYarnClientWithReservation(scheduler); MiniYARNCluster cluster = setupMiniYARNCluster(); YarnClient client = setupYarnClient(cluster); try { @@ -383,9 +396,9 @@ public void testListReservationsByInvalidTimeInterval() throws Exception { .newInstance(ReservationSystemTestUtil.reservationQ, "", 1, -1, true); ReservationListResponse response = client.listReservations(request); - Assert.assertNotNull(response); - Assert.assertEquals(1, response.getReservationAllocationState().size()); - Assert.assertEquals(response.getReservationAllocationState().get(0) + assertNotNull(response); + assertEquals(1, response.getReservationAllocationState().size()); + assertEquals(response.getReservationAllocationState().get(0) .getReservationId().getId(), sRequest.getReservationId().getId()); // List reservations, search by invalid end time < -1. @@ -393,9 +406,9 @@ public void testListReservationsByInvalidTimeInterval() throws Exception { ReservationSystemTestUtil.reservationQ, "", 1, -10, true); response = client.listReservations(request); - Assert.assertNotNull(response); - Assert.assertEquals(1, response.getReservationAllocationState().size()); - Assert.assertEquals(response.getReservationAllocationState().get(0) + assertNotNull(response); + assertEquals(1, response.getReservationAllocationState().size()); + assertEquals(response.getReservationAllocationState().get(0) .getReservationId().getId(), sRequest.getReservationId().getId()); } finally { // clean-up @@ -406,9 +419,11 @@ public void testListReservationsByInvalidTimeInterval() throws Exception { } } - @Test - public void testListReservationsByTimeIntervalContainingNoReservations() - throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("getParameters") + public void testListReservationsByTimeIntervalContainingNoReservations( + SchedulerType scheduler) throws Exception { + initTestYarnClientWithReservation(scheduler); MiniYARNCluster cluster = setupMiniYARNCluster(); YarnClient client = setupYarnClient(cluster); try { @@ -427,7 +442,7 @@ public void testListReservationsByTimeIntervalContainingNoReservations() ReservationListResponse response = client.listReservations(request); // Ensure all reservations are filtered out. - Assert.assertNotNull(response); + assertNotNull(response); assertThat(response.getReservationAllocationState()).isEmpty(); duration = 30000; @@ -442,7 +457,7 @@ public void testListReservationsByTimeIntervalContainingNoReservations() response = client.listReservations(request); // Ensure all reservations are filtered out. - Assert.assertNotNull(response); + assertNotNull(response); assertThat(response.getReservationAllocationState()).isEmpty(); arrival = clock.getTime(); @@ -455,7 +470,7 @@ public void testListReservationsByTimeIntervalContainingNoReservations() response = client.listReservations(request); // Ensure all reservations are filtered out. - Assert.assertNotNull(response); + assertNotNull(response); assertThat(response.getReservationAllocationState()).isEmpty(); // List reservations, search by very small end time. @@ -465,7 +480,7 @@ public void testListReservationsByTimeIntervalContainingNoReservations() response = client.listReservations(request); // Ensure all reservations are filtered out. - Assert.assertNotNull(response); + assertNotNull(response); assertThat(response.getReservationAllocationState()).isEmpty(); } finally { @@ -477,8 +492,10 @@ public void testListReservationsByTimeIntervalContainingNoReservations() } } - @Test - public void testReservationDelete() throws Exception { + @ParameterizedTest(name = "{0}") + @MethodSource("getParameters") + public void testReservationDelete(SchedulerType scheduler) throws Exception { + initTestYarnClientWithReservation(scheduler); MiniYARNCluster cluster = setupMiniYARNCluster(); YarnClient client = setupYarnClient(cluster); try { @@ -494,7 +511,7 @@ public void testReservationDelete() throws Exception { ReservationDeleteRequest dRequest = ReservationDeleteRequest.newInstance(reservationID); ReservationDeleteResponse dResponse = client.deleteReservation(dRequest); - Assert.assertNotNull(dResponse); + assertNotNull(dResponse); System.out.println("Delete reservation response: " + dResponse); // List reservations, search by non-existent reservationID @@ -503,8 +520,8 @@ public void testReservationDelete() throws Exception { -1, false); ReservationListResponse response = client.listReservations(request); - Assert.assertNotNull(response); - Assert.assertEquals(0, response.getReservationAllocationState().size()); + assertNotNull(response); + assertEquals(0, response.getReservationAllocationState().size()); } finally { // clean-up if (client != null) { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestClusterCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestClusterCLI.java index 2d005a1526411..2843632672127 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestClusterCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestClusterCLI.java @@ -21,7 +21,7 @@ import org.apache.hadoop.yarn.api.records.NodeAttributeInfo; import org.apache.hadoop.yarn.api.records.NodeAttributeKey; import org.apache.hadoop.yarn.api.records.NodeAttributeType; -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.spy; import static org.mockito.Mockito.verify; @@ -36,8 +36,8 @@ import org.apache.hadoop.yarn.api.records.NodeLabel; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.apache.hadoop.thirdparty.com.google.common.collect.ImmutableSet; @@ -49,7 +49,7 @@ public class TestClusterCLI { private PrintStream sysErr; private YarnClient client = mock(YarnClient.class); - @Before + @BeforeEach public void setup() { sysOutStream = new ByteArrayOutputStream(); sysOut = spy(new PrintStream(sysOutStream)); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestGpgCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestGpgCLI.java index 0ab981bf60bb9..9006dd6c996f3 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestGpgCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestGpgCLI.java @@ -19,18 +19,18 @@ import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.conf.YarnConfiguration; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestGpgCLI { private GpgCLI gpgCLI; - @Before + @BeforeEach public void setup() throws Exception { Configuration config = new Configuration(); config.setBoolean(YarnConfiguration.FEDERATION_ENABLED, true); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java index ebcc0f2f15967..ecbb81ad96308 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java @@ -22,9 +22,11 @@ import static org.apache.hadoop.yarn.conf.YarnConfiguration.LOG_AGGREGATION_REMOTE_APP_LOG_DIR_FMT; import static org.apache.hadoop.yarn.conf.YarnConfiguration.LOG_AGGREGATION_REMOTE_APP_LOG_DIR_SUFFIX_FMT; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyList; @@ -92,10 +94,10 @@ import org.apache.hadoop.yarn.logaggregation.filecontroller.ifile.LogAggregationIndexedFileController; import org.apache.hadoop.yarn.webapp.util.WebServiceClient; import org.codehaus.jettison.json.JSONObject; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.mockito.ArgumentCaptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -113,7 +115,7 @@ public class TestLogsCLI { private Configuration conf; - @Before + @BeforeEach public void setUp() throws Exception { sysOutStream = new ByteArrayOutputStream(); sysOut = new PrintStream(sysOutStream); @@ -126,12 +128,13 @@ public void setUp() throws Exception { WebServiceClient.initialize(conf); } - @After + @AfterEach public void tearDown() { WebServiceClient.destroy(); } - @Test(timeout = 5000l) + @Test + @Timeout(value = 5) public void testFailResultCodes() throws Exception { conf.setClass("fs.file.impl", LocalFileSystem.class, FileSystem.class); LogCLIHelpers cliHelper = new LogCLIHelpers(); @@ -145,15 +148,16 @@ public void testFailResultCodes() throws Exception { // verify dumping a non-existent application's logs returns a failure code int exitCode = dumper.run( new String[] { "-applicationId", "application_0_0" } ); - assertTrue("Should return an error code", exitCode != 0); + assertTrue(exitCode != 0, "Should return an error code"); // verify dumping a non-existent container log is a failure code exitCode = cliHelper.dumpAContainersLogs("application_0_0", "container_0_0", "nonexistentnode:1234", "nobody"); - assertTrue("Should return an error code", exitCode != 0); + assertTrue(exitCode != 0, "Should return an error code"); } - @Test(timeout = 10000l) + @Test + @Timeout(value = 10) public void testInvalidOpts() throws Exception { YarnClient mockYarnClient = createMockYarnClient( YarnApplicationState.FINISHED, @@ -167,7 +171,8 @@ public void testInvalidOpts() throws Exception { "options parsing failed: Unrecognized option: -InvalidOpts")); } - @Test(timeout = 5000L) + @Test + @Timeout(value = 5) public void testInvalidAMContainerId() throws Exception { conf.setBoolean(YarnConfiguration.APPLICATION_HISTORY_ENABLED, true); YarnClient mockYarnClient = @@ -222,7 +227,8 @@ public void testAMContainerInfoFetchFromTimelineReader() throws Exception { assertTrue(exitCode == 0); } - @Test(timeout = 5000l) + @Test + @Timeout(value = 5) public void testUnknownApplicationId() throws Exception { YarnClient mockYarnClient = createMockYarnClientUnknownApp(); LogsCLI cli = new LogsCLIForTest(mockYarnClient); @@ -237,7 +243,8 @@ public void testUnknownApplicationId() throws Exception { "Unable to get ApplicationState")); } - @Test(timeout = 5000L) + @Test + @Timeout(value = 5) public void testUnknownApplicationAttemptId() throws Exception { YarnClient mockYarnClient = createMockYarnClientUnknownApp(); LogsCLI cli = new LogsCLIForTest(mockYarnClient); @@ -253,7 +260,8 @@ public void testUnknownApplicationAttemptId() throws Exception { "Unable to get ApplicationState.")); } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testHelpMessage() throws Exception { YarnClient mockYarnClient = createMockYarnClient( YarnApplicationState.FINISHED, @@ -372,10 +380,12 @@ public void testHelpMessage() throws Exception { pw.println(" fetch all logs."); pw.close(); String appReportStr = baos.toString("UTF-8"); - Assert.assertTrue(sysOutStream.toString().contains(appReportStr)); + assertTrue(sysOutStream.toString().contains(appReportStr)); } - @Test (timeout = 15000) + @Test + @Timeout(value = 15) + @SuppressWarnings("methodlength") public void testFetchFinishedApplictionLogs() throws Exception { String remoteLogRootDir = "target/logs/"; conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true); @@ -578,43 +588,36 @@ public ContainerReport getContainerReport(String containerIdStr) // Check backward compatibility for -logFiles exitCode = cli.run(new String[] {"-applicationId", appId.toString(), "-logFiles", "stdout"}); - assertTrue("Failed with -logFiles", exitCode == 0); - assertFalse("Failed with -logFiles", sysOutStream.toString().contains( - logMessage(containerId1, "syslog"))); - assertFalse("Failed with -logFiles", sysOutStream.toString().contains( - logMessage(containerId2, "syslog"))); - assertFalse("Failed with -logFiles", sysOutStream.toString().contains( - logMessage(containerId3, "syslog"))); - assertTrue("Failed with -logFiles", sysOutStream.toString().contains( - logMessage(containerId3, "stdout"))); - assertFalse("Failed with -logFiles", sysOutStream.toString().contains( - logMessage(containerId3, "stdout1234"))); - assertFalse("Failed with -logFiles", sysOutStream.toString().contains( - createEmptyLog("empty"))); + assertTrue(exitCode == 0, "Failed with -logFiles"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId1, "syslog")), + "Failed with -logFiles"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId2, "syslog")), + "Failed with -logFiles"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId3, "syslog")), + "Failed with -logFiles"); + assertTrue(sysOutStream.toString().contains(logMessage(containerId3, "stdout")), + "Failed with -logFiles"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId3, "stdout1234")), + "Failed with -logFiles"); + assertFalse(sysOutStream.toString().contains(createEmptyLog("empty")), "Failed with -logFiles"); sysOutStream.reset(); // Check -log_files supercedes -logFiles exitCode = cli.run(new String[] {"-applicationId", appId.toString(), "-log_files", "stdout", "-logFiles", "syslog"}); - assertTrue("Failed with -logFiles and -log_files", exitCode == 0); - assertFalse("Failed with -logFiles and -log_files", - sysOutStream.toString().contains( - logMessage(containerId1, "syslog"))); - assertFalse("Failed with -logFiles and -log_files", - sysOutStream.toString().contains( - logMessage(containerId2, "syslog"))); - assertFalse("Failed with -logFiles and -log_files", - sysOutStream.toString().contains( - logMessage(containerId3, "syslog"))); - assertTrue("Failed with -logFiles and -log_files", - sysOutStream.toString().contains( - logMessage(containerId3, "stdout"))); - assertFalse("Failed with -logFiles and -log_files", - sysOutStream.toString().contains( - logMessage(containerId3, "stdout1234"))); - assertFalse("Failed with -logFiles and -log_files", - sysOutStream.toString().contains( - createEmptyLog("empty"))); + assertTrue(exitCode == 0, "Failed with -logFiles and -log_files"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId1, "syslog")), + "Failed with -logFiles and -log_files"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId2, "syslog")), + "Failed with -logFiles and -log_files"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId3, "syslog")), + "Failed with -logFiles and -log_files"); + assertTrue(sysOutStream.toString().contains(logMessage(containerId3, "stdout")), + "Failed with -logFiles and -log_files"); + assertFalse(sysOutStream.toString().contains(logMessage(containerId3, "stdout1234")), + "Failed with -logFiles and -log_files"); + assertFalse(sysOutStream.toString().contains( + createEmptyLog("empty")), "Failed with -logFiles and -log_files"); sysOutStream.reset(); exitCode = cli.run(new String[] {"-applicationId", appId.toString(), @@ -697,7 +700,7 @@ public ContainerReport getContainerReport(String containerIdStr) "-containerId", containerId3.toString(), "-log_files", "stdout", "-size", "5"}); assertTrue(exitCode == 0); - Assert.assertEquals(new String(logMessage.getBytes(), 0, 5), + assertEquals(new String(logMessage.getBytes(), 0, 5), new String(sysOutStream.toByteArray(), (fullContextSize - fileContentSize - tailContentSize), 5)); sysOutStream.reset(); @@ -717,7 +720,7 @@ public ContainerReport getContainerReport(String containerIdStr) "-containerId", containerId3.toString(), "-log_files", "stdout", "-size", "-5"}); assertTrue(exitCode == 0); - Assert.assertEquals(new String(logMessage.getBytes(), + assertEquals(new String(logMessage.getBytes(), logMessage.getBytes().length - 5, 5), new String(sysOutStream.toByteArray(), (fullContextSize - fileContentSize - tailContentSize), 5)); @@ -728,7 +731,7 @@ public ContainerReport getContainerReport(String containerIdStr) "-containerId", containerId3.toString(), "-log_files", "stdout", "-size", Long.toString(negative)}); assertTrue(exitCode == 0); - Assert.assertEquals(fullContext, sysOutStream.toString()); + assertEquals(fullContext, sysOutStream.toString()); sysOutStream.reset(); // Uploaded the empty log for container0. @@ -858,16 +861,16 @@ public void testCheckRetryCount() throws Exception { try { cli.run(new String[] {"-containerId", containerId1.toString(), "-client_max_retries", "5"}); - Assert.fail("Exception expected! " + fail("Exception expected! " + "NodeManager should be off to run this test. "); } catch (IOException ce) { - Assert.assertTrue( - "Handler exception for reason other than retry: " + ce.getMessage(), - ce.getMessage().contains("Connection retries limit exceeded")); + assertTrue(ce.getMessage().contains("Connection retries limit exceeded"), + "Handler exception for reason other than retry: " + ce.getMessage()); } } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testGetRunningContainerLogs() throws Exception { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); @@ -956,7 +959,8 @@ public void testGetRunningContainerLogs() throws Exception { } } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testFetchRunningApplicationLogs() throws Exception { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); @@ -1028,11 +1032,11 @@ public void testFetchRunningApplicationLogs() throws Exception { // Verify that the log-type is "ALL" List capturedRequests = logsRequestCaptor.getAllValues(); - Assert.assertEquals(2, capturedRequests.size()); + assertEquals(2, capturedRequests.size()); Set logTypes0 = capturedRequests.get(0).getLogTypes(); Set logTypes1 = capturedRequests.get(1).getLogTypes(); - Assert.assertTrue(logTypes0.contains("ALL") && (logTypes0.size() == 1)); - Assert.assertTrue(logTypes1.contains("ALL") && (logTypes1.size() == 1)); + assertTrue(logTypes0.contains("ALL") && (logTypes0.size() == 1)); + assertTrue(logTypes1.contains("ALL") && (logTypes1.size() == 1)); mockYarnClient = createMockYarnClientWithException( YarnApplicationState.RUNNING, ugi.getShortUserName()); @@ -1057,7 +1061,8 @@ public void testFetchRunningApplicationLogs() throws Exception { any(LogCLIHelpers.class), anyBoolean(), anyBoolean()); } - @Test (timeout = 15000) + @Test + @Timeout(value = 15) public void testFetchApplictionLogsAsAnotherUser() throws Exception { String remoteLogRootDir = "target/logs/"; String rootLogDir = "target/LocalLogs"; @@ -1208,7 +1213,8 @@ public void testFetchApplictionLogsAsAnotherUser() throws Exception { } } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testWithInvalidApplicationId() throws Exception { LogsCLI cli = createCli(); @@ -1219,7 +1225,8 @@ public void testWithInvalidApplicationId() throws Exception { "Invalid ApplicationId specified")); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testWithInvalidAppAttemptId() throws Exception { LogsCLI cli = createCli(); @@ -1231,7 +1238,8 @@ public void testWithInvalidAppAttemptId() throws Exception { sysErrStream.reset(); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testWithInvalidContainerId() throws Exception { LogsCLI cli = createCli(); @@ -1243,7 +1251,8 @@ public void testWithInvalidContainerId() throws Exception { sysErrStream.reset(); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testWithNonMatchingEntityIds() throws Exception { ApplicationId appId1 = ApplicationId.newInstance(0, 1); ApplicationId appId2 = ApplicationId.newInstance(0, 2); @@ -1282,7 +1291,8 @@ public void testWithNonMatchingEntityIds() throws Exception { sysErrStream.reset(); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testWithExclusiveArguments() throws Exception { ApplicationId appId1 = ApplicationId.newInstance(0, 1); LogsCLI cli = createCli(); @@ -1308,7 +1318,8 @@ public void testWithExclusiveArguments() throws Exception { sysErrStream.reset(); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testWithFileInputForOptionOut() throws Exception { String localDir = "target/SaveLogs"; Path localPath = new Path(localDir); @@ -1334,7 +1345,8 @@ public void testWithFileInputForOptionOut() throws Exception { } } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testGuessAppOwnerWithCustomSuffix() throws Exception { String remoteLogRootDir = "target/logs/"; String jobUser = "user1"; @@ -1378,7 +1390,8 @@ public void testGuessAppOwnerWithCustomSuffix() throws Exception { } } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testGuessAppOwnerWithCustomAppLogDir() throws Exception { String remoteLogRootDir = "target/logs/"; String remoteLogRootDir1 = "target/logs1/"; @@ -1411,7 +1424,8 @@ public void testGuessAppOwnerWithCustomAppLogDir() throws Exception { } } - @Test (timeout = 15000) + @Test + @Timeout(value = 15) public void testSaveContainerLogsLocally() throws Exception { String remoteLogRootDir = "target/logs/"; String rootLogDir = "target/LocalLogs"; @@ -1499,7 +1513,8 @@ private String readContainerContent(Path containerPath, } } - @Test (timeout = 15000) + @Test + @Timeout(value = 15) public void testPrintContainerLogMetadata() throws Exception { String remoteLogRootDir = "target/logs/"; conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true); @@ -1603,7 +1618,8 @@ public void testPrintContainerLogMetadata() throws Exception { fs.delete(new Path(rootLogDir), true); } - @Test (timeout = 15000) + @Test + @Timeout(value = 15) public void testListNodeInfo() throws Exception { String remoteLogRootDir = "target/logs/"; conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true); @@ -1653,7 +1669,8 @@ public void testListNodeInfo() throws Exception { fs.delete(new Path(rootLogDir), true); } - @Test (timeout = 15000) + @Test + @Timeout(value = 15) public void testFetchApplictionLogsHar() throws Exception { String remoteLogRootDir = "target/logs/"; conf.setBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, true); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestNodeAttributesCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestNodeAttributesCLI.java index 12ac21bc98118..dee4fc7b53c0d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestNodeAttributesCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestNodeAttributesCLI.java @@ -32,8 +32,8 @@ import org.apache.hadoop.yarn.api.records.NodeAttributeInfo; import org.apache.hadoop.yarn.api.records.NodeAttributeKey; import org.apache.hadoop.yarn.api.records.NodeToAttributeValue; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -54,8 +54,8 @@ import org.apache.hadoop.yarn.server.api.protocolrecords.NodeToAttributes; import org.apache.hadoop.yarn.server.api.protocolrecords.NodesToAttributesMappingRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.NodesToAttributesMappingResponse; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; @@ -78,7 +78,7 @@ public class TestNodeAttributesCLI { private String errOutput; private String sysOutput; - @Before + @BeforeEach public void configure() throws IOException, YarnException { admin = mock(ResourceManagerAdministrationProtocol.class); @@ -126,7 +126,7 @@ protected ApplicationClientProtocol createApplicationProtocol() @Test public void testHelp() throws Exception { String[] args = new String[] {"-help", "-replace"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains("-replace <\"node1:attribute[(type)][=value],attribute1" + "[=value],attribute2 node2:attribute2[=value],attribute3\">"); assertErrorContains("Replace the node to attributes mapping information at" @@ -137,14 +137,14 @@ public void testHelp() throws Exception { + " attribute to attribute type mapping."); args = new String[] {"-help", "-remove"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains( "-remove <\"node1:attribute,attribute1" + " node2:attribute2\">"); assertErrorContains("Removes the specified node to attributes mapping" + " information at the ResourceManager"); args = new String[] {"-help", "-add"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains("-add <\"node1:attribute[(type)][=value]," + "attribute1[=value],attribute2 node2:attribute2[=value]," + "attribute3\">"); @@ -156,33 +156,33 @@ public void testHelp() throws Exception { + " existing attribute to attribute type mapping."); args = new String[] {"-help", "-failOnUnknownNodes"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains("-failOnUnknownNodes"); assertErrorContains("Can be used optionally along with [add,remove," + "replace] options. When set, command will fail if specified nodes " + "are unknown."); args = new String[] {"-help", "-list"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains("-list"); assertErrorContains("List all attributes in cluster"); args = new String[] {"-help", "-nodes"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains("-nodes"); assertErrorContains( "Works with [list] to specify node hostnames whose mappings " + "are required to be displayed."); args = new String[] {"-help", "-attributes"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains("-attributes"); assertErrorContains( "Works with [attributestonodes] to specify attributes whose mapping " + "are required to be displayed."); args = new String[] {"-help", "-attributestonodes"}; - assertTrue("It should have succeeded help for replace", 0 == runTool(args)); + assertTrue(0 == runTool(args), "It should have succeeded help for replace"); assertErrorContains("-attributestonodes"); assertErrorContains("Displays mapping of attributes to nodes and attribute " + "values grouped by attributes"); @@ -195,27 +195,24 @@ public void testReplace() throws Exception { // -------------------------------- // parenthesis not match String[] args = new String[] {"-replace", "x("}; - assertTrue("It should have failed as no node is specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), "It should have failed as no node is specified"); assertFailureMessageContains(NodeAttributesCLI.INVALID_MAPPING_ERR_MSG); // parenthesis not match args = new String[] {"-replace", "x:(=abc"}; - assertTrue( - "It should have failed as no closing parenthesis is not specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should have failed as no closing parenthesis is not specified"); assertFailureMessageContains( "Attribute for node x is not properly configured : (=abc"); args = new String[] {"-replace", "x:()=abc"}; - assertTrue("It should have failed as no type specified inside parenthesis", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should have failed as no type specified inside parenthesis"); assertFailureMessageContains( "Attribute for node x is not properly configured : ()=abc"); args = new String[] {"-replace", ":x(string)"}; - assertTrue("It should have failed as no node is specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), "It should have failed as no node is specified"); assertFailureMessageContains("Node name cannot be empty"); // Not expected key=value specifying inner parenthesis @@ -226,15 +223,14 @@ public void testReplace() throws Exception { // Should fail as no attributes specified args = new String[] {"-replace"}; - assertTrue("Should fail as no attribute mappings specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), "Should fail as no attribute mappings specified"); assertFailureMessageContains(NodeAttributesCLI.MISSING_ARGUMENT); // no labels, should fail args = new String[] {"-replace", "-failOnUnknownNodes", "x:key(string)=value,key2=val2"}; - assertTrue("Should fail as no attribute mappings specified for replace", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "Should fail as no attribute mappings specified for replace"); assertFailureMessageContains(NodeAttributesCLI.MISSING_ARGUMENT); // no labels, should fail @@ -250,8 +246,8 @@ public void testReplace() throws Exception { // -------------------------------- args = new String[] {"-replace", "x:key(string)=value,key2=val2 y:key2=val23,key3 z:key4"}; - assertTrue("Should not fail as attribute has been properly mapped", - 0 == runTool(args)); + assertTrue(0 == runTool(args), + "Should not fail as attribute has been properly mapped"); List nodeAttributesList = new ArrayList<>(); List attributes = new ArrayList<>(); attributes.add( @@ -295,8 +291,8 @@ public void testRemove() throws Exception { // -------------------------------- // parenthesis not match String[] args = new String[] {"-remove", "x:"}; - assertTrue("It should have failed as no node is specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should have failed as no node is specified"); assertFailureMessageContains( "Attributes cannot be null or empty for Operation [remove] on the " + "node x"); @@ -305,8 +301,8 @@ public void testRemove() throws Exception { // -------------------------------- args = new String[] {"-remove", "x:key2,key3 z:key4", "-failOnUnknownNodes"}; - assertTrue("Should not fail as attribute has been properly mapped", - 0 == runTool(args)); + assertTrue(0 == runTool(args), + "Should not fail as attribute has been properly mapped"); List nodeAttributesList = new ArrayList<>(); List attributes = new ArrayList<>(); attributes @@ -334,8 +330,8 @@ public void testAdd() throws Exception { // -------------------------------- // parenthesis not match String[] args = new String[] {"-add", "x:"}; - assertTrue("It should have failed as no node is specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should have failed as no node is specified"); assertFailureMessageContains( "Attributes cannot be null or empty for Operation [add] on the node x"); // -------------------------------- @@ -343,8 +339,8 @@ public void testAdd() throws Exception { // -------------------------------- args = new String[] {"-add", "x:key2=123,key3=abc z:key4(string)", "-failOnUnknownNodes"}; - assertTrue("Should not fail as attribute has been properly mapped", - 0 == runTool(args)); + assertTrue(0 == runTool(args), + "Should not fail as attribute has been properly mapped"); List nodeAttributesList = new ArrayList<>(); List attributes = new ArrayList<>(); attributes.add( @@ -369,8 +365,8 @@ public void testAdd() throws Exception { // -------------------------------- args = new String[] {"-add", "x:key2=123,key3=abc x:key4(string)", "-failOnUnknownNodes"}; - assertTrue("Should not fail as attribute has been properly mapped", - 0 == runTool(args)); + assertTrue(0 == runTool(args), + "Should not fail as attribute has been properly mapped"); nodeAttributesList = new ArrayList<>(); attributes = new ArrayList<>(); attributes @@ -406,8 +402,8 @@ public GetClusterNodeAttributesResponse answer( // Success scenarios // -------------------------------- String[] args = new String[] {"-list"}; - assertTrue("It should be success since it list all attributes", - 0 == runTool(args)); + assertTrue(0 == runTool(args), + "It should be success since it list all attributes"); assertSysOutContains("Attribute\t Type", "rm.yarn.io/GPU\t STRING"); } @@ -433,21 +429,21 @@ public GetNodesToAttributesResponse answer( // Failure scenarios // -------------------------------- String[] args = new String[] {"-nodetoattributes", "-nodes"}; - assertTrue("It should not success since nodes are not specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should not success since nodes are not specified"); assertErrorContains(NodeAttributesCLI.INVALID_COMMAND_USAGE); // Missing argument for nodes args = new String[] {"-nodestoattributes", "-nodes"}; - assertTrue("It should not success since nodes are not specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should not success since nodes are not specified"); assertErrorContains(NodeAttributesCLI.MISSING_ARGUMENT); // -------------------------------- // Success with hostname param // -------------------------------- args = new String[] {"-nodestoattributes", "-nodes", "hostname"}; - assertTrue("Should return hostname to attributed list", 0 == runTool(args)); + assertTrue(0 == runTool(args), "Should return hostname to attributed list"); assertSysOutContains("hostname"); } @@ -473,8 +469,8 @@ public GetAttributesToNodesResponse answer( // Success scenarios // -------------------------------- String[] args = new String[] {"-attributestonodes"}; - assertTrue("It should be success since it list all attributes", - 0 == runTool(args)); + assertTrue(0 == runTool(args), + "It should be success since it list all attributes"); assertSysOutContains("Hostname\tAttribute-value", "rm.yarn.io/GPU :", "host1\t ARM"); @@ -482,17 +478,16 @@ public GetAttributesToNodesResponse answer( // fail scenario argument filter missing // -------------------------------- args = new String[] {"-attributestonodes", "-attributes"}; - assertTrue( - "It should not success since attributes for filter are not specified", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should not success since attributes for filter are not specified"); assertErrorContains(NodeAttributesCLI.MISSING_ARGUMENT); // -------------------------------- // fail scenario argument filter missing // -------------------------------- args = new String[] {"-attributestonodes", "-attributes", "fail/da/fail"}; - assertTrue("It should not success since attributes format is not correct", - 0 != runTool(args)); + assertTrue(0 != runTool(args), + "It should not success since attributes format is not correct"); assertErrorContains( "Attribute format not correct. Should be <[prefix]/[name]> " + ":fail/da/fail"); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java index 40cde4fe11b36..5eabdc598f902 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java @@ -18,10 +18,10 @@ package org.apache.hadoop.yarn.client.cli; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.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.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.argThat; @@ -77,9 +77,9 @@ import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.resource.ResourceUtils; import org.apache.hadoop.yarn.util.resource.Resources; -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.ArgumentCaptor; import org.mockito.ArgumentMatcher; import org.mockito.Mockito; @@ -100,7 +100,7 @@ public class TestRMAdminCLI { private static final String HOST_B = "1.2.3.2"; private static File dest; - @Before + @BeforeEach public void setup() throws Exception { ResourceUtils.resetResourceTypes(); Configuration yarnConf = new YarnConfiguration(); @@ -113,7 +113,7 @@ public void setup() throws Exception { ResourceUtils.getResourceTypes(); } - @After + @AfterEach public void teardown() { if (dest.exists()) { dest.delete(); @@ -121,7 +121,7 @@ public void teardown() { } @SuppressWarnings("static-access") - @Before + @BeforeEach public void configure() throws IOException, YarnException { remoteAdminServiceAccessed = false; admin = mock(ResourceManagerAdministrationProtocol.class); @@ -275,12 +275,10 @@ public void testUpdateNodeResource() throws Exception { NodeId nodeId = NodeId.fromString(nodeIdStr); Resource expectedResource = Resources.createResource(memSize, cores); ResourceOption resource = resourceMap.get(nodeId); - assertNotNull("resource for " + nodeIdStr + " shouldn't be null.", - resource); - assertEquals("resource value for " + nodeIdStr + " is not as expected.", - ResourceOption.newInstance(expectedResource, - ResourceOption.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT), - resource); + assertNotNull(resource, "resource for " + nodeIdStr + " shouldn't be null."); + assertEquals(ResourceOption.newInstance(expectedResource, + ResourceOption.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT), + resource, "resource value for " + nodeIdStr + " is not as expected."); } @Test @@ -301,10 +299,9 @@ public void testUpdateNodeResourceWithOverCommitTimeout() throws Exception { NodeId nodeId = NodeId.fromString(nodeIdStr); Resource expectedResource = Resources.createResource(memSize, cores); ResourceOption resource = resourceMap.get(nodeId); - assertNotNull("resource for " + nodeIdStr + " shouldn't be null.", - resource); - assertEquals("resource value for " + nodeIdStr + " is not as expected.", - ResourceOption.newInstance(expectedResource, timeout), resource); + assertNotNull(resource, "resource for " + nodeIdStr + " shouldn't be null."); + assertEquals(ResourceOption.newInstance(expectedResource, timeout), resource, + "resource value for " + nodeIdStr + " is not as expected."); } @Test @@ -347,11 +344,10 @@ public void testUpdateNodeResourceTypes() throws Exception { resource.getResource().getResourceInformation("memory-mb").getValue()); assertEquals("Mi", resource.getResource().getResourceInformation("memory-mb").getUnits()); - assertNotNull("resource for " + nodeIdStr + " shouldn't be null.", - resource); - assertEquals("resource value for " + nodeIdStr + " is not as expected.", - ResourceOption.newInstance(expectedResource, - ResourceOption.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT), resource); + assertNotNull(resource, "resource for " + nodeIdStr + " shouldn't be null."); + assertEquals(ResourceOption.newInstance(expectedResource, + ResourceOption.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT), resource, + "resource value for " + nodeIdStr + " is not as expected."); } @Test @@ -378,10 +374,9 @@ public void testUpdateNodeResourceTypesWithOverCommitTimeout() ResourceInformation.newInstance("resource2", "m", 2)); ResourceOption resource = resourceMap.get(nodeId); - assertNotNull("resource for " + nodeIdStr + " shouldn't be null.", - resource); - assertEquals("resource value for " + nodeIdStr + " is not as expected.", - ResourceOption.newInstance(expectedResource, timeout), resource); + assertNotNull(resource, "resource for " + nodeIdStr + " shouldn't be null."); + assertEquals(ResourceOption.newInstance(expectedResource, timeout), resource, + "resource value for " + nodeIdStr + " is not as expected."); } @Test @@ -807,9 +802,9 @@ public void testHelp() throws Exception { + "[-getServiceState ] [-getAllServiceState] " + "[-checkHealth ] [-help [cmd]]"; String actualHelpMsg = dataOut.toString(); - assertTrue(String.format("Help messages: %n " + actualHelpMsg + " %n doesn't include expected " + - "messages: %n" + expectedHelpMsg), actualHelpMsg.contains(expectedHelpMsg - )); + assertTrue(actualHelpMsg.contains(expectedHelpMsg), + String.format("Help messages: %n " + actualHelpMsg + " %n doesn't include expected " + + "messages: %n" + expectedHelpMsg)); } finally { System.setOut(oldOutPrintStream); System.setErr(oldErrPrintStream); @@ -1039,18 +1034,18 @@ public void testRemoveLabelsOnNodes() throws Exception { args = new String[] { "-replaceLabelsOnNode", "node1= node2=", "-directlyAccessNodeLabelStore" }; - assertTrue("Labels should get replaced even '=' is used ", - 0 == rmAdminCLI.run(args)); + assertTrue(0 == rmAdminCLI.run(args), + "Labels should get replaced even '=' is used "); } private void testError(String[] args, String template, ByteArrayOutputStream data, int resultCode) throws Exception { int actualResultCode = rmAdminCLI.run(args); - assertEquals("Expected result code: " + resultCode + - ", actual result code is: " + actualResultCode, resultCode, actualResultCode); - assertTrue(String.format("Expected error message: %n" + template + - " is not included in messages: %n" + data.toString()), - data.toString().contains(template)); + assertEquals(resultCode, actualResultCode, "Expected result code: " + resultCode + + ", actual result code is: " + actualResultCode); + assertTrue(data.toString().contains(template), + String.format("Expected error message: %n" + template + + " is not included in messages: %n" + data.toString())); data.reset(); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRouterCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRouterCLI.java index 61d9b2f4cdbe6..4538eeb031f92 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRouterCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRouterCLI.java @@ -36,8 +36,8 @@ import org.apache.hadoop.yarn.server.api.protocolrecords.GetSubClustersResponse; import org.apache.hadoop.yarn.server.api.protocolrecords.DeleteFederationQueuePoliciesRequest; import org.apache.hadoop.yarn.server.api.protocolrecords.DeleteFederationQueuePoliciesResponse; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import java.io.ByteArrayOutputStream; @@ -47,8 +47,8 @@ import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -59,7 +59,7 @@ public class TestRouterCLI { private RouterCLI rmAdminCLI; private final static int SUBCLUSTER_NUM = 4; - @Before + @BeforeEach public void setup() throws Exception { admin = mock(ResourceManagerAdministrationProtocol.class); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestSchedConfCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestSchedConfCLI.java index f939076906956..c0f9b1719aa31 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestSchedConfCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestSchedConfCLI.java @@ -24,8 +24,9 @@ import org.glassfish.jersey.test.JerseyTest; import org.glassfish.jersey.test.TestProperties; import org.junit.After; -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 java.io.ByteArrayOutputStream; import java.io.File; @@ -59,10 +60,10 @@ import javax.ws.rs.core.Application; import static org.apache.hadoop.yarn.webapp.JerseyTestBase.JERSEY_RANDOM_PORT; -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.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -140,7 +141,7 @@ protected void configure() { } } - @Before + @BeforeEach public void setUp() throws Exception { super.setUp(); cli = new SchedConfCLI(); @@ -173,19 +174,21 @@ public void cleanUp() throws Exception { super.tearDown(); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGetSchedulerConf() throws Exception { ByteArrayOutputStream sysOutStream = new ByteArrayOutputStream(); PrintStream sysOut = new PrintStream(sysOutStream); System.setOut(sysOut); int exitCode = cli.getSchedulerConf("", target()); - assertEquals("SchedConfCLI failed to run", 0, exitCode); - assertTrue("Failed to get scheduler configuration", - sysOutStream.toString().contains("testqueue")); + assertEquals(0, exitCode, "SchedConfCLI failed to run"); + assertTrue(sysOutStream.toString().contains("testqueue"), + "Failed to get scheduler configuration"); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testFormatSchedulerConf() throws Exception { ResourceScheduler scheduler = rm.getResourceScheduler(); @@ -212,7 +215,8 @@ public void testFormatSchedulerConf() throws Exception { assertNull(schedulerConf.get("schedKey1")); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testInvalidConf() throws Exception { ByteArrayOutputStream sysErrStream = new ByteArrayOutputStream(); PrintStream sysErr = new PrintStream(sysErrStream); @@ -228,12 +232,13 @@ public void testInvalidConf() throws Exception { private void executeCommand(ByteArrayOutputStream sysErrStream, String op, String queueConf) throws Exception { int exitCode = cli.run(new String[] {op, queueConf}); - assertNotEquals("Should return an error code", 0, exitCode); + assertNotEquals(0, exitCode, "Should return an error code"); assertTrue(sysErrStream.toString() .contains("Specify configuration key " + "value as confKey=confVal.")); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testAddQueues() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.addQueues("root.a:a1=aVal1,a2=aVal2,a3=", schedUpdateInfo); @@ -256,7 +261,8 @@ public void testAddQueues() { validateQueueConfigInfo(addQueueInfo, 1, "root.c", paramValues); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testAddQueuesWithCommaInValue() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.addQueues("root.a:a1=a1Val1\\,a1Val2 a1Val3,a2=a2Val1\\,a2Val2", @@ -268,7 +274,8 @@ public void testAddQueuesWithCommaInValue() { validateQueueConfigInfo(addQueueInfo, 0, "root.a", params); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testRemoveQueues() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.removeQueues("root.a;root.b;root.c.c1", schedUpdateInfo); @@ -279,7 +286,8 @@ public void testRemoveQueues() { assertEquals("root.c.c1", removeInfo.get(2)); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testUpdateQueues() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); Map paramValues = new HashMap<>(); @@ -313,7 +321,8 @@ private void validateQueueConfigInfo( paramValues.forEach((k, v) -> assertEquals(v, params.get(k))); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testUpdateQueuesWithCommaInValue() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.updateQueues("root.a:a1=a1Val1\\,a1Val2 a1Val3,a2=a2Val1\\,a2Val2", @@ -326,7 +335,8 @@ public void testUpdateQueuesWithCommaInValue() { validateQueueConfigInfo(updateQueueInfo, 0, "root.a", paramValues); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGlobalUpdate() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.globalUpdates("schedKey1=schedVal1,schedKey2=schedVal2", @@ -337,7 +347,8 @@ public void testGlobalUpdate() { validateGlobalParams(schedUpdateInfo, paramValues); } - @Test(timeout = 10000) + @Test + @Timeout(value = 10) public void testGlobalUpdateWithCommaInValue() { SchedConfUpdateInfo schedUpdateInfo = new SchedConfUpdateInfo(); cli.globalUpdates( diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestTopCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestTopCLI.java index 6aaab2f18fe16..aafce085b2b5b 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestTopCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestTopCLI.java @@ -36,12 +36,14 @@ import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.conf.YarnConfiguration; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test class for TopCli. @@ -60,7 +62,7 @@ public class TestTopCLI { private PrintStream stdout; private PrintStream stderr; - @BeforeClass + @BeforeAll public static void initializeDummyHostnameResolution() throws Exception { String previousIpAddress; for (String hostName : dummyHostNames) { @@ -72,7 +74,7 @@ public static void initializeDummyHostnameResolution() throws Exception { } } - @AfterClass + @AfterAll public static void restoreDummyHostnameResolution() throws Exception { for (Map.Entry hostnameToIpEntry : savedStaticResolution .entrySet()) { @@ -81,13 +83,13 @@ public static void restoreDummyHostnameResolution() throws Exception { } } - @Before + @BeforeEach public void before() { this.stdout = System.out; this.stderr = System.err; } - @After + @AfterEach public void after() { System.setOut(this.stdout); System.setErr(this.stderr); @@ -108,11 +110,11 @@ public void testHAClusterInfoURL() throws IOException, InterruptedException { topcli.getConf().set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); URL clusterUrl = topcli.getHAClusterUrl(conf, RM1_NODE_ID); - Assert.assertEquals("http", clusterUrl.getProtocol()); - Assert.assertEquals(rm1Address, clusterUrl.getAuthority()); + assertEquals("http", clusterUrl.getProtocol()); + assertEquals(rm1Address, clusterUrl.getAuthority()); clusterUrl = topcli.getHAClusterUrl(conf, RM2_NODE_ID); - Assert.assertEquals("http", clusterUrl.getProtocol()); - Assert.assertEquals(rm2Address, clusterUrl.getAuthority()); + assertEquals("http", clusterUrl.getProtocol()); + assertEquals(rm2Address, clusterUrl.getAuthority()); // https rm1Address = "host2:9088"; rm2Address = "host3:9088"; @@ -125,8 +127,8 @@ public void testHAClusterInfoURL() throws IOException, InterruptedException { conf.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); conf.set(YarnConfiguration.YARN_HTTP_POLICY_KEY, "HTTPS_ONLY"); clusterUrl = topcli.getHAClusterUrl(conf, RM1_NODE_ID); - Assert.assertEquals("https", clusterUrl.getProtocol()); - Assert.assertEquals(rm1Address, clusterUrl.getAuthority()); + assertEquals("https", clusterUrl.getProtocol()); + assertEquals(rm1Address, clusterUrl.getAuthority()); } @Test @@ -164,8 +166,8 @@ public void testHeaderNodeManagers() throws Exception { String expected = "NodeManager(s)" + ": 0 total, 3 active, 5 unhealthy, 1 decommissioning," + " 2 decommissioned, 4 lost, 6 rebooted, 7 shutdown"; - Assert.assertTrue( - String.format("Expected output to contain [%s], actual output was [%s].", expected, actual), - actual.contains(expected)); + assertTrue(actual.contains(expected), + String.format("Expected output to contain [%s], actual output was [%s].", + expected, actual)); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java index 25f7747df8817..08487595325d3 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestYarnCLI.java @@ -20,7 +20,11 @@ import org.apache.hadoop.yarn.api.records.NodeAttribute; import org.apache.hadoop.yarn.api.records.NodeAttributeType; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.isA; @@ -99,9 +103,9 @@ import org.apache.hadoop.yarn.util.Records; import org.apache.hadoop.yarn.util.Times; import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.PREFIX; -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.eclipse.jetty.util.log.Log; import org.slf4j.Logger; @@ -119,7 +123,7 @@ public class TestYarnCLI { private static final Pattern SPACES_PATTERN = Pattern.compile("\\s+|\\n+|\\t+"); - @Before + @BeforeEach public void setup() { sysOutStream = new ByteArrayOutputStream(); sysOut = spy(new PrintStream(sysOutStream)); @@ -197,7 +201,7 @@ public void testGetApplicationReport() throws Exception { pw.println(); pw.close(); String appReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appReportStr, sysOutStream.toString()); + assertEquals(appReportStr, sysOutStream.toString()); sysOutStream.reset(); verify(sysOut, times(1 + i)).println(isA(String.class)); } @@ -233,7 +237,7 @@ public void testGetApplicationAttemptReport() throws Exception { pw.println("\tDiagnostics : diagnostics"); pw.close(); String appReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appReportStr, sysOutStream.toString()); + assertEquals(appReportStr, sysOutStream.toString()); verify(sysOut, times(1)).println(isA(String.class)); } @@ -279,7 +283,7 @@ public void testGetApplicationAttempts() throws Exception { pw.println("\t url"); pw.close(); String appReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appReportStr, sysOutStream.toString()); + assertEquals(appReportStr, sysOutStream.toString()); } @Test @@ -322,7 +326,7 @@ public void testGetContainerReport() throws Exception { pw.close(); String appReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appReportStr, sysOutStream.toString()); + assertEquals(appReportStr, sysOutStream.toString()); verify(sysOut, times(1)).println(isA(String.class)); } @@ -386,7 +390,7 @@ public void testGetContainers() throws Exception { Log.getLog().info("OutputFrom command"); String actualOutput = sysOutStream.toString("UTF-8"); Log.getLog().info("["+actualOutput+"]"); - Assert.assertEquals(appReportStr, actualOutput); + assertEquals(appReportStr, actualOutput); } @Test @@ -401,7 +405,7 @@ public void testGetApplicationReportException() throws Exception { verify(sysOut).println( "Application with id '" + applicationId + "' doesn't exist in RM or Timeline Server."); - Assert.assertNotSame("should return non-zero exit code.", 0, exitCode); + assertNotSame(0, exitCode, "should return non-zero exit code."); } @Test @@ -516,7 +520,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); String appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(1)).write(any(byte[].class), anyInt(), anyInt()); //Test command yarn application -list --appTypes apptype1,apptype2 @@ -557,7 +561,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(2)).write(any(byte[].class), anyInt(), anyInt()); //Test command yarn application -list --appStates appState1,appState2 @@ -598,7 +602,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(3)).write(any(byte[].class), anyInt(), anyInt()); // Test command yarn application -list --appTypes apptype1,apptype2 @@ -637,7 +641,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(4)).write(any(byte[].class), anyInt(), anyInt()); //Test command yarn application -list --appStates with invalid appStates @@ -659,7 +663,7 @@ public void testGetApplications() throws Exception { pw.println(output.substring(0, output.length()-1)); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(4)).write(any(byte[].class), anyInt(), anyInt()); //Test command yarn application -list --appStates all @@ -718,7 +722,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(5)).write(any(byte[].class), anyInt(), anyInt()); // Test command yarn application user case insensitive @@ -754,7 +758,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(6)).write(any(byte[].class), anyInt(), anyInt()); // Test command yarn application with tags. @@ -788,7 +792,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(7)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -828,7 +832,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(8)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -857,7 +861,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(9)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -888,7 +892,7 @@ public void testGetApplications() throws Exception { pw.println("\t N/A"); pw.close(); appsReportStr = baos.toString("UTF-8"); - Assert.assertEquals(appsReportStr, sysOutStream.toString()); + assertEquals(appsReportStr, sysOutStream.toString()); verify(sysOut, times(10)).write(any(byte[].class), anyInt(), anyInt()); } @@ -938,14 +942,15 @@ private List getApplicationReports( return appReports; } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testAppsHelpCommand() throws Exception { ApplicationCLI cli = createAndGetAppCLI(); ApplicationCLI spyCli = spy(cli); int result = spyCli.run(new String[] { "application", "-help" }); - Assert.assertTrue(result == 0); + assertTrue(result == 0); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createApplicationCLIHelpMessage(), + assertEquals(createApplicationCLIHelpMessage(), sysOutStream.toString()); sysOutStream.reset(); @@ -953,18 +958,19 @@ public void testAppsHelpCommand() throws Exception { result = cli.run( new String[] { "application", "-status", nodeId.toString(), "args" }); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createApplicationCLIHelpMessage(), + assertEquals(createApplicationCLIHelpMessage(), sysOutStream.toString()); } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testAppAttemptsHelpCommand() throws Exception { ApplicationCLI cli = createAndGetAppCLI(); ApplicationCLI spyCli = spy(cli); int result = spyCli.run(new String[] { "applicationattempt", "-help" }); - Assert.assertTrue(result == 0); + assertTrue(result == 0); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createApplicationAttemptCLIHelpMessage(), + assertEquals(createApplicationAttemptCLIHelpMessage(), sysOutStream.toString()); sysOutStream.reset(); @@ -973,7 +979,7 @@ public void testAppAttemptsHelpCommand() throws Exception { new String[] {"applicationattempt", "-list", applicationId.toString(), "args" }); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createApplicationAttemptCLIHelpMessage(), + assertEquals(createApplicationAttemptCLIHelpMessage(), sysOutStream.toString()); sysOutStream.reset(); @@ -983,18 +989,19 @@ public void testAppAttemptsHelpCommand() throws Exception { new String[] { "applicationattempt", "-status", appAttemptId.toString(), "args" }); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createApplicationAttemptCLIHelpMessage(), + assertEquals(createApplicationAttemptCLIHelpMessage(), sysOutStream.toString()); } - @Test (timeout = 10000) + @Test + @Timeout(value = 10) public void testContainersHelpCommand() throws Exception { ApplicationCLI cli = createAndGetAppCLI(); ApplicationCLI spyCli = spy(cli); int result = spyCli.run(new String[] { "container", "-help" }); - Assert.assertTrue(result == 0); + assertTrue(result == 0); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createContainerCLIHelpMessage(), + assertEquals(createContainerCLIHelpMessage(), normalize(sysOutStream.toString())); sysOutStream.reset(); @@ -1004,7 +1011,7 @@ public void testContainersHelpCommand() throws Exception { result = cli.run( new String[] {"container", "-list", appAttemptId.toString(), "args" }); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createContainerCLIHelpMessage(), + assertEquals(createContainerCLIHelpMessage(), normalize(sysOutStream.toString())); sysOutStream.reset(); @@ -1012,15 +1019,16 @@ public void testContainersHelpCommand() throws Exception { result = cli.run( new String[] { "container", "-status", containerId.toString(), "args" }); verify(spyCli).printUsage(any(String.class), any(Options.class)); - Assert.assertEquals(createContainerCLIHelpMessage(), + assertEquals(createContainerCLIHelpMessage(), normalize(sysOutStream.toString())); } - @Test (timeout = 5000) + @Test + @Timeout(value = 5) public void testNodesHelpCommand() throws Exception { NodeCLI nodeCLI = createAndGetNodeCLI(); nodeCLI.run(new String[] {}); - Assert.assertEquals(createNodeCLIHelpMessage(), + assertEquals(createNodeCLIHelpMessage(), sysOutStream.toString()); } @@ -1063,12 +1071,12 @@ public void testKillApplication() throws Exception { cli.run(new String[] { "application","-kill", applicationId.toString() }); verify(sysOut).println("Application with id '" + applicationId + "' doesn't exist in RM."); - Assert.assertNotSame("should return non-zero exit code.", 0, exitCode); + assertNotSame(0, exitCode, "should return non-zero exit code."); } catch (ApplicationNotFoundException appEx) { - Assert.fail("application -kill should not throw" + + fail("application -kill should not throw" + "ApplicationNotFoundException. " + appEx); } catch (Exception e) { - Assert.fail("Unexpected exception: " + e); + fail("Unexpected exception: " + e); } } @@ -1139,7 +1147,7 @@ public void testKillApplications() throws Exception { .getApplicationReport(applicationId4); result = cli.run(new String[]{"application", "-kill", applicationId3.toString() + " " + applicationId4.toString()}); - Assert.assertNotEquals(0, result); + assertNotEquals(0, result); verify(sysOut).println( "Application with id 'application_1234_0007' doesn't exist in RM."); verify(sysOut).println( @@ -1158,14 +1166,14 @@ public void testKillApplications() throws Exception { newApplicationReport5); result = cli.run(new String[]{"application", "-kill", applicationId3.toString() + " " + applicationId1.toString()}); - Assert.assertEquals(0, result); + assertEquals(0, result); // Test Scenario 5: kill operation with some other command. sysOutStream.reset(); result = cli.run(new String[]{"application", "--appStates", "RUNNING", "-kill", applicationId3.toString() + " " + applicationId1.toString()}); - Assert.assertEquals(-1, result); - Assert.assertEquals(createApplicationCLIHelpMessage(), + assertEquals(-1, result); + assertEquals(createApplicationCLIHelpMessage(), sysOutStream.toString()); } @@ -1241,10 +1249,10 @@ public void testMoveApplicationAcrossQueues() throws Exception { try { result = cli.run(new String[] { "application", "-movetoqueue", applicationId.toString(), "-queue", "targetqueue"}); - Assert.fail(); + fail(); } catch (Exception ex) { - Assert.assertTrue(ex instanceof ApplicationNotFoundException); - Assert.assertEquals("Application with id '" + applicationId + + assertTrue(ex instanceof ApplicationNotFoundException); + assertEquals("Application with id '" + applicationId + "' doesn't exist in RM.", ex.getMessage()); } } @@ -1293,10 +1301,10 @@ public void testMoveApplicationAcrossQueuesWithNewCommand() throws Exception { try { result = cli.run(new String[]{"application", "-appId", applicationId.toString(), "-changeQueue", "targetqueue"}); - Assert.fail(); + fail(); } catch (Exception ex) { - Assert.assertTrue(ex instanceof ApplicationNotFoundException); - Assert.assertEquals( + assertTrue(ex instanceof ApplicationNotFoundException); + assertEquals( "Application with id '" + applicationId + "' doesn't exist in RM.", ex.getMessage()); } @@ -1331,7 +1339,7 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); String nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(1)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1354,13 +1362,13 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(2)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); result = cli.run(new String[] {"-list"}); assertEquals(0, result); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(3)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1389,7 +1397,7 @@ public void testListClusterNodes() throws Exception { pw.println("\tNode-Labels : "); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(4)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1410,7 +1418,7 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(5)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1431,7 +1439,7 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(6)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1452,7 +1460,7 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(7)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1473,7 +1481,7 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(8)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1506,7 +1514,7 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(9)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1541,7 +1549,7 @@ public void testListClusterNodes() throws Exception { pw.println(" 0"); pw.close(); nodesReportStr = baos.toString("UTF-8"); - Assert.assertEquals(nodesReportStr, sysOutStream.toString()); + assertEquals(nodesReportStr, sysOutStream.toString()); verify(sysOut, times(10)).write(any(byte[].class), anyInt(), anyInt()); sysOutStream.reset(); @@ -1695,26 +1703,26 @@ public void testMissingArguments() throws Exception { ApplicationCLI cli = createAndGetAppCLI(); int result = cli.run(new String[] { "application", "-status" }); assertThat(result).isEqualTo(-1); - Assert.assertEquals(String.format("Missing argument for options%n%1s", + assertEquals(String.format("Missing argument for options%n%1s", createApplicationCLIHelpMessage()), sysOutStream.toString()); sysOutStream.reset(); result = cli.run(new String[] { "applicationattempt", "-status" }); assertThat(result).isEqualTo(-1); - Assert.assertEquals(String.format("Missing argument for options%n%1s", + assertEquals(String.format("Missing argument for options%n%1s", createApplicationAttemptCLIHelpMessage()), sysOutStream.toString()); sysOutStream.reset(); result = cli.run(new String[] { "container", "-status" }); assertThat(result).isEqualTo(-1); - Assert.assertEquals(String.format("Missing argument for options %1s", + assertEquals(String.format("Missing argument for options %1s", createContainerCLIHelpMessage()), normalize(sysOutStream.toString())); sysOutStream.reset(); NodeCLI nodeCLI = createAndGetNodeCLI(); result = nodeCLI.run(new String[] { "-status" }); assertThat(result).isEqualTo(-1); - Assert.assertEquals(String.format("Missing argument for options%n%1s", + assertEquals(String.format("Missing argument for options%n%1s", createNodeCLIHelpMessage()), sysOutStream.toString()); } @@ -1751,7 +1759,7 @@ public void testGetQueueInfo() throws Exception { pw.println("\tIntra-queue Preemption : " + "enabled"); pw.close(); String queueInfoStr = baos.toString("UTF-8"); - Assert.assertEquals(queueInfoStr, sysOutStream.toString()); + assertEquals(queueInfoStr, sysOutStream.toString()); } @Test @@ -1775,7 +1783,7 @@ public void testGetQueueInfos() throws Exception { queueInfos.add(queueInfo3); when(client.getAllQueues()).thenReturn(queueInfos); int result = cli.run(new String[] {"-list", "all"}); - Assert.assertEquals(0, result); + assertEquals(0, result); verify(client).getAllQueues(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(baos); @@ -1796,7 +1804,7 @@ public void testGetQueueInfos() throws Exception { writer.print(formattingCLIUtils.render()); writer.close(); String queueInfoStr = baos.toString("UTF-8"); - Assert.assertEquals(queueInfoStr, sysOutStream.toString()); + assertEquals(queueInfoStr, sysOutStream.toString()); } @Test @@ -1837,10 +1845,10 @@ public void testGetQueueInfoOverrideIntraQueuePreemption() throws Exception { int result = cli.run(new String[] { "-status", "a" }); assertEquals(0, result); String queueStatusOut = sysOutStream.toString(); - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("\tPreemption : enabled")); // In-queue preemption is disabled at the "root.a" queue level - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("Intra-queue Preemption : disabled")); cli = createAndGetQueueCLI(yarnClient); sysOutStream.reset(); @@ -1848,10 +1856,10 @@ public void testGetQueueInfoOverrideIntraQueuePreemption() throws Exception { result = cli.run(new String[] { "-status", "a1" }); assertEquals(0, result); queueStatusOut = sysOutStream.toString(); - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("\tPreemption : enabled")); // In-queue preemption is enabled at the "root.a.a1" queue level - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("Intra-queue Preemption : enabled")); } finally { // clean-up @@ -1892,9 +1900,9 @@ public void testGetQueueInfoPreemptionEnabled() throws Exception { int result = cli.run(new String[] { "-status", "a1" }); assertEquals(0, result); String queueStatusOut = sysOutStream.toString(); - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("\tPreemption : enabled")); - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("Intra-queue Preemption : enabled")); } finally { // clean-up @@ -1933,9 +1941,9 @@ public void testGetQueueInfoPreemptionDisabled() throws Exception { int result = cli.run(new String[] { "-status", "a1" }); assertEquals(0, result); String queueStatusOut = sysOutStream.toString(); - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("\tPreemption : disabled")); - Assert.assertTrue(queueStatusOut + assertTrue(queueStatusOut .contains("Intra-queue Preemption : disabled")); } } @@ -1970,7 +1978,7 @@ public void testGetQueueInfoWithEmptyNodeLabel() throws Exception { pw.println("\tIntra-queue Preemption : " + "disabled"); pw.close(); String queueInfoStr = baos.toString("UTF-8"); - Assert.assertEquals(queueInfoStr, sysOutStream.toString()); + assertEquals(queueInfoStr, sysOutStream.toString()); } @Test @@ -2014,7 +2022,7 @@ public void testGetQueueInfoWithFairScheduler() throws Exception { pw.println("\tQueue Preemption : enabled"); pw.close(); String queueInfoStr = baos.toString("UTF-8"); - Assert.assertEquals(queueInfoStr, sysOutStream.toString()); + assertEquals(queueInfoStr, sysOutStream.toString()); } @Test @@ -2062,7 +2070,7 @@ public void testGetQueueInfoWithFairSchedulerAndSubClusterId() throws Exception pw.println("\tQueue Preemption : " + "enabled"); pw.close(); String queueInfoStr = baos.toString("UTF-8"); - Assert.assertEquals(queueInfoStr, sysOutStream.toString()); + assertEquals(queueInfoStr, sysOutStream.toString()); } @Test @@ -2078,7 +2086,7 @@ public void testGetQueueInfoWithNonExistedQueue() throws Exception { + ", please check."); pw.close(); String queueInfoStr = baos.toString("UTF-8"); - Assert.assertEquals(queueInfoStr, sysOutStream.toString()); + assertEquals(queueInfoStr, sysOutStream.toString()); } @Test @@ -2096,7 +2104,7 @@ public void testGetApplicationAttemptReportException() throws Exception { verify(sysOut).println( "Application for AppAttempt with id '" + attemptId1 + "' doesn't exist in RM or Timeline Server."); - Assert.assertNotSame("should return non-zero exit code.", 0, exitCode); + assertNotSame(0, exitCode, "should return non-zero exit code."); ApplicationAttemptId attemptId2 = ApplicationAttemptId.newInstance( applicationId, 2); @@ -2110,7 +2118,7 @@ public void testGetApplicationAttemptReportException() throws Exception { verify(sysOut).println( "Application Attempt with id '" + attemptId2 + "' doesn't exist in RM or Timeline Server."); - Assert.assertNotSame("should return non-zero exit code.", 0, exitCode); + assertNotSame(0, exitCode, "should return non-zero exit code."); } @Test @@ -2130,7 +2138,7 @@ public void testGetContainerReportException() throws Exception { verify(sysOut).println( "Application for Container with id '" + containerId1 + "' doesn't exist in RM or Timeline Server."); - Assert.assertNotSame("should return non-zero exit code.", 0, exitCode); + assertNotSame(0, exitCode, "should return non-zero exit code."); ContainerId containerId2 = ContainerId.newContainerId(attemptId, cntId++); when(client.getContainerReport(containerId2)).thenThrow( new ApplicationAttemptNotFoundException( @@ -2142,7 +2150,7 @@ public void testGetContainerReportException() throws Exception { verify(sysOut).println( "Application Attempt for Container with id '" + containerId2 + "' doesn't exist in RM or Timeline Server."); - Assert.assertNotSame("should return non-zero exit code.", 0, exitCode); + assertNotSame(0, exitCode, "should return non-zero exit code."); ContainerId containerId3 = ContainerId.newContainerId(attemptId, cntId++); when(client.getContainerReport(containerId3)).thenThrow( @@ -2153,10 +2161,11 @@ public void testGetContainerReportException() throws Exception { verify(sysOut).println( "Container with id '" + containerId3 + "' doesn't exist in RM or Timeline Server."); - Assert.assertNotSame("should return non-zero exit code.", 0, exitCode); + assertNotSame(0, exitCode, "should return non-zero exit code."); } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testUpdateApplicationPriority() throws Exception { ApplicationCLI cli = createAndGetAppCLI(); ApplicationId applicationId = ApplicationId.newInstance(1234, 6); @@ -2186,7 +2195,7 @@ public void testFailApplicationAttempt() throws Exception { ApplicationCLI cli = createAndGetAppCLI(); int exitCode = cli.run(new String[] {"applicationattempt", "-fail", "appattempt_1444199730803_0003_000001"}); - Assert.assertEquals(0, exitCode); + assertEquals(0, exitCode); verify(client).failApplicationAttempt(any(ApplicationAttemptId.class)); verifyNoMoreInteractions(client); @@ -2552,7 +2561,8 @@ public void testAppAttemptReportWhileContainerIsNotAssigned() assertEquals(0, result); } - @Test(timeout = 60000) + @Test + @Timeout(value = 60) public void testUpdateApplicationTimeout() throws Exception { ApplicationCLI cli = createAndGetAppCLI(); ApplicationId applicationId = ApplicationId.newInstance(1234, 6); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestFormattingCLIUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestFormattingCLIUtils.java index d890fb5836ade..2f70dcabbe652 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestFormattingCLIUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestFormattingCLIUtils.java @@ -18,7 +18,7 @@ package org.apache.hadoop.yarn.client.util; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.URISyntaxException; @@ -28,7 +28,7 @@ import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class TestFormattingCLIUtils { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestYarnClientUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestYarnClientUtils.java index 42300a0985143..b7c502bd56dde 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestYarnClientUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/util/TestYarnClientUtils.java @@ -24,8 +24,10 @@ import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.conf.YarnConfiguration; -import org.junit.Test; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for the YarnClientUtils class @@ -46,8 +48,8 @@ public void testGetRMPrincipalStandAlone_Configuration() throws IOException { String result = YarnClientUtils.getRmPrincipal(conf); - assertNull("The hostname translation did return null when the principal is " - + "missing from the conf: " + result, result); + assertNull(result, "The hostname translation did return null when the principal is " + + "missing from the conf: " + result); conf = new Configuration(); @@ -57,15 +59,17 @@ public void testGetRMPrincipalStandAlone_Configuration() throws IOException { result = YarnClientUtils.getRmPrincipal(conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/myhost@REALM", result); + assertEquals("test/myhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); conf.set(YarnConfiguration.RM_PRINCIPAL, "test/yourhost@REALM"); result = YarnClientUtils.getRmPrincipal(conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/yourhost@REALM", result); + assertEquals("test/yourhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); } /** @@ -83,8 +87,8 @@ public void testGetRMPrincipalHA_Configuration() throws IOException { String result = YarnClientUtils.getRmPrincipal(conf); - assertNull("The hostname translation did return null when the principal is " - + "missing from the conf: " + result, result); + assertNull(result, "The hostname translation did return null when the principal is " + + "missing from the conf: " + result); conf = new Configuration(); @@ -95,8 +99,9 @@ public void testGetRMPrincipalHA_Configuration() throws IOException { result = YarnClientUtils.getRmPrincipal(conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/myhost@REALM", result); + assertEquals("test/myhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); conf = new Configuration(); @@ -121,15 +126,17 @@ public void testGetRMPrincipalHA_Configuration() throws IOException { result = YarnClientUtils.getRmPrincipal(conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/myhost@REALM", result); + assertEquals("test/myhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); conf.set(YarnConfiguration.RM_PRINCIPAL, "test/yourhost@REALM"); result = YarnClientUtils.getRmPrincipal(conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/yourhost@REALM", result); + assertEquals("test/yourhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); } /** @@ -147,13 +154,15 @@ public void testGetRMPrincipalStandAlone_String() throws IOException { String result = YarnClientUtils.getRmPrincipal("test/_HOST@REALM", conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/myhost@REALM", result); + assertEquals("test/myhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); result = YarnClientUtils.getRmPrincipal("test/yourhost@REALM", conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/yourhost@REALM", result); + assertEquals("test/yourhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); try { result = YarnClientUtils.getRmPrincipal(null, conf); @@ -180,8 +189,9 @@ public void testGetRMPrincipalHA_String() throws IOException { String result = YarnClientUtils.getRmPrincipal("test/_HOST@REALM", conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/myhost@REALM", result); + assertEquals("test/myhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); try { result = YarnClientUtils.getRmPrincipal(null, conf); @@ -211,13 +221,15 @@ public void testGetRMPrincipalHA_String() throws IOException { result = YarnClientUtils.getRmPrincipal("test/_HOST@REALM", conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/myhost@REALM", result); + assertEquals("test/myhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); result = YarnClientUtils.getRmPrincipal("test/yourhost@REALM", conf); - assertEquals("The hostname translation did not produce the expected " - + "results: " + result, "test/yourhost@REALM", result); + assertEquals("test/yourhost@REALM", result, + "The hostname translation did not produce the expected " + + "results: " + result); } /** @@ -235,9 +247,9 @@ public void testGetYarnConfWithRmHaId() throws IOException { YarnConfiguration result = YarnClientUtils.getYarnConfWithRmHaId(conf); assertSameConf(conf, result); - assertEquals("RM_HA_ID was changed when it shouldn't have been: " - + result.get(YarnConfiguration.RM_HA_ID), "rm0", - result.get(YarnConfiguration.RM_HA_ID)); + assertEquals("rm0", result.get(YarnConfiguration.RM_HA_ID), + "RM_HA_ID was changed when it shouldn't have been: " + + result.get(YarnConfiguration.RM_HA_ID)); conf = new Configuration(); @@ -247,9 +259,9 @@ public void testGetYarnConfWithRmHaId() throws IOException { result = YarnClientUtils.getYarnConfWithRmHaId(conf); assertSameConf(conf, result); - assertEquals("RM_HA_ID was changed when it shouldn't have been: " - + result.get(YarnConfiguration.RM_HA_ID), "rm0", - result.get(YarnConfiguration.RM_HA_ID)); + assertEquals("rm0", result.get(YarnConfiguration.RM_HA_ID), + "RM_HA_ID was changed when it shouldn't have been: " + + result.get(YarnConfiguration.RM_HA_ID)); conf = new Configuration(); @@ -259,9 +271,9 @@ public void testGetYarnConfWithRmHaId() throws IOException { result = YarnClientUtils.getYarnConfWithRmHaId(conf); assertSameConf(conf, result); - assertEquals("RM_HA_ID was not set correctly: " - + result.get(YarnConfiguration.RM_HA_ID), "rm0", - result.get(YarnConfiguration.RM_HA_ID)); + assertEquals("rm0", result.get(YarnConfiguration.RM_HA_ID), + "RM_HA_ID was not set correctly: " + + result.get(YarnConfiguration.RM_HA_ID)); conf = new Configuration(); @@ -298,8 +310,8 @@ private void assertSameConf(Configuration master, YarnConfiguration copy) { if (!seen.add(key)) { // Here we use master.get() instead of property.getValue() because // they're not the same thing. - assertEquals("New configuration changed the value of " - + key, master.get(key), copy.get(key)); + assertEquals(master.get(key), copy.get(key), + "New configuration changed the value of " + key); } } @@ -310,9 +322,8 @@ private void assertSameConf(Configuration master, YarnConfiguration copy) { String key = property.getKey(); if (!seen.contains(property.getKey())) { - assertEquals("New configuration changed the value of " - + key, copy.get(key), - master.get(key)); + assertEquals(copy.get(key), + master.get(key), "New configuration changed the value of " + key); } } }