diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/pom.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/pom.xml
index df87a7b18efff..566deec511feb 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/pom.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/pom.xml
@@ -105,13 +105,18 @@
test
- org.junit.vintage
- junit-vintage-engine
+ org.slf4j
+ slf4j-api
+
+
+ org.mockito
+ mockito-junit-jupiter
test
- org.slf4j
- slf4j-api
+ org.junit.vintage
+ junit-vintage-engine
+ test
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.java
index c3d46bb8095f3..19db09dca45d6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.java
@@ -20,6 +20,9 @@
import java.io.File;
import java.io.IOException;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -28,8 +31,8 @@
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.TestContainerManager;
-import org.junit.After;
-import org.junit.Assume;
+
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
public class TestContainerManagerWithLCE extends TestContainerManager {
@@ -49,10 +52,10 @@ public TestContainerManagerWithLCE() throws UnsupportedFileSystemException {
TestContainerManagerWithLCE.class.getName() + "-tmpDir");
}
+ @BeforeEach
@Override
public void setup() throws IOException {
- Assume.assumeTrue("LCE binary path is not passed. Not running the test",
- shouldRunTest());
+ assumeTrue(shouldRunTest(), "LCE binary path is not passed. Not running the test");
super.setup();
localFS.setPermission(new Path(localDir.getCanonicalPath()),
new FsPermission(
@@ -62,7 +65,7 @@ public void setup() throws IOException {
(short) 0777));
}
- @After
+ @AfterEach
@Override
public void tearDown() throws IOException, InterruptedException {
if (shouldRunTest()) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java
index db442797108a6..0e58176637f66 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java
@@ -69,9 +69,8 @@
import org.apache.hadoop.yarn.server.nodemanager.timelineservice.NMTimelinePublisher;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.Records;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -90,6 +89,10 @@
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
/**
* Base class for all the AMRMProxyService test cases. It provides utility
* methods that can be used by the concrete test case classes
@@ -108,16 +111,16 @@ public abstract class BaseAMRMProxyTest {
private Context nmContext;
protected MockAMRMProxyService getAMRMProxyService() {
- Assert.assertNotNull(this.amrmProxyService);
+ assertNotNull(this.amrmProxyService);
return this.amrmProxyService;
}
protected Context getNMContext() {
- Assert.assertNotNull(this.nmContext);
+ assertNotNull(this.nmContext);
return this.nmContext;
}
- @Before
+ @BeforeEach
public void setUp() throws IOException {
this.conf = createConfiguration();
this.dispatcher = new AsyncDispatcher();
@@ -144,7 +147,7 @@ protected YarnConfiguration createConfiguration() {
return config;
}
- @After
+ @AfterEach
public void tearDown() {
this.amrmProxyService.stop();
this.amrmProxyService = null;
@@ -311,8 +314,8 @@ protected List> registerApplication
int index = testContexts.indexOf(testContext);
response = new RegisterApplicationMasterResponseInfo<>(
registerApplicationMaster(index), testContext);
- Assert.assertNotNull(response.getResponse());
- Assert.assertEquals(Integer.toString(index), response.getResponse().getQueue());
+ assertNotNull(response.getResponse());
+ assertEquals(Integer.toString(index), response.getResponse().getQueue());
LOG.info("Successfully registered application master with test context: {}.",
testContext);
@@ -325,8 +328,8 @@ protected List> registerApplication
return response;
});
- Assert.assertEquals("Number of responses received does not match with request",
- testContexts.size(), responses.size());
+ assertEquals(testContexts.size(), responses.size(),
+ "Number of responses received does not match with request");
Set contextResponses = new TreeSet<>();
for (RegisterApplicationMasterResponseInfo item : responses) {
@@ -334,7 +337,7 @@ protected List> registerApplication
}
for (T ep : testContexts) {
- Assert.assertTrue(contextResponses.contains(ep));
+ assertTrue(contextResponses.contains(ep));
}
return responses;
@@ -387,7 +390,7 @@ protected List> finishApplicationMast
response = new FinishApplicationMasterResponseInfo<>(
finishApplicationMaster(testContexts.indexOf(testContext),
FinalApplicationStatus.SUCCEEDED), testContext);
- Assert.assertNotNull(response.getResponse());
+ assertNotNull(response.getResponse());
LOG.info("Successfully finished application master with test contexts: {}.",
testContext);
@@ -399,18 +402,18 @@ protected List> finishApplicationMast
return response;
});
- Assert.assertEquals("Number of responses received does not match with request",
- testContexts.size(), responses.size());
+ assertEquals(testContexts.size(), responses.size(),
+ "Number of responses received does not match with request");
Set contextResponses = new TreeSet<>();
for (FinishApplicationMasterResponseInfo item : responses) {
- Assert.assertNotNull(item);
- Assert.assertNotNull(item.getResponse());
+ assertNotNull(item);
+ assertNotNull(item.getResponse());
contextResponses.add(item.getTestContext());
}
for (T ep : testContexts) {
- Assert.assertTrue(contextResponses.contains(ep));
+ assertTrue(contextResponses.contains(ep));
}
return responses;
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyMetrics.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyMetrics.java
index f4c10eb31a34b..b580e90a94b13 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyMetrics.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyMetrics.java
@@ -22,39 +22,43 @@
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterResponse;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
public class TestAMRMProxyMetrics extends BaseAMRMProxyTest {
public static final Logger LOG =
LoggerFactory.getLogger(TestAMRMProxyMetrics.class);
private static AMRMProxyMetrics metrics;
- @BeforeClass
+ @BeforeAll
public static void init() {
metrics = AMRMProxyMetrics.getMetrics();
LOG.info("Test: aggregate metrics are initialized correctly");
- Assert.assertEquals(0, metrics.getFailedAppStartRequests());
- Assert.assertEquals(0, metrics.getFailedRegisterAMRequests());
- Assert.assertEquals(0, metrics.getFailedFinishAMRequests());
- Assert.assertEquals(0, metrics.getFailedAllocateRequests());
- Assert.assertEquals(0, metrics.getFailedAppRecoveryCount());
- Assert.assertEquals(0, metrics.getFailedAppStopRequests());
- Assert.assertEquals(0, metrics.getFailedUpdateAMRMTokenRequests());
- Assert.assertEquals(0, metrics.getAllocateCount());
- Assert.assertEquals(0, metrics.getRequestCount());
-
- Assert.assertEquals(0, metrics.getNumSucceededAppStartRequests());
- Assert.assertEquals(0, metrics.getNumSucceededRegisterAMRequests());
- Assert.assertEquals(0, metrics.getNumSucceededFinishAMRequests());
- Assert.assertEquals(0, metrics.getNumSucceededAllocateRequests());
- Assert.assertEquals(0, metrics.getNumSucceededRecoverRequests());
- Assert.assertEquals(0, metrics.getNumSucceededAppStopRequests());
- Assert.assertEquals(0, metrics.getNumSucceededUpdateAMRMTokenRequests());
+ assertEquals(0, metrics.getFailedAppStartRequests());
+ assertEquals(0, metrics.getFailedRegisterAMRequests());
+ assertEquals(0, metrics.getFailedFinishAMRequests());
+ assertEquals(0, metrics.getFailedAllocateRequests());
+ assertEquals(0, metrics.getFailedAppRecoveryCount());
+ assertEquals(0, metrics.getFailedAppStopRequests());
+ assertEquals(0, metrics.getFailedUpdateAMRMTokenRequests());
+ assertEquals(0, metrics.getAllocateCount());
+ assertEquals(0, metrics.getRequestCount());
+
+ assertEquals(0, metrics.getNumSucceededAppStartRequests());
+ assertEquals(0, metrics.getNumSucceededRegisterAMRequests());
+ assertEquals(0, metrics.getNumSucceededFinishAMRequests());
+ assertEquals(0, metrics.getNumSucceededAllocateRequests());
+ assertEquals(0, metrics.getNumSucceededRecoverRequests());
+ assertEquals(0, metrics.getNumSucceededAppStopRequests());
+ assertEquals(0, metrics.getNumSucceededUpdateAMRMTokenRequests());
LOG.info("Test: aggregate metrics are updated correctly");
}
@@ -76,33 +80,33 @@ public void testAllocateRequestWithNullValues() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse = registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
- Assert.assertEquals(Integer.toString(testAppId), registerResponse.getQueue());
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(testAppId), registerResponse.getQueue());
AllocateResponse allocateResponse = allocate(testAppId);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
FinishApplicationMasterResponse finishResponse =
finishApplicationMaster(testAppId, FinalApplicationStatus.SUCCEEDED);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
- Assert.assertEquals(failedAppStartRequests, metrics.getFailedAppStartRequests());
- Assert.assertEquals(failedRegisterAMRequests, metrics.getFailedRegisterAMRequests());
- Assert.assertEquals(failedFinishAMRequests, metrics.getFailedFinishAMRequests());
- Assert.assertEquals(failedAllocateRequests, metrics.getFailedAllocateRequests());
- Assert.assertEquals(failedAppRecoveryRequests, metrics.getFailedAppRecoveryCount());
- Assert.assertEquals(failedAppStopRequests, metrics.getFailedAppStopRequests());
- Assert.assertEquals(failedUpdateAMRMTokenRequests, metrics.getFailedUpdateAMRMTokenRequests());
+ assertEquals(failedAppStartRequests, metrics.getFailedAppStartRequests());
+ assertEquals(failedRegisterAMRequests, metrics.getFailedRegisterAMRequests());
+ assertEquals(failedFinishAMRequests, metrics.getFailedFinishAMRequests());
+ assertEquals(failedAllocateRequests, metrics.getFailedAllocateRequests());
+ assertEquals(failedAppRecoveryRequests, metrics.getFailedAppRecoveryCount());
+ assertEquals(failedAppStopRequests, metrics.getFailedAppStopRequests());
+ assertEquals(failedUpdateAMRMTokenRequests, metrics.getFailedUpdateAMRMTokenRequests());
- Assert.assertEquals(succeededAppStartRequests,
+ assertEquals(succeededAppStartRequests,
metrics.getNumSucceededAppStartRequests());
- Assert.assertEquals(1 + succeededRegisterAMRequests,
+ assertEquals(1 + succeededRegisterAMRequests,
metrics.getNumSucceededRegisterAMRequests());
- Assert.assertEquals(1 + succeededFinishAMRequests,
+ assertEquals(1 + succeededFinishAMRequests,
metrics.getNumSucceededFinishAMRequests());
- Assert.assertEquals(1 + succeededAllocateRequests,
+ assertEquals(1 + succeededAllocateRequests,
metrics.getNumSucceededAllocateRequests());
}
@@ -122,42 +126,40 @@ public void testFinishOneApplicationMasterWithFailure() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
- Assert
- .assertEquals(Integer.toString(testAppId), registerResponse.getQueue());
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(testAppId), registerResponse.getQueue());
FinishApplicationMasterResponse finishResponse =
finishApplicationMaster(testAppId, FinalApplicationStatus.FAILED);
- Assert.assertNotNull(finishResponse);
+ assertNotNull(finishResponse);
try {
// Try to finish an application master that is already finished.
finishApplicationMaster(testAppId, FinalApplicationStatus.SUCCEEDED);
- Assert
- .fail("The request to finish application master should have failed");
+ fail("The request to finish application master should have failed");
} catch (Throwable ex) {
// This is expected. So nothing required here.
LOG.info("Finish registration failed as expected because it was not "
+ "registered");
}
- Assert.assertEquals(failedAppStartRequests,
+ assertEquals(failedAppStartRequests,
metrics.getFailedAppStartRequests());
- Assert.assertEquals(failedRegisterAMRequests,
+ assertEquals(failedRegisterAMRequests,
metrics.getFailedRegisterAMRequests());
- Assert.assertEquals(1 + failedFinishAMRequests,
+ assertEquals(1 + failedFinishAMRequests,
metrics.getFailedFinishAMRequests());
- Assert.assertEquals(failedAllocateRequests,
+ assertEquals(failedAllocateRequests,
metrics.getFailedAllocateRequests());
- Assert.assertEquals(succeededAppStartRequests,
+ assertEquals(succeededAppStartRequests,
metrics.getNumSucceededAppStartRequests());
- Assert.assertEquals(1 + succeededRegisterAMRequests,
+ assertEquals(1 + succeededRegisterAMRequests,
metrics.getNumSucceededRegisterAMRequests());
- Assert.assertEquals(1 + succeededFinishAMRequests,
+ assertEquals(1 + succeededFinishAMRequests,
metrics.getNumSucceededFinishAMRequests());
- Assert.assertEquals(succeededAllocateRequests,
+ assertEquals(succeededAllocateRequests,
metrics.getNumSucceededAllocateRequests());
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyService.java
index 30ed6b61a481c..37b66ac4a7ab2 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyService.java
@@ -45,8 +45,14 @@
import org.apache.hadoop.yarn.server.nodemanager.amrmproxy.AMRMProxyService.RequestInterceptorChainWrapper;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService.RecoveredAMRMProxyState;
import org.apache.hadoop.yarn.util.Records;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
public class TestAMRMProxyService extends BaseAMRMProxyTest {
@@ -70,11 +76,11 @@ public void testRequestInterceptorChainCreation() throws Exception {
case 0:
case 1:
case 2:
- Assert.assertEquals(PassThroughRequestInterceptor.class.getName(),
+ assertEquals(PassThroughRequestInterceptor.class.getName(),
root.getClass().getName());
break;
case 3:
- Assert.assertEquals(MockRequestInterceptor.class.getName(), root.getClass().getName());
+ assertEquals(MockRequestInterceptor.class.getName(), root.getClass().getName());
break;
}
@@ -82,8 +88,8 @@ public void testRequestInterceptorChainCreation() throws Exception {
index++;
}
- Assert.assertEquals("The number of interceptors in chain does not match",
- Integer.toString(4), Integer.toString(index));
+ assertEquals(Integer.toString(4), Integer.toString(index),
+ "The number of interceptors in chain does not match");
}
@@ -99,8 +105,8 @@ public void testRegisterOneApplicationMaster() throws Exception {
// name
int testAppId = 1;
RegisterApplicationMasterResponse response1 = registerApplicationMaster(testAppId);
- Assert.assertNotNull(response1);
- Assert.assertEquals(Integer.toString(testAppId), response1.getQueue());
+ assertNotNull(response1);
+ assertEquals(Integer.toString(testAppId), response1.getQueue());
}
/**
@@ -120,13 +126,13 @@ public void testInterceptorInitFailure() throws IOException {
int testAppId = 1;
try {
registerApplicationMaster(testAppId);
- Assert.fail("Should not reach here. Expecting an exception thrown");
+ fail("Should not reach here. Expecting an exception thrown");
} catch (Exception e) {
Map pipelines =
getAMRMProxyService().getPipelines();
ApplicationId id = getApplicationId(testAppId);
- Assert.assertNull("The interceptor pipeline should be removed if initialization fails",
- pipelines.get(id));
+ assertNull(pipelines.get(id),
+ "The interceptor pipeline should be removed if initialization fails");
}
}
@@ -140,8 +146,8 @@ public void testInterceptorInitFailure() throws IOException {
public void testRegisterMultipleApplicationMasters() throws Exception {
for (int testAppId = 0; testAppId < 3; testAppId++) {
RegisterApplicationMasterResponse response = registerApplicationMaster(testAppId);
- Assert.assertNotNull(response);
- Assert.assertEquals(Integer.toString(testAppId), response.getQueue());
+ assertNotNull(response);
+ assertEquals(Integer.toString(testAppId), response.getQueue());
}
}
@@ -174,16 +180,16 @@ public void testFinishOneApplicationMasterWithSuccess() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
- Assert.assertEquals(Integer.toString(testAppId),
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(testAppId),
registerResponse.getQueue());
FinishApplicationMasterResponse finishResponse =
finishApplicationMaster(testAppId,
FinalApplicationStatus.SUCCEEDED);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
}
@Test
@@ -191,20 +197,19 @@ public void testFinishOneApplicationMasterWithFailure() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
- Assert.assertEquals(Integer.toString(testAppId),
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(testAppId),
registerResponse.getQueue());
FinishApplicationMasterResponse finishResponse =
finishApplicationMaster(testAppId, FinalApplicationStatus.FAILED);
- Assert.assertNotNull(finishResponse);
+ assertNotNull(finishResponse);
try {
// Try to finish an application master that is already finished.
finishApplicationMaster(testAppId, FinalApplicationStatus.SUCCEEDED);
- Assert
- .fail("The request to finish application master should have failed");
+ fail("The request to finish application master should have failed");
} catch (Throwable ex) {
// This is expected. So nothing required here.
LOG.info("Finish registration failed as expected because it was not registered");
@@ -216,8 +221,7 @@ public void testFinishInvalidApplicationMaster() {
try {
// Try to finish an application master that was not registered.
finishApplicationMaster(4, FinalApplicationStatus.SUCCEEDED);
- Assert
- .fail("The request to finish application master should have failed");
+ fail("The request to finish application master should have failed");
} catch (Throwable ex) {
// This is expected. So nothing required here.
LOG.info("Finish registration failed as expected because it was not registered");
@@ -230,8 +234,8 @@ public void testFinishMultipleApplicationMasters() throws Exception {
for (int index = 0; index < numberOfRequests; index++) {
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(index);
- Assert.assertNotNull(registerResponse);
- Assert.assertEquals(Integer.toString(index),
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(index),
registerResponse.getQueue());
}
@@ -240,18 +244,17 @@ public void testFinishMultipleApplicationMasters() throws Exception {
FinishApplicationMasterResponse finishResponse =
finishApplicationMaster(index, FinalApplicationStatus.SUCCEEDED);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
// Assert that the application has been removed from the collection
- Assert.assertEquals(this.getAMRMProxyService().getPipelines().size(), index);
+ assertEquals(this.getAMRMProxyService().getPipelines().size(), index);
}
try {
// Try to finish an application master that is already finished.
finishApplicationMaster(1, FinalApplicationStatus.SUCCEEDED);
- Assert
- .fail("The request to finish application master should have failed");
+ fail("The request to finish application master should have failed");
} catch (Throwable ex) {
// This is expected. So nothing required here.
LOG.info("Finish registration failed as expected because it was not registered");
@@ -260,8 +263,7 @@ public void testFinishMultipleApplicationMasters() throws Exception {
try {
// Try to finish an application master that was not registered.
finishApplicationMaster(4, FinalApplicationStatus.SUCCEEDED);
- Assert
- .fail("The request to finish application master should have failed");
+ fail("The request to finish application master should have failed");
} catch (Throwable ex) {
// This is expected. So nothing required here.
LOG.info("Finish registration failed as expected because it was not registered");
@@ -280,9 +282,8 @@ public void testFinishMultipleApplicationMastersInParallel()
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(i);
- Assert.assertNotNull(registerResponse);
- Assert
- .assertEquals(Integer.toString(i), registerResponse.getQueue());
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(i), registerResponse.getQueue());
}
finishApplicationMastersInParallel(testContexts);
@@ -293,19 +294,19 @@ public void testAllocateRequestWithNullValues() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
- Assert.assertEquals(Integer.toString(testAppId),
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(testAppId),
registerResponse.getQueue());
AllocateResponse allocateResponse = allocate(testAppId);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
FinishApplicationMasterResponse finishResponse =
finishApplicationMaster(testAppId,
FinalApplicationStatus.SUCCEEDED);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
}
@Test
@@ -314,8 +315,7 @@ public void testAllocateRequestWithoutRegistering() {
try {
// Try to allocate an application master without registering.
allocate(1);
- Assert
- .fail("The request to allocate application master should have failed");
+ fail("The request to allocate application master should have failed");
} catch (Throwable ex) {
// This is expected. So nothing required here.
LOG.info("AllocateRequest failed as expected because AM was not registered");
@@ -327,7 +327,7 @@ public void testAllocateWithOneResourceRequest() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
getContainersAndAssert(testAppId, 1);
finishApplicationMaster(testAppId, FinalApplicationStatus.SUCCEEDED);
}
@@ -337,7 +337,7 @@ public void testAllocateWithMultipleResourceRequest() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
getContainersAndAssert(testAppId, 10);
finishApplicationMaster(testAppId, FinalApplicationStatus.SUCCEEDED);
}
@@ -347,7 +347,7 @@ public void testAllocateAndReleaseContainers() throws Exception {
int testAppId = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
List containers = getContainersAndAssert(testAppId, 10);
releaseContainersAndAssert(testAppId, containers);
finishApplicationMaster(testAppId, FinalApplicationStatus.SUCCEEDED);
@@ -360,7 +360,7 @@ public void testAllocateAndReleaseContainersForMultipleAM()
for (int testAppId = 0; testAppId < numberOfApps; testAppId++) {
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
List containers = getContainersAndAssert(testAppId, 10);
releaseContainersAndAssert(testAppId, containers);
}
@@ -383,7 +383,7 @@ public void testAllocateAndReleaseContainersForMultipleAMInParallel()
try {
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId);
- Assert.assertNotNull("response is null", registerResponse);
+ assertNotNull(registerResponse, "response is null");
List containers =
getContainersAndAssert(testAppId, 10);
releaseContainersAndAssert(testAppId, containers);
@@ -397,11 +397,11 @@ public void testAllocateAndReleaseContainersForMultipleAMInParallel()
return testAppId;
});
- Assert.assertEquals("Number of responses received does not match with request",
- tempAppIds.size(), responses.size());
+ assertEquals(tempAppIds.size(), responses.size(),
+ "Number of responses received does not match with request");
for (Integer testAppId : responses) {
- Assert.assertNotNull(testAppId);
+ assertNotNull(testAppId);
finishApplicationMaster(testAppId, FinalApplicationStatus.SUCCEEDED);
}
}
@@ -417,10 +417,10 @@ public void testMultipleAttemptsSameNode() throws Exception {
RegisterApplicationMasterResponse response1 =
registerApplicationMaster(appId.getId());
- Assert.assertNotNull(response1);
+ assertNotNull(response1);
AllocateResponse allocateResponse = allocate(appId.getId());
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
// Second Attempt
@@ -430,10 +430,10 @@ public void testMultipleAttemptsSameNode() throws Exception {
RequestInterceptorChainWrapper chain2 =
getAMRMProxyService().getPipelines().get(appId);
- Assert.assertEquals(applicationAttemptId, chain2.getApplicationAttemptId());
+ assertEquals(applicationAttemptId, chain2.getApplicationAttemptId());
allocateResponse = allocate(appId.getId());
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
}
private List getContainersAndAssert(int appId,
@@ -452,11 +452,9 @@ private List getContainersAndAssert(int appId,
allocateRequest.setAskList(askList);
AllocateResponse allocateResponse = allocate(appId, allocateRequest);
- Assert.assertNotNull("allocate() returned null response",
- allocateResponse);
- Assert.assertNull(
- "new AMRMToken from RM should have been nulled by AMRMProxyService",
- allocateResponse.getAMRMToken());
+ assertNotNull(allocateResponse, "allocate() returned null response");
+ assertNull(allocateResponse.getAMRMToken(),
+ "new AMRMToken from RM should have been nulled by AMRMProxyService");
containers.addAll(allocateResponse.getAllocatedContainers());
@@ -466,11 +464,9 @@ private List getContainersAndAssert(int appId,
while (containers.size() < askList.size() && numHeartbeat++ < 10) {
allocateResponse =
allocate(appId, Records.newRecord(AllocateRequest.class));
- Assert.assertNotNull("allocate() returned null response",
- allocateResponse);
- Assert.assertNull(
- "new AMRMToken from RM should have been nulled by AMRMProxyService",
- allocateResponse.getAMRMToken());
+ assertNotNull(allocateResponse, "allocate() returned null response");
+ assertNull(allocateResponse.getAMRMToken(),
+ "new AMRMToken from RM should have been nulled by AMRMProxyService");
containers.addAll(allocateResponse.getAllocatedContainers());
@@ -482,14 +478,14 @@ private List getContainersAndAssert(int appId,
// We broadcast the request, the number of containers we received will be
// higher than we ask
- Assert.assertTrue("The asklist count is not same as response",
- askList.size() <= containers.size());
+ assertTrue(askList.size() <= containers.size(),
+ "The asklist count is not same as response");
return containers;
}
private void releaseContainersAndAssert(int appId,
List containers) throws Exception {
- Assert.assertTrue(containers.size() > 0);
+ assertTrue(containers.size() > 0);
AllocateRequest allocateRequest =
Records.newRecord(AllocateRequest.class);
allocateRequest.setResponseId(1);
@@ -502,10 +498,9 @@ private void releaseContainersAndAssert(int appId,
allocateRequest.setReleaseList(relList);
AllocateResponse allocateResponse = allocate(appId, allocateRequest);
- Assert.assertNotNull(allocateResponse);
- Assert.assertNull(
- "new AMRMToken from RM should have been nulled by AMRMProxyService",
- allocateResponse.getAMRMToken());
+ assertNotNull(allocateResponse);
+ assertNull(allocateResponse.getAMRMToken(),
+ "new AMRMToken from RM should have been nulled by AMRMProxyService");
// We need to make sure all the resource managers received the
// release list. The containers sent by the mock resource managers will be
@@ -523,10 +518,9 @@ private void releaseContainersAndAssert(int appId,
&& numHeartbeat++ < 10) {
allocateResponse =
allocate(appId, Records.newRecord(AllocateRequest.class));
- Assert.assertNotNull(allocateResponse);
- Assert.assertNull(
- "new AMRMToken from RM should have been nulled by AMRMProxyService",
- allocateResponse.getAMRMToken());
+ assertNotNull(allocateResponse);
+ assertNull(allocateResponse.getAMRMToken(),
+ "new AMRMToken from RM should have been nulled by AMRMProxyService");
newlyFinished = getCompletedContainerIds(
allocateResponse.getCompletedContainersStatuses());
@@ -539,7 +533,7 @@ private void releaseContainersAndAssert(int appId,
Thread.sleep(10);
}
- Assert.assertEquals(relList.size(), containersForReleasedContainerIds.size());
+ assertEquals(relList.size(), containersForReleasedContainerIds.size());
}
/**
@@ -560,47 +554,46 @@ public void testRecovery() throws Exception {
int testAppId1 = 1;
RegisterApplicationMasterResponse registerResponse =
registerApplicationMaster(testAppId1);
- Assert.assertNotNull(registerResponse);
- Assert.assertEquals(Integer.toString(testAppId1),
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(testAppId1),
registerResponse.getQueue());
int testAppId2 = 2;
registerResponse = registerApplicationMaster(testAppId2);
- Assert.assertNotNull(registerResponse);
- Assert.assertEquals(Integer.toString(testAppId2),
+ assertNotNull(registerResponse);
+ assertEquals(Integer.toString(testAppId2),
registerResponse.getQueue());
AllocateResponse allocateResponse = allocate(testAppId2);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
// At the time of kill, app1 just registerAM, app2 already did one allocate.
// Both application should be recovered
createAndStartAMRMProxyService(conf);
- Assert.assertEquals(2, getAMRMProxyService().getPipelines().size());
+ assertEquals(2, getAMRMProxyService().getPipelines().size());
allocateResponse = allocate(testAppId1);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
FinishApplicationMasterResponse finishResponse =
finishApplicationMaster(testAppId1, FinalApplicationStatus.SUCCEEDED);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
allocateResponse = allocate(testAppId2);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
finishResponse =
finishApplicationMaster(testAppId2, FinalApplicationStatus.SUCCEEDED);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
int testAppId3 = 3;
try {
// Try to finish an application master that is not registered.
finishApplicationMaster(testAppId3, FinalApplicationStatus.SUCCEEDED);
- Assert
- .fail("The Mock RM should complain about not knowing the third app");
+ fail("The Mock RM should complain about not knowing the third app");
} catch (Throwable ex) {
}
@@ -626,14 +619,14 @@ public void testAppRecoveryFailure() throws YarnException, Exception {
RecoveredAMRMProxyState state =
getNMContext().getNMStateStore().loadAMRMProxyState();
- Assert.assertEquals(1, state.getAppContexts().size());
+ assertEquals(1, state.getAppContexts().size());
// AMRMProxy restarts and recover
createAndStartAMRMProxyService(conf);
state = getNMContext().getNMStateStore().loadAMRMProxyState();
// The app that failed to recover should have been removed from NMSS
- Assert.assertEquals(0, state.getAppContexts().size());
+ assertEquals(0, state.getAppContexts().size());
}
@Test
@@ -645,14 +638,14 @@ public void testCheckIfAppExistsInStateStore()
createAndStartAMRMProxyService(conf);
- Assert.assertFalse(getAMRMProxyService().checkIfAppExistsInStateStore(appId));
+ assertFalse(getAMRMProxyService().checkIfAppExistsInStateStore(appId));
Configuration distConf = createConfiguration();
conf.setBoolean(YarnConfiguration.DIST_SCHEDULING_ENABLED, true);
createAndStartAMRMProxyService(distConf);
- Assert.assertTrue(getAMRMProxyService().checkIfAppExistsInStateStore(appId));
+ assertTrue(getAMRMProxyService().checkIfAppExistsInStateStore(appId));
}
/**
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyTokenSecretManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyTokenSecretManager.java
index db7167d4ebced..a8b5b951f7a4b 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyTokenSecretManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyTokenSecretManager.java
@@ -29,10 +29,11 @@
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Unit test for AMRMProxyTokenSecretManager.
@@ -43,7 +44,7 @@ public class TestAMRMProxyTokenSecretManager {
private AMRMProxyTokenSecretManager secretManager;
private NMMemoryStateStoreService stateStore;
- @Before
+ @BeforeEach
public void setup() {
conf = new YarnConfiguration();
conf.setBoolean(YarnConfiguration.NM_RECOVERY_ENABLED, true);
@@ -57,7 +58,7 @@ public void setup() {
secretManager.start();
}
- @After
+ @AfterEach
public void breakdown() {
if (secretManager != null) {
secretManager.stop();
@@ -85,7 +86,7 @@ public void testNormalCase() throws IOException {
try {
secretManager.retrievePassword(identifier);
- Assert.fail("Expect InvalidToken exception");
+ fail("Expect InvalidToken exception");
} catch (InvalidToken e) {
}
}
@@ -133,7 +134,7 @@ public void testRecovery() throws IOException {
try {
secretManager.retrievePassword(identifier);
- Assert.fail("Expect InvalidToken exception because the "
+ fail("Expect InvalidToken exception because the "
+ "old master key should have expired");
} catch (InvalidToken e) {
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptor.java
index c60fda5f72bfc..0182ac9c38c98 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptor.java
@@ -83,11 +83,19 @@
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.server.uam.UnmanagedAMPoolManager;
import org.apache.hadoop.yarn.util.Records;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+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;
+
/**
* Extends the TestAMRMProxyService and overrides methods in order to use the
* AMRMProxyService's pipeline test cases for testing the FederationInterceptor
@@ -111,6 +119,7 @@ public class TestFederationInterceptor extends BaseAMRMProxyTest {
private volatile int lastResponseId;
+ @BeforeEach
@Override
public void setUp() throws IOException {
super.setUp();
@@ -142,6 +151,7 @@ public void setUp() throws IOException {
lastResponseId = 0;
}
+ @AfterEach
@Override
public void tearDown() {
interceptor.cleanupRegistry();
@@ -211,7 +221,7 @@ private List getContainersAndAssert(int numberOfResourceRequests,
allocateRequest.setResponseId(lastResponseId);
AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull("allocate() returned null response", allocateResponse);
+ assertNotNull(allocateResponse, "allocate() returned null response");
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -227,8 +237,7 @@ private List getContainersAndAssert(int numberOfResourceRequests,
allocateRequest = Records.newRecord(AllocateRequest.class);
allocateRequest.setResponseId(lastResponseId);
allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull("allocate() returned null response",
- allocateResponse);
+ assertNotNull(allocateResponse, "allocate() returned null response");
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -241,13 +250,13 @@ private List getContainersAndAssert(int numberOfResourceRequests,
LOG.info("Total number of allocated containers: {}.", containers.size());
Thread.sleep(10);
}
- Assert.assertEquals(numberOfAllocationExcepted, containers.size());
+ assertEquals(numberOfAllocationExcepted, containers.size());
return containers;
}
private void releaseContainersAndAssert(List containers)
throws Exception {
- Assert.assertTrue(containers.size() > 0);
+ assertTrue(containers.size() > 0);
AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class);
List relList = new ArrayList<>(containers.size());
for (Container container : containers) {
@@ -258,7 +267,7 @@ private void releaseContainersAndAssert(List containers)
allocateRequest.setResponseId(lastResponseId);
AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -281,7 +290,7 @@ private void releaseContainersAndAssert(List containers)
allocateRequest = Records.newRecord(AllocateRequest.class);
allocateRequest.setResponseId(lastResponseId);
allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -297,14 +306,14 @@ private void releaseContainersAndAssert(List containers)
Thread.sleep(10);
}
- Assert.assertEquals(relList.size(),
+ assertEquals(relList.size(),
containersForReleasedContainerIds.size());
}
private void checkAMRMToken(Token amrmToken) {
if (amrmToken != null) {
// The token should be the one issued by home MockRM
- Assert.assertEquals(Integer.toString(0), amrmToken.getKind());
+ assertEquals(Integer.toString(0), amrmToken.getKind());
}
}
@@ -322,10 +331,10 @@ public void testMultipleSubClusters() throws Exception {
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate the first batch of containers, with sc1 and sc2 active
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -334,7 +343,7 @@ public void testMultipleSubClusters() throws Exception {
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers * 2);
- Assert.assertEquals(2, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(2, interceptor.getUnmanagedAMPoolSize());
// Allocate the second batch of containers, with sc1 and sc3 active
deRegisterSubCluster(SubClusterId.newInstance("SC-2"));
@@ -343,7 +352,7 @@ public void testMultipleSubClusters() throws Exception {
numberOfContainers = 1;
containers.addAll(
getContainersAndAssert(numberOfContainers, numberOfContainers * 2));
- Assert.assertEquals(3, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(3, interceptor.getUnmanagedAMPoolSize());
// Allocate the third batch of containers with only in home sub-cluster
// active
@@ -354,7 +363,7 @@ public void testMultipleSubClusters() throws Exception {
numberOfContainers = 2;
containers.addAll(
getContainersAndAssert(numberOfContainers, numberOfContainers));
- Assert.assertEquals(3, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(3, interceptor.getUnmanagedAMPoolSize());
// Release all containers
releaseContainersAndAssert(containers);
@@ -368,8 +377,8 @@ public void testMultipleSubClusters() throws Exception {
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
return null;
});
@@ -393,10 +402,10 @@ public void testReregister() throws Exception {
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate the first batch of containers
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -407,7 +416,7 @@ public void testReregister() throws Exception {
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers * 2);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
interceptor.setShouldReRegisterNext();
@@ -425,8 +434,8 @@ public void testReregister() throws Exception {
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
return null;
});
}
@@ -438,7 +447,8 @@ public void testReregister() throws Exception {
* RM failover and AM timeout, it will call us resulting in a second register
* thread.
*/
- @Test(timeout = 5000)
+ @Test
+ @Timeout(value = 5)
public void testConcurrentRegister()
throws InterruptedException, ExecutionException {
ExecutorService threadpool = Executors.newCachedThreadPool();
@@ -475,10 +485,10 @@ public void testConcurrentRegister()
// Both thread should return without exception
RegisterApplicationMasterResponse response = compSvc.take().get();
- Assert.assertNotNull(response);
+ assertNotNull(response);
response = compSvc.take().get();
- Assert.assertNotNull(response);
+ assertNotNull(response);
threadpool.shutdown();
}
@@ -543,10 +553,10 @@ protected void testRecover(final RegistryOperations registryObj)
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate one batch of containers
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -555,7 +565,7 @@ protected void testRecover(final RegistryOperations registryObj)
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers * 2);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
// Make sure all async hb threads are done
interceptor.drainAllAsyncQueue(true);
@@ -566,11 +576,11 @@ protected void testRecover(final RegistryOperations registryObj)
String scEntry =
FederationInterceptor.NMSS_SECONDARY_SC_PREFIX + "SC-1";
if (registryObj == null) {
- Assert.assertTrue(recoveredDataMap.containsKey(scEntry));
+ assertTrue(recoveredDataMap.containsKey(scEntry));
} else {
// When AMRMPRoxy HA is enabled, NMSS should not have the UAM token,
// it should be in Registry
- Assert.assertFalse(recoveredDataMap.containsKey(scEntry));
+ assertFalse(recoveredDataMap.containsKey(scEntry));
}
// Preserve the mock RM instances
@@ -584,9 +594,9 @@ protected void testRecover(final RegistryOperations registryObj)
getConf(), attemptId, "test-user", null, null, null, registryObj));
interceptor.recover(recoveredDataMap);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
// SC1 should be initialized to be timed out
- Assert.assertEquals(1, interceptor.getTimedOutSCs(true).size());
+ assertEquals(1, interceptor.getTimedOutSCs(true).size());
// The first allocate call expects a fail-over exception and re-register
try {
@@ -596,7 +606,7 @@ protected void testRecover(final RegistryOperations registryObj)
AllocateResponse allocateResponse =
interceptor.allocate(allocateRequest);
lastResponseId = allocateResponse.getResponseId();
- Assert.fail("Expecting an ApplicationMasterNotRegisteredException "
+ fail("Expecting an ApplicationMasterNotRegisteredException "
+ " after FederationInterceptor restarts and recovers");
} catch (ApplicationMasterNotRegisteredException e) {
}
@@ -615,18 +625,18 @@ protected void testRecover(final RegistryOperations registryObj)
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
// After the application succeeds, the registry/NMSS entry should be
// cleaned up
if (registryObj != null) {
- Assert.assertEquals(0,
+ assertEquals(0,
interceptor.getRegistryClient().getAllApplications().size());
} else {
recoveredDataMap =
recoverDataMapForAppAttempt(nmStateStore, attemptId);
- Assert.assertFalse(recoveredDataMap.containsKey(scEntry));
+ assertFalse(recoveredDataMap.containsKey(scEntry));
}
return null;
});
@@ -641,21 +651,21 @@ public void testRequestInterceptorChainCreation() throws Exception {
switch (index) {
case 0:
case 1:
- Assert.assertEquals(PassThroughRequestInterceptor.class.getName(),
+ assertEquals(PassThroughRequestInterceptor.class.getName(),
root.getClass().getName());
break;
case 2:
- Assert.assertEquals(TestableFederationInterceptor.class.getName(),
+ assertEquals(TestableFederationInterceptor.class.getName(),
root.getClass().getName());
break;
default:
- Assert.fail();
+ fail();
}
root = root.getNextInterceptor();
index++;
}
- Assert.assertEquals("The number of interceptors in chain does not match",
- Integer.toString(3), Integer.toString(index));
+ assertEquals(Integer.toString(3), Integer.toString(index),
+ "The number of interceptors in chain does not match");
}
/**
@@ -681,7 +691,7 @@ public void testTwoIdenticalRegisterRequest() throws Exception {
for (int i = 0; i < 2; i++) {
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
}
}
@@ -697,7 +707,7 @@ public void testTwoDifferentRegisterRequest() throws Exception {
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
// Register the application second time with a different request obj
@@ -708,7 +718,7 @@ public void testTwoDifferentRegisterRequest() throws Exception {
try {
registerResponse = interceptor.registerApplicationMaster(registerReq);
lastResponseId = 0;
- Assert.fail("Should throw if a different request obj is used");
+ fail("Should throw if a different request obj is used");
} catch (YarnException e) {
}
}
@@ -748,15 +758,15 @@ public void testAllocateResponse() throws Exception {
response = interceptor.allocate(allocateRequest);
- Assert.assertEquals(1, response.getAllocatedContainers().size());
- Assert.assertNotNull(response.getAvailableResources());
- Assert.assertEquals(1, response.getCompletedContainersStatuses().size());
- Assert.assertEquals(1, response.getUpdatedNodes().size());
- Assert.assertNotNull(response.getPreemptionMessage());
- Assert.assertEquals(1, response.getNMTokens().size());
- Assert.assertEquals(1, response.getUpdatedContainers().size());
- Assert.assertEquals(1, response.getUpdateErrors().size());
- Assert.assertNotNull(response.getApplicationPriority());
+ assertEquals(1, response.getAllocatedContainers().size());
+ assertNotNull(response.getAvailableResources());
+ assertEquals(1, response.getCompletedContainersStatuses().size());
+ assertEquals(1, response.getUpdatedNodes().size());
+ assertNotNull(response.getPreemptionMessage());
+ assertEquals(1, response.getNMTokens().size());
+ assertEquals(1, response.getUpdatedContainers().size());
+ assertEquals(1, response.getUpdateErrors().size());
+ assertNotNull(response.getApplicationPriority());
}
@Test
@@ -772,7 +782,7 @@ public void testSubClusterTimeOut() throws Exception {
registerReq.setTrackingUrl("");
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -780,8 +790,8 @@ public void testSubClusterTimeOut() throws Exception {
getContainersAndAssert(1, 1);
AllocateResponse allocateResponse = interceptor.generateBaseAllocationResponse();
- Assert.assertEquals(2, allocateResponse.getNumClusterNodes());
- Assert.assertEquals(0, interceptor.getTimedOutSCs(true).size());
+ assertEquals(2, allocateResponse.getNumClusterNodes());
+ assertEquals(0, interceptor.getTimedOutSCs(true).size());
// Let all SC timeout (home and SC-1), without an allocate from AM
Thread.sleep(800);
@@ -789,8 +799,8 @@ public void testSubClusterTimeOut() throws Exception {
// Should not be considered timeout, because there's no recent AM
// heartbeat
allocateResponse = interceptor.generateBaseAllocationResponse();
- Assert.assertEquals(2, allocateResponse.getNumClusterNodes());
- Assert.assertEquals(0, interceptor.getTimedOutSCs(true).size());
+ assertEquals(2, allocateResponse.getNumClusterNodes());
+ assertEquals(0, interceptor.getTimedOutSCs(true).size());
// Generate a duplicate heartbeat from AM, so that it won't really
// trigger a heartbeat to all SC
@@ -802,8 +812,8 @@ public void testSubClusterTimeOut() throws Exception {
// Should be considered timeout
allocateResponse = interceptor.generateBaseAllocationResponse();
- Assert.assertEquals(0, allocateResponse.getNumClusterNodes());
- Assert.assertEquals(2, interceptor.getTimedOutSCs(true).size());
+ assertEquals(0, allocateResponse.getNumClusterNodes());
+ assertEquals(2, interceptor.getTimedOutSCs(true).size());
return null;
});
}
@@ -822,10 +832,10 @@ public void testSecondAttempt() throws Exception {
// Register the application
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate one batch of containers
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -837,7 +847,7 @@ public void testSecondAttempt() throws Exception {
for (Container c : containers) {
LOG.info("Allocated container {}.", c.getId());
}
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
// Make sure all async hb threads are done
interceptor.drainAllAsyncQueue(true);
@@ -865,10 +875,10 @@ public void testSecondAttempt() throws Exception {
int numberOfContainers = 3;
// Should re-attach secondaries and get the three running containers
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
// SC1 should be initialized to be timed out
- Assert.assertEquals(1, interceptor.getTimedOutSCs(true).size());
- Assert.assertEquals(numberOfContainers,
+ assertEquals(1, interceptor.getTimedOutSCs(true).size());
+ assertEquals(numberOfContainers,
registerResponse.getContainersFromPreviousAttempts().size());
// Release all containers
@@ -884,12 +894,12 @@ public void testSecondAttempt() throws Exception {
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
// After the application succeeds, the registry entry should be deleted
if (interceptor.getRegistryClient() != null) {
- Assert.assertEquals(0,
+ assertEquals(0,
interceptor.getRegistryClient().getAllApplications().size());
}
return null;
@@ -933,11 +943,11 @@ public void testMergeAllocateResponse() {
interceptor.mergeAllocateResponse(homeResponse,
response, SubClusterId.newInstance("SC-1"));
- Assert.assertEquals(2,
+ assertEquals(2,
homeResponse.getPreemptionMessage().getContract().getContainers().size());
- Assert.assertEquals(2, homeResponse.getAllocatedContainers().size());
- Assert.assertEquals(2, homeResponse.getUpdatedNodes().size());
- Assert.assertEquals(2, homeResponse.getCompletedContainersStatuses().size());
+ assertEquals(2, homeResponse.getAllocatedContainers().size());
+ assertEquals(2, homeResponse.getUpdatedNodes().size());
+ assertEquals(2, homeResponse.getCompletedContainersStatuses().size());
}
private PreemptionMessage createDummyPreemptionMessage(
@@ -972,10 +982,10 @@ public void testSameContainerFromDiffRM() throws IOException, InterruptedExcepti
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate the first batch of containers, with sc1 active
SubClusterId subClusterId1 = SubClusterId.newInstance("SC-1");
@@ -984,8 +994,8 @@ public void testSameContainerFromDiffRM() throws IOException, InterruptedExcepti
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers);
- Assert.assertNotNull(containers);
- Assert.assertEquals(3, containers.size());
+ assertNotNull(containers);
+ assertEquals(3, containers.size());
// with sc2 active
SubClusterId subClusterId2 = SubClusterId.newInstance("SC-2");
@@ -998,8 +1008,8 @@ public void testSameContainerFromDiffRM() throws IOException, InterruptedExcepti
interceptor.cacheAllocatedContainersForSubClusterId(containers, subClusterId2);
Map cIdToSCMap = interceptor.getContainerIdToSubClusterIdMap();
for (SubClusterId subClusterId : cIdToSCMap.values()) {
- Assert.assertNotNull(subClusterId);
- Assert.assertEquals(subClusterId1, subClusterId);
+ assertNotNull(subClusterId);
+ assertEquals(subClusterId1, subClusterId);
}
// 2.Deregister SubCluster1, Register the same Containers to SubCluster2
@@ -1008,8 +1018,8 @@ public void testSameContainerFromDiffRM() throws IOException, InterruptedExcepti
interceptor.cacheAllocatedContainersForSubClusterId(containers, subClusterId2);
Map cIdToSCMap2 = interceptor.getContainerIdToSubClusterIdMap();
for (SubClusterId subClusterId : cIdToSCMap2.values()) {
- Assert.assertNotNull(subClusterId);
- Assert.assertEquals(subClusterId2, subClusterId);
+ assertNotNull(subClusterId);
+ assertEquals(subClusterId2, subClusterId);
}
// 3.Deregister subClusterId2, Register the same Containers to SubCluster1
@@ -1017,7 +1027,7 @@ public void testSameContainerFromDiffRM() throws IOException, InterruptedExcepti
// an exception will be thrown when registering the first Container.
deRegisterSubCluster(subClusterId2);
Container container1 = containers.get(0);
- Assert.assertNotNull(container1);
+ assertNotNull(container1);
String errMsg =
" Can't use any subCluster because an exception occurred" +
" ContainerId: " + container1.getId() +
@@ -1043,8 +1053,8 @@ public void testSameContainerFromDiffRM() throws IOException, InterruptedExcepti
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
return null;
});
@@ -1073,10 +1083,10 @@ public void testBatchFinishApplicationMaster() throws IOException, InterruptedEx
// Register ApplicationMaster
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq1);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate the first batch of containers, with sc1 and sc2 active
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -1085,8 +1095,8 @@ public void testBatchFinishApplicationMaster() throws IOException, InterruptedEx
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers * 2);
- Assert.assertEquals(2, interceptor.getUnmanagedAMPoolSize());
- Assert.assertEquals(numberOfContainers * 2, containers.size());
+ assertEquals(2, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(numberOfContainers * 2, containers.size());
// Finish the application
FinishApplicationMasterRequest finishReq =
@@ -1096,8 +1106,8 @@ public void testBatchFinishApplicationMaster() throws IOException, InterruptedEx
finishReq.setFinalApplicationStatus(FinalApplicationStatus.SUCCEEDED);
FinishApplicationMasterResponse finishResp = interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResp);
- Assert.assertTrue(finishResp.getIsUnregistered());
+ assertNotNull(finishResp);
+ assertTrue(finishResp.getIsUnregistered());
return null;
});
@@ -1127,10 +1137,10 @@ public void testRemoveAppFromRegistryApplicationSuccess()
// Register ApplicationMaster
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq1);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate the first batch of containers, with sc1 active
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -1138,8 +1148,8 @@ public void testRemoveAppFromRegistryApplicationSuccess()
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
- Assert.assertEquals(numberOfContainers, containers.size());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(numberOfContainers, containers.size());
// Finish the application
FinishApplicationMasterRequest finishReq =
@@ -1149,13 +1159,13 @@ public void testRemoveAppFromRegistryApplicationSuccess()
finishReq.setFinalApplicationStatus(FinalApplicationStatus.SUCCEEDED);
FinishApplicationMasterResponse finishResp = interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResp);
- Assert.assertTrue(finishResp.getIsUnregistered());
+ assertNotNull(finishResp);
+ assertTrue(finishResp.getIsUnregistered());
FederationRegistryClient client = interceptor.getRegistryClient();
List applications = client.getAllApplications();
- Assert.assertNotNull(finishResp);
- Assert.assertEquals(0, applications.size());
+ assertNotNull(finishResp);
+ assertEquals(0, applications.size());
return null;
});
}
@@ -1185,10 +1195,10 @@ public void testRemoveAppFromRegistryApplicationFailed()
// Register ApplicationMaster
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq1);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate the first batch of containers, with sc1 active
registerSubCluster(SubClusterId.newInstance("SC-1"));
@@ -1196,8 +1206,8 @@ public void testRemoveAppFromRegistryApplicationFailed()
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
- Assert.assertEquals(numberOfContainers, containers.size());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(numberOfContainers, containers.size());
// Finish the application
FinishApplicationMasterRequest finishReq =
@@ -1210,15 +1220,15 @@ public void testRemoveAppFromRegistryApplicationFailed()
// At this time, the Application should not be cleaned up because the state is not SUCCESS.
FederationRegistryClient client = interceptor.getRegistryClient();
List applications = client.getAllApplications();
- Assert.assertNotNull(applications);
- Assert.assertEquals(1, applications.size());
+ assertNotNull(applications);
+ assertEquals(1, applications.size());
// interceptor cleanupRegistry
ApplicationId applicationId = interceptor.getAttemptId().getApplicationId();
client.removeAppFromRegistry(applicationId);
applications = client.getAllApplications();
- Assert.assertNotNull(applications);
- Assert.assertEquals(0, applications.size());
+ assertNotNull(applications);
+ assertEquals(0, applications.size());
return null;
});
@@ -1268,9 +1278,9 @@ public void testRecoverWithBadSubCluster(final RegistryOperations registryObj)
// SC-1 was offline, SC-2 was recovered at this time, UnmanagedAMPool.size=1 and only SC-2
UnmanagedAMPoolManager unmanagedAMPoolManager = interceptor.getUnmanagedAMPool();
Set allUAMIds = unmanagedAMPoolManager.getAllUAMIds();
- Assert.assertNotNull(allUAMIds);
- Assert.assertEquals(1, allUAMIds.size());
- Assert.assertTrue(allUAMIds.contains(sc2.getId()));
+ assertNotNull(allUAMIds);
+ assertEquals(1, allUAMIds.size());
+ assertTrue(allUAMIds.contains(sc2.getId()));
// Step6. The first allocate call expects a fail-over exception and re-register.
AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class);
@@ -1312,10 +1322,10 @@ private List registerApplicationAndAssignContainers(
// Register HomeSC
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
// We only registered HomeSC, so UnmanagedAMPoolSize should be empty
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// We assign 3 Containers to each cluster
int numberOfContainers = 3;
@@ -1323,13 +1333,13 @@ private List registerApplicationAndAssignContainers(
getContainersAndAssert(numberOfContainers, numberOfContainers * 3);
// At this point, UnmanagedAMPoolSize should be equal to 2 and should contain SC-1, SC-2
- Assert.assertEquals(2, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(2, interceptor.getUnmanagedAMPoolSize());
UnmanagedAMPoolManager unmanagedAMPoolManager = interceptor.getUnmanagedAMPool();
Set allUAMIds = unmanagedAMPoolManager.getAllUAMIds();
- Assert.assertNotNull(allUAMIds);
- Assert.assertEquals(2, allUAMIds.size());
- Assert.assertTrue(allUAMIds.contains("SC-1"));
- Assert.assertTrue(allUAMIds.contains("SC-2"));
+ assertNotNull(allUAMIds);
+ assertEquals(2, allUAMIds.size());
+ assertTrue(allUAMIds.contains("SC-1"));
+ assertTrue(allUAMIds.contains("SC-2"));
// Make sure all async hb threads are done
interceptor.drainAllAsyncQueue(true);
@@ -1374,9 +1384,9 @@ private void releaseContainers(List containers, SubClusterId subClust
MockResourceManagerFacade sc1Facade = secondaries.get("SC-1");
HashMap> appContainerMap =
sc1Facade.getApplicationContainerIdMap();
- Assert.assertNotNull(appContainerMap);
+ assertNotNull(appContainerMap);
ApplicationId applicationId = attemptId.getApplicationId();
- Assert.assertNotNull(applicationId);
+ assertNotNull(applicationId);
List sc1ContainerList = appContainerMap.get(applicationId);
// Release all containers,
@@ -1397,8 +1407,8 @@ private void finishApplication() throws IOException, YarnException {
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
}
@Test
@@ -1417,17 +1427,17 @@ public void testLaunchUAMAndRegisterApplicationMasterRetry() throws Exception {
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate the first batch of containers, with sc1 active
registerSubCluster(SubClusterId.newInstance("SC-1"));
int numberOfContainers = 3;
List containers = getContainersAndAssert(numberOfContainers, numberOfContainers);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
// Release all containers
releaseContainersAndAssert(containers);
@@ -1441,12 +1451,12 @@ public void testLaunchUAMAndRegisterApplicationMasterRetry() throws Exception {
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
return null;
});
- Assert.assertEquals(0, interceptor.getRetryCount());
+ assertEquals(0, interceptor.getRetryCount());
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptorSecure.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptorSecure.java
index 5b3f94dcb5989..57ca49a0e121a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptorSecure.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestFederationInterceptorSecure.java
@@ -73,15 +73,17 @@
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.util.Records;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.*;
+import org.junit.jupiter.api.io.TempDir;
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.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
public class TestFederationInterceptorSecure extends BaseAMRMProxyTest {
private static final Logger LOG = LoggerFactory.getLogger(TestFederationInterceptor.class);
@@ -113,31 +115,29 @@ public class TestFederationInterceptorSecure extends BaseAMRMProxyTest {
private static String serverPrincipal;
private static File serverKeytab;
- @ClassRule
- public final static TemporaryFolder FOLDER = new TemporaryFolder();
-
- @BeforeClass
- public static void setUpCluster() throws Exception {
+ @BeforeAll
+ public static void setUpCluster(@TempDir java.nio.file.Path dir) throws Exception {
miniKDC = new MiniKdc(MiniKdc.createConf(), TEST_ROOT_DIR);
miniKDC.start();
- workDir = FOLDER.getRoot();
+ workDir = dir.toFile();
serverKeytab = new File(workDir, "yarn.keytab");
serverPrincipal =
serverUserName + "/" + (Path.WINDOWS ? "127.0.0.1" : "localhost") + "@EXAMPLE.COM";
miniKDC.createPrincipal(serverKeytab, serverPrincipal);
}
- @AfterClass
+ @AfterAll
public static void tearDownCluster() {
if (miniKDC != null) {
miniKDC.stop();
}
- if (FOLDER != null) {
- FOLDER.delete();
+ if (workDir != null) {
+ workDir.delete();
}
}
+ @BeforeEach
@Override
public void setUp() throws IOException {
super.setUp();
@@ -183,6 +183,7 @@ private void stopRpcServer() {
}
}
+ @AfterEach
@Override
public void tearDown() {
interceptor.cleanupRegistry();
@@ -257,7 +258,7 @@ private List getContainersAndAssert(int numberOfResourceRequests,
allocateRequest.setResponseId(lastResponseId);
AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull("allocate() returned null response", allocateResponse);
+ assertNotNull(allocateResponse, "allocate() returned null response");
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -272,7 +273,7 @@ private List getContainersAndAssert(int numberOfResourceRequests,
allocateRequest = Records.newRecord(AllocateRequest.class);
allocateRequest.setResponseId(lastResponseId);
allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull("allocate() returned null response", allocateResponse);
+ assertNotNull(allocateResponse, "allocate() returned null response");
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -285,13 +286,13 @@ private List getContainersAndAssert(int numberOfResourceRequests,
LOG.info("Total number of allocated containers: {}.", containers.size());
Thread.sleep(10);
}
- Assert.assertEquals(numberOfAllocationExcepted, containers.size());
+ assertEquals(numberOfAllocationExcepted, containers.size());
return containers;
}
private void releaseContainersAndAssert(List containers)
throws Exception {
- Assert.assertTrue(containers.size() > 0);
+ assertTrue(containers.size() > 0);
AllocateRequest allocateRequest = Records.newRecord(AllocateRequest.class);
List relList = new ArrayList<>(containers.size());
for (Container container : containers) {
@@ -302,7 +303,7 @@ private void releaseContainersAndAssert(List containers)
allocateRequest.setResponseId(lastResponseId);
AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -322,7 +323,7 @@ private void releaseContainersAndAssert(List containers)
allocateRequest = Records.newRecord(AllocateRequest.class);
allocateRequest.setResponseId(lastResponseId);
allocateResponse = interceptor.allocate(allocateRequest);
- Assert.assertNotNull(allocateResponse);
+ assertNotNull(allocateResponse);
checkAMRMToken(allocateResponse.getAMRMToken());
lastResponseId = allocateResponse.getResponseId();
@@ -337,13 +338,13 @@ private void releaseContainersAndAssert(List containers)
Thread.sleep(10);
}
- Assert.assertEquals(relList.size(), containersForReleasedContainerIds.size());
+ assertEquals(relList.size(), containersForReleasedContainerIds.size());
}
private void checkAMRMToken(Token amrmToken) {
if (amrmToken != null) {
// The token should be the one issued by home MockRM
- Assert.assertEquals(Integer.toString(0), amrmToken.getKind());
+ assertEquals(Integer.toString(0), amrmToken.getKind());
}
}
@@ -376,10 +377,10 @@ protected void testRecoverWithRPCClientRM(
RegisterApplicationMasterResponse registerResponse =
interceptor.registerApplicationMaster(registerReq);
- Assert.assertNotNull(registerResponse);
+ assertNotNull(registerResponse);
lastResponseId = 0;
- Assert.assertEquals(0, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(0, interceptor.getUnmanagedAMPoolSize());
// Allocate one batch of containers
registerSubCluster(SubClusterId.newInstance(SC_ID1));
@@ -388,7 +389,7 @@ protected void testRecoverWithRPCClientRM(
int numberOfContainers = 3;
List containers =
getContainersAndAssert(numberOfContainers, numberOfContainers * 2);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
// Make sure all async hb threads are done
interceptor.drainAllAsyncQueue(true);
@@ -397,11 +398,11 @@ protected void testRecoverWithRPCClientRM(
Map recoveredDataMap = recoverDataMapForAppAttempt(nmStateStore, attemptId);
String scEntry = FederationInterceptor.NMSS_SECONDARY_SC_PREFIX + "SC-1";
if (registryObj == null) {
- Assert.assertTrue(recoveredDataMap.containsKey(scEntry));
+ assertTrue(recoveredDataMap.containsKey(scEntry));
} else {
// When AMRMPRoxy HA is enabled, NMSS should not have the UAM token,
// it should be in Registry
- Assert.assertFalse(recoveredDataMap.containsKey(scEntry));
+ assertFalse(recoveredDataMap.containsKey(scEntry));
}
// Preserve the mock RM instances
@@ -417,9 +418,9 @@ protected void testRecoverWithRPCClientRM(
interceptor.recover(recoveredDataMap);
interceptor.setClientRPC(false);
- Assert.assertEquals(1, interceptor.getUnmanagedAMPoolSize());
+ assertEquals(1, interceptor.getUnmanagedAMPoolSize());
// SC-1 should be initialized to be timed out
- Assert.assertEquals(1, interceptor.getTimedOutSCs(true).size());
+ assertEquals(1, interceptor.getTimedOutSCs(true).size());
// The first allocate call expects a fail-over exception and re-register
try {
@@ -427,7 +428,7 @@ protected void testRecoverWithRPCClientRM(
allocateRequest.setResponseId(lastResponseId);
AllocateResponse allocateResponse = interceptor.allocate(allocateRequest);
lastResponseId = allocateResponse.getResponseId();
- Assert.fail("Expecting an ApplicationMasterNotRegisteredException "
+ fail("Expecting an ApplicationMasterNotRegisteredException "
+ " after FederationInterceptor restarts and recovers");
} catch (ApplicationMasterNotRegisteredException e) {
}
@@ -446,16 +447,16 @@ protected void testRecoverWithRPCClientRM(
FinishApplicationMasterResponse finishResponse =
interceptor.finishApplicationMaster(finishReq);
- Assert.assertNotNull(finishResponse);
- Assert.assertTrue(finishResponse.getIsUnregistered());
+ assertNotNull(finishResponse);
+ assertTrue(finishResponse.getIsUnregistered());
// After the application succeeds, the registry/NMSS entry should be
// cleaned up
if (registryObj != null) {
- Assert.assertEquals(0, interceptor.getRegistryClient().getAllApplications().size());
+ assertEquals(0, interceptor.getRegistryClient().getAllApplications().size());
} else {
recoveredDataMap = recoverDataMapForAppAttempt(nmStateStore, attemptId);
- Assert.assertFalse(recoveredDataMap.containsKey(scEntry));
+ assertFalse(recoveredDataMap.containsKey(scEntry));
}
return null;
});
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/impl/pb/TestNMProtoUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/impl/pb/TestNMProtoUtils.java
index 11a69e9ce1628..40a43f1b7937b 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/impl/pb/TestNMProtoUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/impl/pb/TestNMProtoUtils.java
@@ -25,12 +25,12 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.deletion.task.DeletionTaskType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.deletion.task.DockerContainerDeletionTask;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.deletion.task.FileDeletionTask;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBLocalizerRPC.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBLocalizerRPC.java
index 221b9df74dfc4..f4f77397dce78 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBLocalizerRPC.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBLocalizerRPC.java
@@ -18,8 +18,8 @@
package org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.impl.pb;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.InetSocketAddress;
@@ -32,7 +32,7 @@
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerAction;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerHeartbeatResponse;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class TestPBLocalizerRPC {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBRecordImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBRecordImpl.java
index 0fe8f0179bed9..1d806ff9cf119 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBRecordImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBRecordImpl.java
@@ -17,16 +17,15 @@
*/
package org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.impl.pb;
-import static org.junit.Assert.assertEquals;
-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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import org.apache.hadoop.yarn.api.records.URL;
-import org.junit.Assert;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
@@ -49,7 +48,8 @@
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.LocalizerStatus;
import org.apache.hadoop.yarn.server.nodemanager.api.protocolrecords.ResourceStatusType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
public class TestPBRecordImpl {
@@ -118,7 +118,8 @@ static LocalizerHeartbeatResponse createLocalizerHeartbeatResponse()
return ret;
}
- @Test(timeout=10000)
+ @Test
+ @Timeout(value = 10)
public void testLocalResourceStatusSerDe() throws Exception {
LocalResourceStatus rsrcS = createLocalResourceStatus();
assertTrue(rsrcS instanceof LocalResourceStatusPBImpl);
@@ -138,7 +139,8 @@ public void testLocalResourceStatusSerDe() throws Exception {
assertEquals(createResource(), rsrcD.getResource());
}
- @Test(timeout=10000)
+ @Test
+ @Timeout(value = 10)
public void testLocalizerStatusSerDe() throws Exception {
LocalizerStatus rsrcS = createLocalizerStatus();
assertTrue(rsrcS instanceof LocalizerStatusPBImpl);
@@ -160,7 +162,8 @@ public void testLocalizerStatusSerDe() throws Exception {
assertEquals(createLocalResourceStatus(), rsrcD.getResourceStatus(0));
}
- @Test(timeout=10000)
+ @Test
+ @Timeout(value = 10)
public void testLocalizerHeartbeatResponseSerDe() throws Exception {
LocalizerHeartbeatResponse rsrcS = createLocalizerHeartbeatResponse();
assertTrue(rsrcS instanceof LocalizerHeartbeatResponsePBImpl);
@@ -182,14 +185,15 @@ public void testLocalizerHeartbeatResponseSerDe() throws Exception {
}
- @Test(timeout=10000)
+ @Test
+ @Timeout(value = 10)
public void testSerializedExceptionDeSer() throws Exception{
// without cause
YarnException yarnEx = new YarnException("Yarn_Exception");
SerializedException serEx = SerializedException.newInstance(yarnEx);
Throwable throwable = serEx.deSerialize();
- Assert.assertEquals(yarnEx.getClass(), throwable.getClass());
- Assert.assertEquals(yarnEx.getMessage(), throwable.getMessage());
+ assertEquals(yarnEx.getClass(), throwable.getClass());
+ assertEquals(yarnEx.getMessage(), throwable.getMessage());
// with cause
IOException ioe = new IOException("Test_IOException");
@@ -201,13 +205,13 @@ public void testSerializedExceptionDeSer() throws Exception{
SerializedException serEx2 = SerializedException.newInstance(yarnEx2);
Throwable throwable2 = serEx2.deSerialize();
throwable2.printStackTrace();
- Assert.assertEquals(yarnEx2.getClass(), throwable2.getClass());
- Assert.assertEquals(yarnEx2.getMessage(), throwable2.getMessage());
+ assertEquals(yarnEx2.getClass(), throwable2.getClass());
+ assertEquals(yarnEx2.getMessage(), throwable2.getMessage());
- Assert.assertEquals(runtimeException.getClass(), throwable2.getCause().getClass());
- Assert.assertEquals(runtimeException.getMessage(), throwable2.getCause().getMessage());
+ assertEquals(runtimeException.getClass(), throwable2.getCause().getClass());
+ assertEquals(runtimeException.getMessage(), throwable2.getCause().getMessage());
- Assert.assertEquals(ioe.getClass(), throwable2.getCause().getCause().getClass());
- Assert.assertEquals(ioe.getMessage(), throwable2.getCause().getCause().getMessage());
+ assertEquals(ioe.getClass(), throwable2.getCause().getCause().getClass());
+ assertEquals(ioe.getMessage(), throwable2.getCause().getCause().getMessage());
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
index 37045dc74b8df..aa6db999a1382 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
@@ -94,9 +94,10 @@
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.util.resource.Resources;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
public abstract class BaseContainerManagerTest {
@@ -179,7 +180,7 @@ protected ContainerExecutor createContainerExecutor() {
return spy(exec);
}
- @Before
+ @BeforeEach
public void setup() throws IOException {
localFS.delete(new Path(localDir.getAbsolutePath()), true);
localFS.delete(new Path(tmpDir.getAbsolutePath()), true);
@@ -307,7 +308,7 @@ public void delete(DeletionTask deletionTask) {
};
}
- @After
+ @AfterEach
public void tearDown() throws IOException, InterruptedException {
if (containerManager != null) {
containerManager.stop();
@@ -358,8 +359,8 @@ public static void waitForContainerState(
} while (!fStates.contains(containerStatus.getState())
&& timeoutSecs < timeOutMax);
LOG.info("Container state is " + containerStatus.getState());
- Assert.assertTrue("ContainerState is not correct (timedout)",
- fStates.contains(containerStatus.getState()));
+ assertTrue(fStates.contains(containerStatus.getState()),
+ "ContainerState is not correct (timedout)");
}
public static void waitForApplicationState(
@@ -378,8 +379,8 @@ public static void waitForApplicationState(
Thread.sleep(1000);
}
- Assert.assertTrue("App is not in " + finalState + " yet!! Timedout!!",
- app.getApplicationState().equals(finalState));
+ assertTrue(app.getApplicationState().equals(finalState),
+ "App is not in " + finalState + " yet!! Timedout!!");
}
public static void waitForNMContainerState(ContainerManagerImpl
@@ -423,8 +424,8 @@ public static void waitForNMContainerState(ContainerManagerImpl
} while (!finalStates.contains(currentState)
&& timeoutSecs < timeOutMax);
LOG.info("Container state is " + currentState);
- Assert.assertTrue("ContainerState is not correct (timedout)",
- finalStates.contains(currentState));
+ assertTrue(finalStates.contains(currentState),
+ "ContainerState is not correct (timedout)");
}
public static Token createContainerToken(ContainerId cId, long rmIdentifier,
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
index fd82126b7e830..79a3ec482b55d 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
@@ -21,11 +21,13 @@
import static org.apache.hadoop.service.Service.STATE.INITED;
import static org.apache.hadoop.service.Service.STATE.STARTED;
import static org.apache.hadoop.service.Service.STATE.STOPPED;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.anyString;
@@ -39,11 +41,8 @@
import org.apache.hadoop.util.Sets;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.records.AuxServiceRecord;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.records.AuxServiceRecords;
-import org.junit.After;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -98,14 +97,14 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.deletion.task.FileDeletionTask;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.records.AuxServiceFile;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
/**
* Test for auxiliary services. Parameter 0 tests the Configuration-based aux
* services and parameter 1 tests manifest-based aux services.
*/
-@RunWith(value = Parameterized.class)
public class TestAuxServices {
private static final Logger LOG =
LoggerFactory.getLogger(TestAuxServices.class);
@@ -118,25 +117,24 @@ public class TestAuxServices {
private final static Context MOCK_CONTEXT = mock(Context.class);
private final static DeletionService MOCK_DEL_SERVICE = mock(
DeletionService.class);
- private final Boolean useManifest;
+ private Boolean useManifest;
private File rootDir = GenericTestUtils.getTestDir(getClass()
.getSimpleName());
private File manifest = new File(rootDir, "manifest.txt");
private ObjectMapper mapper = new ObjectMapper();
- @Parameterized.Parameters
public static Collection getParams() {
return Arrays.asList(false, true);
}
- @Before
+ @BeforeEach
public void setup() {
if (!rootDir.exists()) {
rootDir.mkdirs();
}
}
- @After
+ @AfterEach
public void cleanup() {
if (useManifest) {
manifest.delete();
@@ -144,8 +142,8 @@ public void cleanup() {
rootDir.delete();
}
- public TestAuxServices(Boolean useManifest) {
- this.useManifest = useManifest;
+ private void initTestAuxServices(Boolean pUseManifest) {
+ this.useManifest = pUseManifest;
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@@ -269,8 +267,10 @@ private void writeManifestFile(AuxServiceRecords services, Configuration
}
@SuppressWarnings("resource")
- @Test
- public void testRemoteAuxServiceClassPath() throws Exception {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testRemoteAuxServiceClassPath(boolean pUseManifest) throws Exception {
+ initTestAuxServices(pUseManifest);
Configuration conf = new YarnConfiguration();
FileSystem fs = FileSystem.get(conf);
AuxServiceRecord serviceC =
@@ -320,11 +320,11 @@ public void testRemoteAuxServiceClassPath() throws Exception {
aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
mockContext2, mockDelService2);
aux.init(conf);
- Assert.fail("The permission of the jar is wrong."
+ fail("The permission of the jar is wrong."
+ "Should throw out exception.");
} catch (YarnRuntimeException ex) {
- Assert.assertTrue(ex.getMessage(), ex.getMessage().contains(
- "The remote jarfile should not be writable by group or others"));
+ assertTrue(ex.getMessage().contains(
+ "The remote jarfile should not be writable by group or others"), ex.getMessage());
}
Files.delete(Paths.get(testJar.getAbsolutePath()));
@@ -345,14 +345,14 @@ public void testRemoteAuxServiceClassPath() throws Exception {
aux.start();
Map meta = aux.getMetaData();
String auxName = "";
- Assert.assertTrue(meta.size() == 1);
+ assertTrue(meta.size() == 1);
for(Entry i : meta.entrySet()) {
auxName = i.getKey();
}
- Assert.assertEquals("ServiceC", auxName);
+ assertEquals("ServiceC", auxName);
aux.serviceStop();
FileStatus[] status = fs.listStatus(rootAuxServiceDirPath);
- Assert.assertTrue(status.length == 1);
+ assertTrue(status.length == 1);
// initialize the same auxservice again, and make sure that we did not
// re-download the jar from remote directory.
@@ -361,14 +361,14 @@ public void testRemoteAuxServiceClassPath() throws Exception {
aux.init(conf);
aux.start();
meta = aux.getMetaData();
- Assert.assertTrue(meta.size() == 1);
+ assertTrue(meta.size() == 1);
for(Entry i : meta.entrySet()) {
auxName = i.getKey();
}
- Assert.assertEquals("ServiceC", auxName);
+ assertEquals("ServiceC", auxName);
verify(mockDelService2, times(0)).delete(any(FileDeletionTask.class));
status = fs.listStatus(rootAuxServiceDirPath);
- Assert.assertTrue(status.length == 1);
+ assertTrue(status.length == 1);
aux.serviceStop();
// change the last modification time for remote jar,
@@ -383,7 +383,7 @@ public void testRemoteAuxServiceClassPath() throws Exception {
aux.start();
verify(mockDelService2, times(1)).delete(any(FileDeletionTask.class));
status = fs.listStatus(rootAuxServiceDirPath);
- Assert.assertTrue(status.length == 2);
+ assertTrue(status.length == 2);
aux.serviceStop();
} finally {
if (testJar != null) {
@@ -400,8 +400,11 @@ public void testRemoteAuxServiceClassPath() throws Exception {
// including ServiceC class, and add this jar to customized directory.
// By setting some proper configurations, we should load ServiceC class
// from customized class path.
- @Test (timeout = 15000)
- public void testCustomizedAuxServiceClassPath() throws Exception {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ @Timeout(value = 15)
+ public void testCustomizedAuxServiceClassPath(boolean pUseManifest) throws Exception {
+ initTestAuxServices(pUseManifest);
// verify that we can load AuxService Class from default Class path
Configuration conf = new YarnConfiguration();
AuxServiceRecord serviceC =
@@ -423,14 +426,14 @@ public void testCustomizedAuxServiceClassPath() throws Exception {
Map meta = aux.getMetaData();
String auxName = "";
Set defaultAuxClassPath = null;
- Assert.assertTrue(meta.size() == 1);
+ assertTrue(meta.size() == 1);
for(Entry i : meta.entrySet()) {
auxName = i.getKey();
String auxClassPath = StandardCharsets.UTF_8.decode(i.getValue()).toString();
defaultAuxClassPath = new HashSet(Arrays.asList(StringUtils
.getTrimmedStrings(auxClassPath)));
}
- Assert.assertEquals("ServiceC", auxName);
+ assertEquals("ServiceC", auxName);
aux.serviceStop();
// create a new jar file, and configure it as customized class path
@@ -474,14 +477,14 @@ public void testCustomizedAuxServiceClassPath() throws Exception {
aux.init(conf);
aux.start();
meta = aux.getMetaData();
- Assert.assertTrue(meta.size() == 1);
+ assertTrue(meta.size() == 1);
Set customizedAuxClassPath = null;
for(Entry i : meta.entrySet()) {
- Assert.assertTrue(auxName.equals(i.getKey()));
+ assertTrue(auxName.equals(i.getKey()));
String classPath = StandardCharsets.UTF_8.decode(i.getValue()).toString();
customizedAuxClassPath = new HashSet(Arrays.asList(StringUtils
.getTrimmedStrings(classPath)));
- Assert.assertTrue(classPath.contains(testJar.getName()));
+ assertTrue(classPath.contains(testJar.getName()));
}
aux.stop();
@@ -489,7 +492,7 @@ public void testCustomizedAuxServiceClassPath() throws Exception {
// and the default class path.
Set mutalClassPath = Sets.intersection(defaultAuxClassPath,
customizedAuxClassPath);
- Assert.assertTrue(mutalClassPath.isEmpty());
+ assertTrue(mutalClassPath.isEmpty());
} finally {
if (testJar != null) {
testJar.delete();
@@ -497,8 +500,11 @@ public void testCustomizedAuxServiceClassPath() throws Exception {
}
}
- @Test (timeout = 15000)
- public void testReuseLocalizedAuxiliaryJar() throws Exception {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ @Timeout(value = 15)
+ public void testReuseLocalizedAuxiliaryJar(boolean pUseManifest) throws Exception {
+ initTestAuxServices(pUseManifest);
File testJar = null;
AuxServices aux = null;
Configuration conf = new YarnConfiguration();
@@ -524,8 +530,7 @@ public void testReuseLocalizedAuxiliaryJar() throws Exception {
// Validate the path on reuse of localized jar
path = aux.maybeDownloadJars("ServiceB", ServiceB.class.getName(),
testJar.getAbsolutePath(), AuxServiceFile.TypeEnum.STATIC, conf);
- assertFalse("Failed to reuse the localized jar",
- path.toString().endsWith("/*"));
+ assertFalse(path.toString().endsWith("/*"), "Failed to reuse the localized jar");
} finally {
if (testJar != null) {
testJar.delete();
@@ -536,8 +541,10 @@ public void testReuseLocalizedAuxiliaryJar() throws Exception {
}
}
- @Test
- public void testAuxEventDispatch() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testAuxEventDispatch(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
Configuration conf = new Configuration();
if (useManifest) {
AuxServiceRecord serviceA =
@@ -579,8 +586,8 @@ public void testAuxEventDispatch() throws IOException {
Collection servs = aux.getServices();
for (AuxiliaryService serv: servs) {
ArrayList appIds = ((LightService)serv).getAppIdsStopped();
- assertEquals("app not properly stopped", 1, appIds.size());
- assertTrue("wrong app stopped", appIds.contains((Integer)66));
+ assertEquals(1, appIds.size(), "app not properly stopped");
+ assertTrue(appIds.contains((Integer)66), "wrong app stopped");
}
for (AuxiliaryService serv : servs) {
@@ -642,8 +649,10 @@ private Configuration getABConf(String aName, String bName,
return conf;
}
- @Test
- public void testAuxServices() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testAuxServices(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
Configuration conf = getABConf();
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
MOCK_CONTEXT, MOCK_DEL_SERVICE);
@@ -656,7 +665,7 @@ public void testAuxServices() throws IOException {
else if (s instanceof ServiceB) { latch *= 3; }
else fail("Unexpected service type " + s.getClass());
}
- assertEquals("Invalid mix of services", 6, latch);
+ assertEquals(6, latch, "Invalid mix of services");
aux.start();
for (AuxiliaryService s : aux.getServices()) {
assertEquals(STARTED, s.getServiceState());
@@ -670,8 +679,10 @@ public void testAuxServices() throws IOException {
}
}
- @Test
- public void testAuxServicesMeta() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testAuxServicesMeta(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
Configuration conf = getABConf();
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
MOCK_CONTEXT, MOCK_DEL_SERVICE);
@@ -684,7 +695,7 @@ public void testAuxServicesMeta() throws IOException {
else if (s instanceof ServiceB) { latch *= 3; }
else fail("Unexpected service type " + s.getClass());
}
- assertEquals("Invalid mix of services", 6, latch);
+ assertEquals(6, latch, "Invalid mix of services");
aux.start();
for (Service s : aux.getServices()) {
assertEquals(STARTED, s.getServiceState());
@@ -701,8 +712,10 @@ public void testAuxServicesMeta() throws IOException {
}
}
- @Test
- public void testAuxUnexpectedStop() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testAuxUnexpectedStop(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
// AuxServices no longer expected to stop when services stop
Configuration conf = getABConf();
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
@@ -712,13 +725,15 @@ public void testAuxUnexpectedStop() throws IOException {
Service s = aux.getServices().iterator().next();
s.stop();
- assertEquals("Auxiliary service stop caused AuxServices stop",
- STARTED, aux.getServiceState());
+ assertEquals(STARTED, aux.getServiceState(),
+ "Auxiliary service stop caused AuxServices stop");
assertEquals(2, aux.getServices().size());
}
- @Test
- public void testValidAuxServiceName() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testValidAuxServiceName(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
Configuration conf = getABConf("Asrv1", "Bsrv_2", ServiceA.class,
ServiceB.class);
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
@@ -726,7 +741,7 @@ public void testValidAuxServiceName() throws IOException {
try {
aux.init(conf);
} catch (Exception ex) {
- Assert.fail("Should not receive the exception.");
+ fail("Should not receive the exception.");
}
//Test bad auxService Name
@@ -744,17 +759,18 @@ public void testValidAuxServiceName() throws IOException {
}
try {
aux1.init(conf);
- Assert.fail("Should receive the exception.");
+ fail("Should receive the exception.");
} catch (Exception ex) {
- assertTrue("Wrong message: " + ex.getMessage(),
- ex.getMessage().contains("The auxiliary service name: 1Asrv1 is " +
- "invalid. The valid service name should only contain a-zA-Z0-9_" +
- " and cannot start with numbers."));
+ assertTrue(ex.getMessage().contains("The auxiliary service name: 1Asrv1 is " +
+ "invalid. The valid service name should only contain a-zA-Z0-9_" +
+ " and cannot start with numbers."), "Wrong message: " + ex.getMessage());
}
}
- @Test
- public void testAuxServiceRecoverySetup() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testAuxServiceRecoverySetup(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
Configuration conf = getABConf("Asrv", "Bsrv", RecoverableServiceA.class,
RecoverableServiceB.class);
conf.setBoolean(YarnConfiguration.NM_RECOVERY_ENABLED, true);
@@ -763,10 +779,10 @@ public void testAuxServiceRecoverySetup() throws IOException {
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
MOCK_CONTEXT, MOCK_DEL_SERVICE);
aux.init(conf);
- Assert.assertEquals(2, aux.getServices().size());
+ assertEquals(2, aux.getServices().size());
File auxStorageDir = new File(TEST_DIR,
AuxServices.STATE_STORE_ROOT_NAME);
- Assert.assertEquals(2, auxStorageDir.listFiles().length);
+ assertEquals(2, auxStorageDir.listFiles().length);
aux.close();
} finally {
FileUtil.fullyDelete(TEST_DIR);
@@ -788,15 +804,14 @@ static class RecoverableAuxService extends AuxiliaryService {
protected void serviceInit(Configuration conf) throws Exception {
super.serviceInit(conf);
Path storagePath = getRecoveryPath();
- Assert.assertNotNull("Recovery path not present when aux service inits",
- storagePath);
- Assert.assertTrue(storagePath.toString().contains(auxName));
+ assertNotNull(storagePath,
+ "Recovery path not present when aux service inits");
+ assertTrue(storagePath.toString().contains(auxName));
FileSystem fs = FileSystem.getLocal(conf);
- Assert.assertTrue("Recovery path does not exist",
- fs.exists(storagePath));
- Assert.assertEquals("Recovery path has wrong permissions",
- new FsPermission((short)0700),
- fs.getFileStatus(storagePath).getPermission());
+ assertTrue(fs.exists(storagePath), "Recovery path does not exist");
+ assertEquals(new FsPermission((short)0700),
+ fs.getFileStatus(storagePath).getPermission(),
+ "Recovery path has wrong permissions");
}
@Override
@@ -854,8 +869,10 @@ public ByteBuffer getMetaData() {
}
}
- @Test
- public void testAuxServicesConfChange() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testAuxServicesConfChange(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
Configuration conf = new Configuration();
if (useManifest) {
AuxServiceRecord service =
@@ -887,9 +904,11 @@ public void testAuxServicesConfChange() throws IOException {
aux.stop();
}
- @Test
- public void testAuxServicesManifestPermissions() throws IOException {
- Assume.assumeTrue(useManifest);
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testAuxServicesManifestPermissions(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
+ assumeTrue(useManifest);
Configuration conf = getABConf();
FileSystem fs = FileSystem.get(conf);
fs.setPermission(new Path(manifest.getAbsolutePath()), FsPermission
@@ -936,9 +955,11 @@ public void testAuxServicesManifestPermissions() throws IOException {
assertEquals(2, aux.getServices().size());
}
- @Test
- public void testRemoveManifest() throws IOException {
- Assume.assumeTrue(useManifest);
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testRemoveManifest(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
+ assumeTrue(useManifest);
Configuration conf = getABConf();
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
MOCK_CONTEXT, MOCK_DEL_SERVICE);
@@ -949,20 +970,22 @@ public void testRemoveManifest() throws IOException {
assertEquals(0, aux.getServices().size());
}
- @Test
- public void testManualReload() throws IOException {
- Assume.assumeTrue(useManifest);
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testManualReload(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
+ assumeTrue(useManifest);
Configuration conf = getABConf();
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
MOCK_CONTEXT, MOCK_DEL_SERVICE);
aux.init(conf);
try {
aux.reload(null);
- Assert.fail("Should receive the exception.");
+ fail("Should receive the exception.");
} catch (IOException e) {
- assertTrue("Wrong message: " + e.getMessage(),
- e.getMessage().equals("Auxiliary services have not been started " +
- "yet, please retry later"));
+ assertTrue(e.getMessage().equals("Auxiliary services have not been started " +
+ "yet, please retry later"),
+ "Wrong message: " + e.getMessage());
}
aux.start();
assertEquals(2, aux.getServices().size());
@@ -973,27 +996,29 @@ public void testManualReload() throws IOException {
aux.stop();
}
- @Test
- public void testReloadWhenDisabled() throws IOException {
+ @ParameterizedTest
+ @MethodSource("getParams")
+ public void testReloadWhenDisabled(boolean pUseManifest) throws IOException {
+ initTestAuxServices(pUseManifest);
Configuration conf = new Configuration();
final AuxServices aux = new AuxServices(MOCK_AUX_PATH_HANDLER,
MOCK_CONTEXT, MOCK_DEL_SERVICE);
aux.init(conf);
try {
aux.reload(null);
- Assert.fail("Should receive the exception.");
+ fail("Should receive the exception.");
} catch (IOException e) {
- assertTrue("Wrong message: " + e.getMessage(),
- e.getMessage().equals("Dynamic reloading is not enabled via " +
- YarnConfiguration.NM_AUX_SERVICES_MANIFEST_ENABLED));
+ assertTrue(e.getMessage().equals("Dynamic reloading is not enabled via " +
+ YarnConfiguration.NM_AUX_SERVICES_MANIFEST_ENABLED),
+ "Wrong message: " + e.getMessage());
}
try {
aux.reloadManifest();
- Assert.fail("Should receive the exception.");
+ fail("Should receive the exception.");
} catch (IOException e) {
- assertTrue("Wrong message: " + e.getMessage(),
- e.getMessage().equals("Dynamic reloading is not enabled via " +
- YarnConfiguration.NM_AUX_SERVICES_MANIFEST_ENABLED));
+ assertTrue(e.getMessage().equals("Dynamic reloading is not enabled via " +
+ YarnConfiguration.NM_AUX_SERVICES_MANIFEST_ENABLED),
+ "Wrong message: " + e.getMessage());
}
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java
index 7a65a799080f6..5527dd5d09c35 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java
@@ -30,9 +30,12 @@
import static org.apache.hadoop.test.MetricsAsserts.assertGauge;
import static org.apache.hadoop.test.MetricsAsserts.assertGaugeGt;
import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.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;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
@@ -124,8 +127,8 @@
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerStartContext;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
@@ -229,7 +232,7 @@ public void testContainerManagerInitialization() throws IOException {
if (!localAddr.getHostAddress().equals(fqdn)) {
// only check if fqdn is not same as ip
// api returns ip in case of resolution failure
- Assert.assertEquals(fqdn, context.getNodeId().getHost());
+ assertEquals(fqdn, context.getNodeId().getHost());
}
// Just do a query for a non-existing container.
@@ -248,7 +251,7 @@ public void testContainerManagerInitialization() throws IOException {
} catch (Throwable e) {
throwsException = true;
}
- Assert.assertTrue(throwsException);
+ assertTrue(throwsException);
}
@Test
@@ -318,17 +321,17 @@ public void testContainerSetup() throws Exception {
for (File f : new File[] { localDir, sysDir, userCacheDir, appDir,
appSysDir,
containerDir, containerSysDir }) {
- Assert.assertTrue(f.getAbsolutePath() + " doesn't exist!!", f.exists());
- Assert.assertTrue(f.getAbsolutePath() + " is not a directory!!",
- f.isDirectory());
+ assertTrue(f.exists(), f.getAbsolutePath() + " doesn't exist!!");
+ assertTrue(f.isDirectory(),
+ f.getAbsolutePath() + " is not a directory!!");
}
- Assert.assertTrue(targetFile.getAbsolutePath() + " doesn't exist!!",
- targetFile.exists());
+ assertTrue(targetFile.exists(),
+ targetFile.getAbsolutePath() + " doesn't exist!!");
// Now verify the contents of the file
BufferedReader reader = new BufferedReader(new FileReader(targetFile));
- Assert.assertEquals("Hello World!", reader.readLine());
- Assert.assertEquals(null, reader.readLine());
+ assertEquals("Hello World!", reader.readLine());
+ assertEquals(null, reader.readLine());
//
// check the localization counter
@@ -364,7 +367,8 @@ public void testContainerSetup() throws Exception {
assertGauge("LocalizedCacheHitFilesRatio", 50, rb);
}
- @Test (timeout = 10000L)
+ @Test
+ @Timeout(10)
public void testAuxPathHandler() throws Exception {
File testDir = GenericTestUtils
.getTestDir(TestContainerManager.class.getSimpleName() + "LocDir");
@@ -391,7 +395,7 @@ public void testAuxPathHandler() throws Exception {
auxiliaryLocalPathHandler.getLocalPathForRead("test");
fail("Should not have passed!");
} catch (IOException e) {
- Assert.assertTrue(e.getMessage().contains("Could not find"));
+ assertTrue(e.getMessage().contains("Could not find"));
} finally {
testFile.delete();
testDir.delete();
@@ -460,26 +464,26 @@ public void testContainerLaunchAndStop() throws IOException,
Thread.sleep(1000);
LOG.info("Waiting for process start-file to be created");
}
- Assert.assertTrue("ProcessStartFile doesn't exist!",
- processStartFile.exists());
+ assertTrue(processStartFile.exists(),
+ "ProcessStartFile doesn't exist!");
// Now verify the contents of the file
BufferedReader reader =
new BufferedReader(new FileReader(processStartFile));
- Assert.assertEquals("Hello World!", reader.readLine());
+ assertEquals("Hello World!", reader.readLine());
// Get the pid of the process
String pid = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
// Now test the stop functionality.
// Assert that the process is alive
- Assert.assertTrue("Process is not alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is not alive!");
// Once more
- Assert.assertTrue("Process is not alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is not alive!");
List containerIds = new ArrayList<>();
containerIds.add(cId);
@@ -494,11 +498,11 @@ public void testContainerLaunchAndStop() throws IOException,
ContainerStatus containerStatus =
containerManager.getContainerStatuses(gcsRequest).getContainerStatuses().get(0);
int expectedExitCode = ContainerExitStatus.KILLED_BY_APPMASTER;
- Assert.assertEquals(expectedExitCode, containerStatus.getExitStatus());
+ assertEquals(expectedExitCode, containerStatus.getExitStatus());
// Assert that the process is not alive anymore
- Assert.assertFalse("Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is still alive!");
}
@Test
@@ -523,9 +527,9 @@ private String doRestartTests(ContainerId cId, File oldStartFile,
int beforeRestart = metrics.getRunningContainers();
Container container =
containerManager.getContext().getContainers().get(cId);
- Assert.assertFalse(container.isReInitializing());
+ assertFalse(container.isReInitializing());
containerManager.restartContainer(cId);
- Assert.assertTrue(container.isReInitializing());
+ assertTrue(container.isReInitializing());
// Wait for original process to die and the new process to restart
int timeoutSecs = 0;
@@ -538,8 +542,8 @@ private String doRestartTests(ContainerId cId, File oldStartFile,
"and new process to start!!");
}
- Assert.assertFalse("Old Process Still alive!!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pid),
+ "Old Process Still alive!!");
String newPid = null;
timeoutSecs = 0;
@@ -548,11 +552,11 @@ private String doRestartTests(ContainerId cId, File oldStartFile,
// Now verify the contents of the file
BufferedReader reader =
new BufferedReader(new FileReader(oldStartFile));
- Assert.assertEquals(testString, reader.readLine());
+ assertEquals(testString, reader.readLine());
// Get the pid of the process
newPid = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
reader.close();
if (!newPid.equals(pid)) {
break;
@@ -561,10 +565,10 @@ private String doRestartTests(ContainerId cId, File oldStartFile,
}
// Assert both pids are different
- Assert.assertNotEquals(pid, newPid);
+ assertNotEquals(pid, newPid);
// Container cannot rollback from a restart
- Assert.assertEquals(canRollback, container.canRollback());
+ assertEquals(canRollback, container.canRollback());
return newPid;
}
@@ -587,33 +591,33 @@ private String[] testContainerReInitSuccess(boolean autoCommit)
ResourceUtilization afterUpgrade =
ResourceUtilization.newInstance(
containerManager.getContainerScheduler().getCurrentUtilization());
- Assert.assertEquals("Possible resource leak detected !!",
- beforeUpgrade, afterUpgrade);
+ assertEquals(beforeUpgrade, afterUpgrade,
+ "Possible resource leak detected !!");
// Assert that the First process is not alive anymore
- Assert.assertFalse("Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is still alive!");
BufferedReader reader =
new BufferedReader(new FileReader(newStartFile));
- Assert.assertEquals("Upgrade World!", reader.readLine());
+ assertEquals("Upgrade World!", reader.readLine());
// Get the pid of the process
String newPid = reader.readLine().trim();
- Assert.assertNotEquals("Old and New Pids must be different !", pid, newPid);
+ assertNotEquals(pid, newPid, "Old and New Pids must be different !");
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
reader.close();
// Verify old file still exists and is accessible by
// the new process...
reader = new BufferedReader(new FileReader(oldStartFile));
- Assert.assertEquals("Hello World!", reader.readLine());
+ assertEquals("Hello World!", reader.readLine());
// Assert that the New process is alive
- Assert.assertTrue("New Process is not alive!",
- DefaultContainerExecutor.containerIsAlive(newPid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(newPid),
+ "New Process is not alive!");
return new String[]{pid, newPid};
}
@@ -627,15 +631,15 @@ public void testContainerUpgradeSuccessAutoCommit() throws IOException,
// Should not be able to Commit (since already auto committed)
try {
containerManager.commitLastReInitialization(createContainerId(0));
- Assert.fail();
+ fail();
} catch (Exception e) {
- Assert.assertTrue(e.getMessage().contains("Nothing to Commit"));
+ assertTrue(e.getMessage().contains("Nothing to Commit"));
}
List containerStates =
listener.states.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
ContainerState.NEW,
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
@@ -657,7 +661,7 @@ public void testContainerUpgradeSuccessAutoCommit() throws IOException,
List containerEventTypes =
listener.events.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
ContainerEventType.INIT_CONTAINER,
ContainerEventType.RESOURCE_LOCALIZED,
ContainerEventType.CONTAINER_LAUNCHED,
@@ -677,9 +681,9 @@ public void testContainerUpgradeSuccessExplicitCommit() throws IOException,
// Should not be able to Rollback once committed
try {
containerManager.rollbackLastReInitialization(cId);
- Assert.fail();
+ fail();
} catch (Exception e) {
- Assert.assertTrue(e.getMessage().contains("Nothing to rollback to"));
+ assertTrue(e.getMessage().contains("Nothing to rollback to"));
}
}
@@ -709,10 +713,10 @@ public void testContainerUpgradeSuccessExplicitRollback() throws IOException,
Container container =
containerManager.getContext().getContainers().get(cId);
- Assert.assertTrue(container.isReInitializing());
+ assertTrue(container.isReInitializing());
// Original should be dead anyway
- Assert.assertFalse("Original Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(pids[0]));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pids[0]),
+ "Original Process is still alive!");
// Wait for new container to startup
int timeoutSecs = 0;
@@ -720,7 +724,7 @@ public void testContainerUpgradeSuccessExplicitRollback() throws IOException,
Thread.sleep(1000);
LOG.info("Waiting for ReInitialization to complete..");
}
- Assert.assertFalse(container.isReInitializing());
+ assertFalse(container.isReInitializing());
timeoutSecs = 0;
// Wait for new processStartfile to be created
@@ -732,19 +736,19 @@ public void testContainerUpgradeSuccessExplicitRollback() throws IOException,
// Now verify the contents of the file
BufferedReader reader =
new BufferedReader(new FileReader(oldStartFile));
- Assert.assertEquals("Hello World!", reader.readLine());
+ assertEquals("Hello World!", reader.readLine());
// Get the pid of the process
String rolledBackPid = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
- Assert.assertNotEquals("The Rolled-back process should be a different pid",
- pids[0], rolledBackPid);
+ assertNotEquals(pids[0], rolledBackPid,
+ "The Rolled-back process should be a different pid");
List containerStates =
listener.states.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
ContainerState.NEW,
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
@@ -784,7 +788,7 @@ public void testContainerUpgradeSuccessExplicitRollback() throws IOException,
List containerEventTypes =
listener.events.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
ContainerEventType.INIT_CONTAINER,
ContainerEventType.RESOURCE_LOCALIZED,
ContainerEventType.CONTAINER_LAUNCHED,
@@ -825,13 +829,13 @@ public void testContainerUpgradeLocalizationFailure() throws IOException,
// Assert that the First process is STILL alive
// since upgrade was terminated..
- Assert.assertTrue("Process is NOT alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is NOT alive!");
List containerStates =
listener.states.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
ContainerState.NEW,
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
@@ -847,7 +851,7 @@ public void testContainerUpgradeLocalizationFailure() throws IOException,
List containerEventTypes =
listener.events.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
ContainerEventType.INIT_CONTAINER,
ContainerEventType.RESOURCE_LOCALIZED,
ContainerEventType.CONTAINER_LAUNCHED,
@@ -876,8 +880,8 @@ public void testContainerUpgradeProcessFailure() throws IOException,
prepareContainerUpgrade(true, true, false, cId, newStartFile);
// Assert that the First process is not alive anymore
- Assert.assertFalse("Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is still alive!");
}
@Test
@@ -901,8 +905,8 @@ public void testContainerUpgradeRollbackDueToFailure() throws IOException,
prepareContainerUpgrade(false, true, false, cId, newStartFile);
// Assert that the First process is not alive anymore
- Assert.assertFalse("Original Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pid),
+ "Original Process is still alive!");
int timeoutSecs = 0;
// Wait for oldStartFile to be created
@@ -916,19 +920,19 @@ public void testContainerUpgradeRollbackDueToFailure() throws IOException,
// Now verify the contents of the file
BufferedReader reader =
new BufferedReader(new FileReader(oldStartFile));
- Assert.assertEquals("Hello World!", reader.readLine());
+ assertEquals("Hello World!", reader.readLine());
// Get the pid of the process
String rolledBackPid = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
- Assert.assertNotEquals("The Rolled-back process should be a different pid",
- pid, rolledBackPid);
+ assertNotEquals(pid, rolledBackPid,
+ "The Rolled-back process should be a different pid");
List containerStates =
listener.states.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
ContainerState.NEW,
org.apache.hadoop.yarn.server.nodemanager.containermanager.container.
@@ -956,7 +960,7 @@ public void testContainerUpgradeRollbackDueToFailure() throws IOException,
List containerEventTypes =
listener.events.get(createContainerId(0));
- Assert.assertEquals(Arrays.asList(
+ assertEquals(Arrays.asList(
ContainerEventType.INIT_CONTAINER,
ContainerEventType.RESOURCE_LOCALIZED,
ContainerEventType.CONTAINER_LAUNCHED,
@@ -996,7 +1000,7 @@ private void prepareContainerUpgrade(boolean autoCommit, boolean failCmd,
containerManager.reInitializeContainer(cId, containerLaunchContext,
autoCommit);
} catch (Exception e) {
- Assert.assertTrue(e.getMessage().contains("Cannot perform RE_INIT"));
+ assertTrue(e.getMessage().contains("Cannot perform RE_INIT"));
}
int timeoutSecs = 0;
int maxTimeToWait = failLoc ? 10 : 20;
@@ -1038,24 +1042,23 @@ private String prepareInitialContainer(ContainerId cId, File startFile)
Thread.sleep(1000);
LOG.info("Waiting for process start-file to be created");
}
- Assert.assertTrue("ProcessStartFile doesn't exist!",
- startFile.exists());
+ assertTrue(startFile.exists(), "ProcessStartFile doesn't exist!");
// Now verify the contents of the file
BufferedReader reader =
new BufferedReader(new FileReader(startFile));
- Assert.assertEquals("Hello World!", reader.readLine());
+ assertEquals("Hello World!", reader.readLine());
// Get the pid of the process
String pid = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
// Assert that the process is alive
- Assert.assertTrue("Process is not alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is not alive!");
// Once more
- Assert.assertTrue("Process is not alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is not alive!");
return pid;
}
@@ -1190,20 +1193,19 @@ protected void testContainerLaunchAndExit(int exitCode) throws IOException,
ContainerStatus containerStatus = containerManager.
getContainerStatuses(gcsRequest).getContainerStatuses().get(0);
- // Verify exit status matches exit state of script
- Assert.assertEquals(exitCode,
- containerStatus.getExitStatus());
+ // Verify exit status matches exit state of script
+ assertEquals(exitCode, containerStatus.getExitStatus());
}
@Test
public void testContainerLaunchAndExitSuccess() throws IOException,
InterruptedException, YarnException {
- containerManager.start();
- int exitCode = 0;
+ containerManager.start();
+ int exitCode = 0;
- // launch context for a command that will return exit code 0
- // and verify exit code returned
- testContainerLaunchAndExit(exitCode);
+ // launch context for a command that will return exit code 0
+ // and verify exit code returned
+ testContainerLaunchAndExit(exitCode);
}
@Test
@@ -1306,9 +1308,9 @@ public Boolean get() {
// Verify container cannot localize resources while at non-running state.
try{
containerManager.localize(request);
- Assert.fail();
+ fail();
} catch (YarnException e) {
- Assert.assertTrue(
+ assertTrue(
e.getMessage().contains("Cannot perform LOCALIZE"));
}
}
@@ -1333,19 +1335,16 @@ private void checkResourceLocalized(ContainerId containerId, String symLink) {
// localDir/nmPrivate/application_0_0000/container_0_0000_01_000000
File containerSysDir = new File(appSysDir, containerId.toString());
- Assert.assertTrue("AppDir " + appDir.getAbsolutePath() + " doesn't exist!!",
- appDir.exists());
- Assert.assertTrue(
- "AppSysDir " + appSysDir.getAbsolutePath() + " doesn't exist!!",
- appSysDir.exists());
- Assert.assertTrue(
- "containerDir " + containerDir.getAbsolutePath() + " doesn't exist !",
- containerDir.exists());
- Assert.assertTrue("containerSysDir " + containerSysDir.getAbsolutePath()
- + " doesn't exist !", containerDir.exists());
- Assert.assertTrue(
- "targetFile " + targetFile.getAbsolutePath() + " doesn't exist !!",
- targetFile.exists());
+ assertTrue(appDir.exists(), "AppDir " + appDir.getAbsolutePath() + " doesn't exist!!");
+ assertTrue(appSysDir.exists(), "AppSysDir "
+ + appSysDir.getAbsolutePath() + " doesn't exist!!");
+ assertTrue(containerDir.exists(), "containerDir "
+ + containerDir.getAbsolutePath() + " doesn't exist !");
+ assertTrue(containerDir.exists(), "containerSysDir "
+ + containerSysDir.getAbsolutePath()
+ + " doesn't exist !");
+ assertTrue(targetFile.exists(),
+ "targetFile " + targetFile.getAbsolutePath() + " doesn't exist !!");
}
@Test
@@ -1423,15 +1422,15 @@ public void testLocalFilesCleanup() throws InterruptedException,
File appSysDir = new File(sysDir, appIDStr);
File containerSysDir = new File(appSysDir, containerIDStr);
// AppDir should still exist
- Assert.assertTrue("AppDir " + appDir.getAbsolutePath()
- + " doesn't exist!!", appDir.exists());
- Assert.assertTrue("AppSysDir " + appSysDir.getAbsolutePath()
- + " doesn't exist!!", appSysDir.exists());
+ assertTrue(appDir.exists(), "AppDir " + appDir.getAbsolutePath()
+ + " doesn't exist!!");
+ assertTrue(appSysDir.exists(), "AppSysDir " + appSysDir.getAbsolutePath()
+ + " doesn't exist!!");
for (File f : new File[] { containerDir, containerSysDir }) {
- Assert.assertFalse(f.getAbsolutePath() + " exists!!", f.exists());
+ assertFalse(f.exists(), f.getAbsolutePath() + " exists!!");
}
- Assert.assertFalse(targetFile.getAbsolutePath() + " exists!!",
- targetFile.exists());
+ assertFalse(targetFile.exists(),
+ targetFile.getAbsolutePath() + " exists!!");
// Simulate RM sending an AppFinish event.
containerManager.handle(new CMgrCompletedAppsEvent(Arrays
@@ -1450,15 +1449,15 @@ public void testLocalFilesCleanup() throws InterruptedException,
while (f.exists() && timeout++ < 15) {
Thread.sleep(1000);
}
- Assert.assertFalse(f.getAbsolutePath() + " exists!!", f.exists());
+ assertFalse(f.exists(), f.getAbsolutePath() + " exists!!");
}
// Wait for deletion
int timeout = 0;
while (targetFile.exists() && timeout++ < 15) {
Thread.sleep(1000);
}
- Assert.assertFalse(targetFile.getAbsolutePath() + " exists!!",
- targetFile.exists());
+ assertFalse(targetFile.exists(),
+ targetFile.getAbsolutePath() + " exists!!");
}
@Test
@@ -1495,14 +1494,14 @@ public void testContainerLaunchFromPreviousRM() throws IOException,
} catch (Throwable e) {
e.printStackTrace();
catchException = true;
- Assert.assertTrue(e.getMessage().contains(
+ assertTrue(e.getMessage().contains(
"Container " + cId1 + " rejected as it is allocated by a previous RM"));
- Assert.assertTrue(e.getClass().getName()
+ assertTrue(e.getClass().getName()
.equalsIgnoreCase(InvalidContainerException.class.getName()));
}
// Verify that startContainer fail because of invalid container request
- Assert.assertTrue(catchException);
+ assertTrue(catchException);
// Construct the Container with a RMIdentifier within current RM
StartContainerRequest startRequest2 =
@@ -1523,7 +1522,7 @@ public void testContainerLaunchFromPreviousRM() throws IOException,
noException = false;
}
// Verify that startContainer get no YarnException
- Assert.assertTrue(noException);
+ assertTrue(noException);
}
@Test
@@ -1555,17 +1554,17 @@ public void testMultipleContainersLaunch() throws Exception {
containerManager.startContainers(requestList);
Thread.sleep(5000);
- Assert.assertEquals(5, response.getSuccessfullyStartedContainers().size());
+ assertEquals(5, response.getSuccessfullyStartedContainers().size());
for (ContainerId id : response.getSuccessfullyStartedContainers()) {
// Containers with odd id should succeed.
- Assert.assertEquals(1, id.getContainerId() & 1);
+ assertEquals(1, id.getContainerId() & 1);
}
- Assert.assertEquals(5, response.getFailedRequests().size());
+ assertEquals(5, response.getFailedRequests().size());
for (Map.Entry entry : response
.getFailedRequests().entrySet()) {
// Containers with even id should fail.
- Assert.assertEquals(0, entry.getKey().getContainerId() & 1);
- Assert.assertTrue(entry.getValue().getMessage()
+ assertEquals(0, entry.getKey().getContainerId() & 1);
+ assertTrue(entry.getValue().getMessage()
.contains(
"Container " + entry.getKey() + " rejected as it is allocated by a previous RM"));
}
@@ -1605,17 +1604,17 @@ public void testMultipleContainersStopAndGetStatus() throws Exception {
GetContainerStatusesRequest.newInstance(containerIds);
GetContainerStatusesResponse statusResponse =
containerManager.getContainerStatuses(statusRequest);
- Assert.assertEquals(5, statusResponse.getContainerStatuses().size());
+ assertEquals(5, statusResponse.getContainerStatuses().size());
for (ContainerStatus status : statusResponse.getContainerStatuses()) {
// Containers with odd id should succeed
- Assert.assertEquals(1, status.getContainerId().getContainerId() & 1);
+ assertEquals(1, status.getContainerId().getContainerId() & 1);
}
- Assert.assertEquals(5, statusResponse.getFailedRequests().size());
+ assertEquals(5, statusResponse.getFailedRequests().size());
for (Map.Entry entry : statusResponse
.getFailedRequests().entrySet()) {
// Containers with even id should fail.
- Assert.assertEquals(0, entry.getKey().getContainerId() & 1);
- Assert.assertTrue(entry.getValue().getMessage()
+ assertEquals(0, entry.getKey().getContainerId() & 1);
+ assertTrue(entry.getValue().getMessage()
.contains("attempted to get status for non-application container"));
}
@@ -1624,18 +1623,18 @@ public void testMultipleContainersStopAndGetStatus() throws Exception {
StopContainersRequest.newInstance(containerIds);
StopContainersResponse stopResponse =
containerManager.stopContainers(stopRequest);
- Assert.assertEquals(5, stopResponse.getSuccessfullyStoppedContainers()
+ assertEquals(5, stopResponse.getSuccessfullyStoppedContainers()
.size());
for (ContainerId id : stopResponse.getSuccessfullyStoppedContainers()) {
// Containers with odd id should succeed.
- Assert.assertEquals(1, id.getContainerId() & 1);
+ assertEquals(1, id.getContainerId() & 1);
}
- Assert.assertEquals(5, stopResponse.getFailedRequests().size());
+ assertEquals(5, stopResponse.getFailedRequests().size());
for (Map.Entry entry : stopResponse
.getFailedRequests().entrySet()) {
// Containers with even id should fail.
- Assert.assertEquals(0, entry.getKey().getContainerId() & 1);
- Assert.assertTrue(entry.getValue().getMessage()
+ assertEquals(0, entry.getKey().getContainerId() & 1);
+ assertTrue(entry.getValue().getMessage()
.contains("attempted to stop non-application container"));
}
}
@@ -1661,10 +1660,10 @@ public void testUnauthorizedRequests() throws IOException, YarnException {
StartContainersResponse startResponse =
containerManager.startContainers(allRequests);
- Assert.assertFalse("Should not be authorized to start container",
- startResponse.getSuccessfullyStartedContainers().contains(cId));
- Assert.assertTrue("Start container request should fail",
- startResponse.getFailedRequests().containsKey(cId));
+ assertFalse(startResponse.getSuccessfullyStartedContainers().contains(cId),
+ "Should not be authorized to start container");
+ assertTrue(startResponse.getFailedRequests().containsKey(cId),
+ "Start container request should fail");
// Insert the containerId into context, make it as if it is running
ContainerTokenIdentifier containerTokenIdentifier =
@@ -1681,10 +1680,10 @@ public void testUnauthorizedRequests() throws IOException, YarnException {
StopContainersResponse stopResponse =
containerManager.stopContainers(stopRequest);
- Assert.assertFalse("Should not be authorized to stop container",
- stopResponse.getSuccessfullyStoppedContainers().contains(cId));
- Assert.assertTrue("Stop container request should fail",
- stopResponse.getFailedRequests().containsKey(cId));
+ assertFalse(stopResponse.getSuccessfullyStoppedContainers().contains(cId),
+ "Should not be authorized to stop container");
+ assertTrue(stopResponse.getFailedRequests().containsKey(cId),
+ "Stop container request should fail");
// getContainerStatuses()
containerIds = new ArrayList<>();
@@ -1694,10 +1693,10 @@ public void testUnauthorizedRequests() throws IOException, YarnException {
GetContainerStatusesResponse response =
containerManager.getContainerStatuses(request);
- Assert.assertEquals("Should not be authorized to get container status",
- response.getContainerStatuses().size(), 0);
- Assert.assertTrue("Get status request should fail",
- response.getFailedRequests().containsKey(cId));
+ assertEquals(response.getContainerStatuses().size(), 0,
+ "Should not be authorized to get container status");
+ assertTrue(response.getFailedRequests().containsKey(cId),
+ "Get status request should fail");
}
@Test
@@ -1734,10 +1733,10 @@ public void testStartContainerFailureWithUnknownAuxService() throws Exception {
StartContainersResponse response =
containerManager.startContainers(requestList);
- Assert.assertEquals(1, response.getFailedRequests().size());
- Assert.assertEquals(0, response.getSuccessfullyStartedContainers().size());
- Assert.assertTrue(response.getFailedRequests().containsKey(cId));
- Assert.assertTrue(response.getFailedRequests().get(cId).getMessage()
+ assertEquals(1, response.getFailedRequests().size());
+ assertEquals(0, response.getSuccessfullyStartedContainers().size());
+ assertTrue(response.getFailedRequests().containsKey(cId));
+ assertTrue(response.getFailedRequests().get(cId).getMessage()
.contains("The auxService:" + serviceName + " does not exist"));
}
@@ -1754,7 +1753,7 @@ public void testNullTokens() throws Exception {
} catch(YarnException ye) {
strExceptionMsg = ye.getMessage();
}
- Assert.assertEquals(strExceptionMsg,
+ assertEquals(strExceptionMsg,
ContainerManagerImpl.INVALID_NMTOKEN_MSG);
strExceptionMsg = "";
@@ -1764,7 +1763,7 @@ public void testNullTokens() throws Exception {
} catch(YarnException ye) {
strExceptionMsg = ye.getMessage();
}
- Assert.assertEquals(strExceptionMsg,
+ assertEquals(strExceptionMsg,
ContainerManagerImpl.INVALID_CONTAINERTOKEN_MSG);
strExceptionMsg = "";
@@ -1774,7 +1773,7 @@ public void testNullTokens() throws Exception {
} catch(YarnException ye) {
strExceptionMsg = ye.getMessage();
}
- Assert.assertEquals(strExceptionMsg,
+ assertEquals(strExceptionMsg,
ContainerManagerImpl.INVALID_NMTOKEN_MSG);
strExceptionMsg = "";
@@ -1783,7 +1782,7 @@ public void testNullTokens() throws Exception {
} catch(YarnException ye) {
strExceptionMsg = ye.getMessage();
}
- Assert.assertEquals(strExceptionMsg,
+ assertEquals(strExceptionMsg,
ContainerManagerImpl.INVALID_NMTOKEN_MSG);
ContainerManagerImpl spyContainerMgr = spy(cMgrImpl);
@@ -1798,7 +1797,7 @@ public void testNullTokens() throws Exception {
} catch(YarnException ye) {
strExceptionMsg = ye.getMessage();
}
- Assert.assertEquals(strExceptionMsg,
+ assertEquals(strExceptionMsg,
ContainerManagerImpl.INVALID_NMTOKEN_MSG);
strExceptionMsg = "";
@@ -1808,7 +1807,7 @@ public void testNullTokens() throws Exception {
} catch(YarnException ye) {
strExceptionMsg = ye.getMessage();
}
- Assert.assertEquals(strExceptionMsg,
+ assertEquals(strExceptionMsg,
ContainerManagerImpl.INVALID_NMTOKEN_MSG);
Mockito.doNothing().when(spyContainerMgr).authorizeUser(ugInfo, null);
@@ -1822,7 +1821,7 @@ public void testNullTokens() throws Exception {
} catch(YarnException ye) {
strExceptionMsg = ye.getCause().getMessage();
}
- Assert.assertEquals(strExceptionMsg,
+ assertEquals(strExceptionMsg,
ContainerManagerImpl.INVALID_CONTAINERTOKEN_MSG);
}
@@ -1846,10 +1845,10 @@ public void testIncreaseContainerResourceWithInvalidRequests() throws Exception
StartContainersResponse response = containerManager
.startContainers(requestList);
- Assert.assertEquals(4, response.getSuccessfullyStartedContainers().size());
+ assertEquals(4, response.getSuccessfullyStartedContainers().size());
int i = 0;
for (ContainerId id : response.getSuccessfullyStartedContainers()) {
- Assert.assertEquals(i, id.getContainerId());
+ assertEquals(i, id.getContainerId());
i++;
}
@@ -1880,14 +1879,14 @@ public void testIncreaseContainerResourceWithInvalidRequests() throws Exception
ContainerUpdateResponse updateResponse =
containerManager.updateContainer(updateRequest);
// Check response
- Assert.assertEquals(
+ assertEquals(
1, updateResponse.getSuccessfullyUpdatedContainers().size());
- Assert.assertEquals(1, updateResponse.getFailedRequests().size());
+ assertEquals(1, updateResponse.getFailedRequests().size());
for (Map.Entry entry : updateResponse
.getFailedRequests().entrySet()) {
- Assert.assertNotNull("Failed message", entry.getValue().getMessage());
+ assertNotNull(entry.getValue().getMessage(), "Failed message");
if (cId7.equals(entry.getKey())) {
- Assert.assertTrue(entry.getValue().getMessage()
+ assertTrue(entry.getValue().getMessage()
.contains("Container " + cId7.toString()
+ " is not handled by this NodeManager"));
} else {
@@ -1958,9 +1957,8 @@ public void testChangeContainerResource() throws Exception {
ContainerUpdateRequest.newInstance(increaseTokens);
ContainerUpdateResponse updateResponse =
containerManager.updateContainer(updateRequest);
- Assert.assertEquals(
- 1, updateResponse.getSuccessfullyUpdatedContainers().size());
- Assert.assertTrue(updateResponse.getFailedRequests().isEmpty());
+ assertEquals(1, updateResponse.getSuccessfullyUpdatedContainers().size());
+ assertTrue(updateResponse.getFailedRequests().isEmpty());
// Check status
List containerIds = new ArrayList<>();
containerIds.add(cId);
@@ -1980,9 +1978,8 @@ public void testChangeContainerResource() throws Exception {
updateRequest = ContainerUpdateRequest.newInstance(decreaseTokens);
updateResponse = containerManager.updateContainer(updateRequest);
- Assert.assertEquals(
- 1, updateResponse.getSuccessfullyUpdatedContainers().size());
- Assert.assertTrue(updateResponse.getFailedRequests().isEmpty());
+ assertEquals(1, updateResponse.getSuccessfullyUpdatedContainers().size());
+ assertTrue(updateResponse.getFailedRequests().isEmpty());
// Check status with retry
containerStatus = containerManager
@@ -2069,8 +2066,8 @@ private void testContainerLaunchAndSignal(SignalContainerCommand command)
Thread.sleep(1000);
LOG.info("Waiting for process start-file to be created");
}
- Assert.assertTrue("ProcessStartFile doesn't exist!",
- processStartFile.exists());
+ assertTrue(processStartFile.exists(),
+ "ProcessStartFile doesn't exist!");
// Simulate NodeStatusUpdaterImpl sending CMgrSignalContainersEvent
SignalContainerRequest signalReq =
@@ -2086,8 +2083,8 @@ private void testContainerLaunchAndSignal(SignalContainerCommand command)
} else {
verify(exec, timeout(10000).atLeastOnce()).signalContainer(signalContextCaptor.capture());
ContainerSignalContext signalContext = signalContextCaptor.getAllValues().get(0);
- Assert.assertEquals(cId, signalContext.getContainer().getContainerId());
- Assert.assertEquals(signal, signalContext.getSignal());
+ assertEquals(cId, signalContext.getContainer().getContainerId());
+ assertEquals(signal, signalContext.getSignal());
}
}
@@ -2129,10 +2126,10 @@ public void testStartContainerFailureWithInvalidLocalResource()
StartContainersResponse response =
containerManager.startContainers(requestList);
- Assert.assertTrue(response.getFailedRequests().size() == 1);
- Assert.assertTrue(response.getSuccessfullyStartedContainers().size() == 0);
- Assert.assertTrue(response.getFailedRequests().containsKey(cId));
- Assert.assertTrue(response.getFailedRequests().get(cId).getMessage()
+ assertTrue(response.getFailedRequests().size() == 1);
+ assertTrue(response.getSuccessfullyStartedContainers().size() == 0);
+ assertTrue(response.getFailedRequests().containsKey(cId));
+ assertTrue(response.getFailedRequests().get(cId).getMessage()
.contains("Null resource URL for local resource"));
}
@@ -2174,10 +2171,10 @@ public void testStartContainerFailureWithNullTypeLocalResource()
StartContainersResponse response =
containerManager.startContainers(requestList);
- Assert.assertTrue(response.getFailedRequests().size() == 1);
- Assert.assertTrue(response.getSuccessfullyStartedContainers().size() == 0);
- Assert.assertTrue(response.getFailedRequests().containsKey(cId));
- Assert.assertTrue(response.getFailedRequests().get(cId).getMessage()
+ assertTrue(response.getFailedRequests().size() == 1);
+ assertTrue(response.getSuccessfullyStartedContainers().size() == 0);
+ assertTrue(response.getFailedRequests().containsKey(cId));
+ assertTrue(response.getFailedRequests().get(cId).getMessage()
.contains("Null resource type for local resource"));
}
@@ -2219,10 +2216,10 @@ public void testStartContainerFailureWithNullVisibilityLocalResource()
StartContainersResponse response =
containerManager.startContainers(requestList);
- Assert.assertTrue(response.getFailedRequests().size() == 1);
- Assert.assertTrue(response.getSuccessfullyStartedContainers().size() == 0);
- Assert.assertTrue(response.getFailedRequests().containsKey(cId));
- Assert.assertTrue(response.getFailedRequests().get(cId).getMessage()
+ assertTrue(response.getFailedRequests().size() == 1);
+ assertTrue(response.getSuccessfullyStartedContainers().size() == 0);
+ assertTrue(response.getFailedRequests().containsKey(cId));
+ assertTrue(response.getFailedRequests().get(cId).getMessage()
.contains("Null resource visibility for local resource"));
}
@@ -2264,16 +2261,16 @@ public void testGetLocalizationStatuses() throws Exception {
GetLocalizationStatusesResponse statusResponse =
containerManager.getLocalizationStatuses(statusRequest);
- Assert.assertEquals(1, statusResponse.getLocalizationStatuses()
+ assertEquals(1, statusResponse.getLocalizationStatuses()
.get(containerId).size());
LocalizationStatus status = statusResponse.getLocalizationStatuses()
.get(containerId).iterator().next();
- Assert.assertEquals("resource key", "dest_file1",
- status.getResourceKey());
- Assert.assertEquals("resource status", LocalizationState.COMPLETED,
- status.getLocalizationState());
+ assertEquals("dest_file1",
+ status.getResourceKey(), "resource key");
+ assertEquals(LocalizationState.COMPLETED,
+ status.getLocalizationState(), "resource status");
- Assert.assertEquals(0, statusResponse.getFailedRequests().size());
+ assertEquals(0, statusResponse.getFailedRequests().size());
// stop containers
StopContainersRequest stopRequest =
@@ -2326,21 +2323,21 @@ public void testGetLocalizationStatusesMultiContainers() throws Exception {
GetLocalizationStatusesResponse statusResponse =
containerManager.getLocalizationStatuses(statusRequest);
- Assert.assertEquals(2, statusResponse.getLocalizationStatuses().size());
+ assertEquals(2, statusResponse.getLocalizationStatuses().size());
ContainerId[] containerIds = {container1, container2};
Arrays.stream(containerIds).forEach(cntnId -> {
List statuses = statusResponse
.getLocalizationStatuses().get(container1);
- Assert.assertEquals(1, statuses.size());
+ assertEquals(1, statuses.size());
LocalizationStatus status = statuses.get(0);
- Assert.assertEquals("resource key", "dest_file1",
- status.getResourceKey());
- Assert.assertEquals("resource status", LocalizationState.COMPLETED,
- status.getLocalizationState());
+ assertEquals("dest_file1",
+ status.getResourceKey(), "resource key");
+ assertEquals(LocalizationState.COMPLETED,
+ status.getLocalizationState(), "resource status");
});
- Assert.assertEquals(0, statusResponse.getFailedRequests().size());
+ assertEquals(0, statusResponse.getFailedRequests().size());
// stop containers
StopContainersRequest stopRequest =
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.java
index e8779ef0e85b7..c9d745533b372 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.java
@@ -19,11 +19,11 @@
package org.apache.hadoop.yarn.server.nodemanager.containermanager;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -117,9 +117,8 @@
import org.apache.hadoop.yarn.server.nodemanager.timelineservice.NMTimelinePublisher;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.util.timeline.TimelineUtils;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class TestContainerManagerRecovery extends BaseContainerManagerTest {
@@ -128,7 +127,7 @@ public TestContainerManagerRecovery() throws UnsupportedFileSystemException {
}
@Override
- @Before
+ @BeforeEach
public void setup() throws IOException {
localFS.delete(new Path(localDir.getAbsolutePath()), true);
localFS.delete(new Path(tmpDir.getAbsolutePath()), true);
@@ -600,14 +599,14 @@ public void testResourceMappingRecoveryForContainer() throws Exception {
app = context.getApplications().get(appId);
assertNotNull(app);
- Assert.assertNotNull(nmContainer);
+ assertNotNull(nmContainer);
ResourceMappings resourceMappings = nmContainer.getResourceMappings();
List assignedResource = resourceMappings
.getAssignedResources("gpu");
- Assert.assertTrue(assignedResource.equals(gpuResources));
- Assert.assertTrue(
+ assertTrue(assignedResource.equals(gpuResources));
+ assertTrue(
resourceMappings.getAssignedResources("numa").equals(numaResources));
- Assert.assertTrue(
+ assertTrue(
resourceMappings.getAssignedResources("fpga").equals(fpgaResources));
cm.stop();
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestNMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestNMProxy.java
index 3498ebe40da1b..c47ee4ec6c4c8 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestNMProxy.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestNMProxy.java
@@ -47,9 +47,12 @@
import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.hadoop.yarn.util.Records;
-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 static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
public class TestNMProxy extends BaseContainerManagerTest {
@@ -59,7 +62,7 @@ public TestNMProxy() throws UnsupportedFileSystemException {
int retryCount = 0;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
containerManager.start();
}
@@ -114,8 +117,9 @@ public GetContainerStatusesResponse getContainerStatuses(
};
}
- @Test(timeout = 20000)
- public void testNMProxyRetry() throws Exception {
+ @Test
+ @Timeout(value = 20)
+ public void testNMProxyRetry() throws Exception {
conf.setLong(YarnConfiguration.CLIENT_NM_CONNECT_MAX_WAIT_MS, 10000);
conf.setLong(YarnConfiguration.CLIENT_NM_CONNECT_RETRY_INTERVAL_MS, 100);
StartContainersRequest allRequests =
@@ -124,32 +128,36 @@ public void testNMProxyRetry() throws Exception {
ContainerManagementProtocol proxy = getNMProxy(conf);
proxy.startContainers(allRequests);
- Assert.assertEquals(5, retryCount);
+ assertEquals(5, retryCount);
retryCount = 0;
proxy.stopContainers(Records.newRecord(StopContainersRequest.class));
- Assert.assertEquals(5, retryCount);
+ assertEquals(5, retryCount);
retryCount = 0;
proxy.getContainerStatuses(Records
.newRecord(GetContainerStatusesRequest.class));
- Assert.assertEquals(5, retryCount);
+ assertEquals(5, retryCount);
}
- @Test(timeout = 20000, expected = IOException.class)
+ @Test
+ @Timeout(value = 20)
public void testShouldNotRetryForeverForNonNetworkExceptionsOnNMConnections()
throws Exception {
- conf.setLong(YarnConfiguration.CLIENT_NM_CONNECT_MAX_WAIT_MS, -1);
- StartContainersRequest allRequests =
- Records.newRecord(StartContainersRequest.class);
+ assertThrows(IOException.class, ()->{
+ conf.setLong(YarnConfiguration.CLIENT_NM_CONNECT_MAX_WAIT_MS, -1);
+ StartContainersRequest allRequests =
+ Records.newRecord(StartContainersRequest.class);
- ContainerManagementProtocol proxy = getNMProxy(conf);
+ ContainerManagementProtocol proxy = getNMProxy(conf);
- retryCount = 0;
- proxy.startContainers(allRequests);
+ retryCount = 0;
+ proxy.startContainers(allRequests);
+ });
}
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testNMProxyRPCRetry() throws Exception {
conf.setLong(YarnConfiguration.CLIENT_NM_CONNECT_MAX_WAIT_MS, 1000);
conf.setLong(YarnConfiguration.CLIENT_NM_CONNECT_RETRY_INTERVAL_MS, 100);
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/TestApplication.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/TestApplication.java
index e3907f8d25161..0063dfdbbd815 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/TestApplication.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/application/TestApplication.java
@@ -17,8 +17,17 @@
*/
package org.apache.hadoop.yarn.server.nodemanager.containermanager.application;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.argThat;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.refEq;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -64,8 +73,7 @@
import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
@@ -273,7 +281,7 @@ public void testAppFinishedOnRunningContainers() {
ContainerTokenIdentifier identifier =
wa.getContainerTokenIdentifier(container.getContainerId());
waitForContainerTokenToExpire(identifier);
- Assert.assertTrue(wa.context.getContainerTokenSecretManager()
+ assertTrue(wa.context.getContainerTokenSecretManager()
.isValidStartContainerRequest(identifier));
}
assertEquals(ApplicationState.FINISHED, wa.app.getApplicationState());
@@ -349,7 +357,7 @@ public void testAppFinishedOnCompletedContainers() {
ContainerTokenIdentifier identifier =
wa.getContainerTokenIdentifier(container.getContainerId());
waitForContainerTokenToExpire(identifier);
- Assert.assertTrue(wa.context.getContainerTokenSecretManager()
+ assertTrue(wa.context.getContainerTokenSecretManager()
.isValidStartContainerRequest(identifier));
}
assertEquals(ApplicationState.FINISHED, wa.app.getApplicationState());
@@ -602,7 +610,7 @@ private class WrappedApplication {
.put(identifier.getContainerID(), identifier);
context.getContainerTokenSecretManager().startContainerSuccessful(
identifier);
- Assert.assertFalse(context.getContainerTokenSecretManager()
+ assertFalse(context.getContainerTokenSecretManager()
.isValidStartContainerRequest(identifier));
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
index 3241cca27603c..c9165bbcaa341 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
@@ -17,10 +17,10 @@
*/
package org.apache.hadoop.yarn.server.nodemanager.containermanager.container;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.refEq;
@@ -107,8 +107,7 @@
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.util.ControlledClock;
import org.apache.hadoop.yarn.util.resource.Resources;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import org.mockito.Mockito;
@@ -358,17 +357,17 @@ public void testCleanupOnSuccess() throws Exception {
ContainerEventType e5 = wc.initStateToEvent.get(s5);
ContainerState s6 = wc.eventToFinalState.get(e5);
- Assert.assertEquals(ContainerState.LOCALIZING, s2);
- Assert.assertEquals(ContainerState.SCHEDULED, s3);
- Assert.assertEquals(ContainerState.RUNNING, s4);
- Assert.assertEquals(ContainerState.EXITED_WITH_SUCCESS, s5);
- Assert.assertEquals(ContainerState.DONE, s6);
+ assertEquals(ContainerState.LOCALIZING, s2);
+ assertEquals(ContainerState.SCHEDULED, s3);
+ assertEquals(ContainerState.RUNNING, s4);
+ assertEquals(ContainerState.EXITED_WITH_SUCCESS, s5);
+ assertEquals(ContainerState.DONE, s6);
- Assert.assertEquals(ContainerEventType.INIT_CONTAINER, e1);
- Assert.assertEquals(ContainerEventType.RESOURCE_LOCALIZED, e2);
- Assert.assertEquals(ContainerEventType.CONTAINER_LAUNCHED, e3);
- Assert.assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS, e4);
- Assert.assertEquals(ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, e5);
+ assertEquals(ContainerEventType.INIT_CONTAINER, e1);
+ assertEquals(ContainerEventType.RESOURCE_LOCALIZED, e2);
+ assertEquals(ContainerEventType.CONTAINER_LAUNCHED, e3);
+ assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS, e4);
+ assertEquals(ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, e5);
}
finally {
if (wc != null) {
@@ -586,14 +585,14 @@ public void testKillOnNew() throws Exception {
// check container metrics is generated.
ContainerMetrics containerMetrics =
ContainerMetrics.forContainer(wc.cId, 1, 5000);
- Assert.assertEquals(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER,
+ assertEquals(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER,
containerMetrics.exitCode.value());
- Assert.assertTrue(containerMetrics.startTime.value() > 0);
- Assert.assertTrue(containerMetrics.finishTime.value() >=
+ assertTrue(containerMetrics.startTime.value() > 0);
+ assertTrue(containerMetrics.finishTime.value() >=
containerMetrics.startTime.value());
- Assert.assertEquals(ContainerEventType.KILL_CONTAINER,
+ assertEquals(ContainerEventType.KILL_CONTAINER,
wc.initStateToEvent.get(ContainerState.NEW));
- Assert.assertEquals(ContainerState.DONE,
+ assertEquals(ContainerState.DONE,
wc.eventToFinalState.get(ContainerEventType.KILL_CONTAINER));
} finally {
if (wc != null) {
@@ -879,7 +878,7 @@ public void testResourceLocalizedOnLocalizationFailed() throws Exception {
assertEquals(ContainerState.LOCALIZATION_FAILED, wc.c.getContainerState());
assertNull(wc.c.getLocalizedResources());
verifyCleanupCall(wc);
- Assert.assertTrue(wc.getDiagnostics().contains(FAKE_LOCALIZATION_ERROR));
+ assertTrue(wc.getDiagnostics().contains(FAKE_LOCALIZATION_ERROR));
} finally {
if (wc != null) {
wc.finished();
@@ -1065,7 +1064,7 @@ private void testContainerRetry(ContainerRetryContext containerRetryContext,
break;
}
}
- Assert.assertEquals(expectedRetries, retryTimes);
+ assertEquals(expectedRetries, retryTimes);
} finally {
if (wc != null) {
wc.finished();
@@ -1097,7 +1096,7 @@ private void testContainerRestartInterval(
try {
wc = new WrappedContainer(25, 314159265358980L, 4345,
"yak", containerRetryContext);
- Assert.assertEquals(
+ assertEquals(
((ContainerImpl)wc.c).getContainerRetryContext().getRetryInterval(),
expectedRestartInterval);
} finally {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestResourceMappings.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestResourceMappings.java
index 5095fbc7ccc68..02cc63f44cc23 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestResourceMappings.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestResourceMappings.java
@@ -19,9 +19,8 @@
import org.apache.hadoop.thirdparty.com.google.common.collect.ImmutableList;
import org.apache.hadoop.yarn.server.nodemanager.api.deviceplugin.Device;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -29,12 +28,15 @@
import java.io.Serializable;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
public class TestResourceMappings {
private static final ResourceMappings.AssignedResources testResources =
new ResourceMappings.AssignedResources();
- @BeforeClass
+ @BeforeAll
public static void setup() {
testResources.updateAssignedResources(ImmutableList.of(
Device.Builder.newInstance()
@@ -64,12 +66,12 @@ public void testSerializeAssignedResourcesWithSerializationUtils() {
ResourceMappings.AssignedResources deserialized =
ResourceMappings.AssignedResources.fromBytes(serializedString);
- Assert.assertEquals(testResources.getAssignedResources(),
+ assertEquals(testResources.getAssignedResources(),
deserialized.getAssignedResources());
} catch (IOException e) {
e.printStackTrace();
- Assert.fail(String.format("Serialization of test AssignedResources " +
+ fail(String.format("Serialization of test AssignedResources " +
"failed with %s", e.getMessage()));
}
}
@@ -82,12 +84,12 @@ public void testAssignedResourcesCanDeserializePreviouslySerializedValues() {
ResourceMappings.AssignedResources deserialized =
ResourceMappings.AssignedResources.fromBytes(serializedString);
- Assert.assertEquals(testResources.getAssignedResources(),
+ assertEquals(testResources.getAssignedResources(),
deserialized.getAssignedResources());
} catch (IOException e) {
e.printStackTrace();
- Assert.fail(String.format("Deserialization of test AssignedResources " +
+ fail(String.format("Deserialization of test AssignedResources " +
"failed with %s", e.getMessage()));
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestSlidingWindowRetryPolicy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestSlidingWindowRetryPolicy.java
index 2aa4605c540ef..8d71706c7a3f0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestSlidingWindowRetryPolicy.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestSlidingWindowRetryPolicy.java
@@ -21,9 +21,12 @@
import org.apache.hadoop.yarn.api.records.ContainerRetryContext;
import org.apache.hadoop.yarn.api.records.ContainerRetryPolicy;
import org.apache.hadoop.yarn.util.ControlledClock;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for {@link SlidingWindowRetryPolicy}.
@@ -33,7 +36,7 @@ public class TestSlidingWindowRetryPolicy {
private ControlledClock clock;
private SlidingWindowRetryPolicy retryPolicy;
- @Before
+ @BeforeEach
public void setup() {
clock = new ControlledClock();
retryPolicy = new SlidingWindowRetryPolicy(clock);
@@ -45,10 +48,9 @@ public void testNeverRetry() {
ContainerRetryContext.NEVER_RETRY_CONTEXT;
SlidingWindowRetryPolicy.RetryContext windowContext = new
SlidingWindowRetryPolicy.RetryContext(retryContext);
- Assert.assertFalse("never retry", retryPolicy.shouldRetry(windowContext,
- 12));
- Assert.assertEquals("remaining retries", 0,
- windowContext.getRemainingRetries());
+ assertFalse(retryPolicy.shouldRetry(windowContext,
+ 12), "never retry");
+ assertEquals(0, windowContext.getRemainingRetries(), "remaining retries");
}
@Test
@@ -58,11 +60,10 @@ public void testAlwaysRetry() {
0, 10);
SlidingWindowRetryPolicy.RetryContext windowContext = new
SlidingWindowRetryPolicy.RetryContext(retryContext);
- Assert.assertTrue("always retry", retryPolicy.shouldRetry(windowContext,
- 12));
- Assert.assertEquals("remaining retries",
- ContainerRetryContext.RETRY_FOREVER,
- windowContext.getRemainingRetries());
+ assertTrue(retryPolicy.shouldRetry(windowContext,
+ 12), "always retry");
+ assertEquals(ContainerRetryContext.RETRY_FOREVER,
+ windowContext.getRemainingRetries(), "remaining retries");
}
@Test
@@ -71,31 +72,31 @@ public void testFailuresValidityInterval() {
.newInstance(ContainerRetryPolicy.RETRY_ON_ALL_ERRORS, null, 1, 0, 10);
SlidingWindowRetryPolicy.RetryContext windowRetryContext =
new SlidingWindowRetryPolicy.RetryContext(retryContext);
- Assert.assertTrue("retry 1",
- retryPolicy.shouldRetry(windowRetryContext, 12));
+ assertTrue(
+ retryPolicy.shouldRetry(windowRetryContext, 12), "retry 1");
retryPolicy.updateRetryContext(windowRetryContext);
- Assert.assertEquals("remaining retries", 1,
- windowRetryContext.getRemainingRetries());
+ assertEquals(1,
+ windowRetryContext.getRemainingRetries(), "remaining retries");
clock.setTime(20);
- Assert.assertTrue("retry 2",
- retryPolicy.shouldRetry(windowRetryContext, 12));
+ assertTrue(
+ retryPolicy.shouldRetry(windowRetryContext, 12), "retry 2");
retryPolicy.updateRetryContext(windowRetryContext);
- Assert.assertEquals("remaining retries", 1,
- windowRetryContext.getRemainingRetries());
+ assertEquals(1,
+ windowRetryContext.getRemainingRetries(), "remaining retries");
clock.setTime(40);
- Assert.assertTrue("retry 3",
- retryPolicy.shouldRetry(windowRetryContext, 12));
+ assertTrue(
+ retryPolicy.shouldRetry(windowRetryContext, 12), "retry 3");
retryPolicy.updateRetryContext(windowRetryContext);
- Assert.assertEquals("remaining retries", 1,
- windowRetryContext.getRemainingRetries());
+ assertEquals(1,
+ windowRetryContext.getRemainingRetries(), "remaining retries");
clock.setTime(45);
- Assert.assertFalse("retry failed",
- retryPolicy.shouldRetry(windowRetryContext, 12));
+ assertFalse(
+ retryPolicy.shouldRetry(windowRetryContext, 12), "retry failed");
retryPolicy.updateRetryContext(windowRetryContext);
- Assert.assertEquals("remaining retries", 0,
- windowRetryContext.getRemainingRetries());
+ assertEquals(0,
+ windowRetryContext.getRemainingRetries(), "remaining retries");
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestDockerContainerDeletionTask.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestDockerContainerDeletionTask.java
index 738a1dd0f1285..76ce26fcdba15 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestDockerContainerDeletionTask.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestDockerContainerDeletionTask.java
@@ -18,10 +18,10 @@
import org.apache.hadoop.yarn.proto.YarnServerNodemanagerRecoveryProtos;
import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
@@ -36,7 +36,7 @@ public class TestDockerContainerDeletionTask {
private DeletionService deletionService;
private DockerContainerDeletionTask deletionTask;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
deletionService = mock(DeletionService.class);
deletionTask = new DockerContainerDeletionTask(ID, deletionService, USER,
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestFileDeletionTask.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestFileDeletionTask.java
index fd2e4fbb894a0..f6d475dd39efb 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestFileDeletionTask.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/deletion/task/TestFileDeletionTask.java
@@ -19,14 +19,14 @@
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.proto.YarnServerNodemanagerRecoveryProtos.DeletionServiceDeleteTaskProto;
import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
-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 java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
@@ -43,7 +43,7 @@ public class TestFileDeletionTask {
private DeletionService deletionService;
private FileDeletionTask deletionTask;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
deletionService = mock(DeletionService.class);
baseDirs.add(BASEDIR);
@@ -51,7 +51,7 @@ public void setUp() throws Exception {
baseDirs);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
baseDirs.clear();
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerCleanup.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerCleanup.java
index 17574df02b4fd..cc03fe5948829 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerCleanup.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerCleanup.java
@@ -31,9 +31,8 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
-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.mockito.ArgumentCaptor;
import org.mockito.Mockito;
@@ -41,6 +40,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.hadoop.yarn.conf.YarnConfiguration.NM_SLEEP_DELAY_BEFORE_SIGKILL_MS;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -56,7 +56,7 @@ public class TestContainerCleanup {
private ContainerLaunch launch;
private ContainerCleanup cleanup;
- @Before
+ @BeforeEach
public void setup() throws Exception {
conf = new YarnConfiguration();
conf.setLong(NM_SLEEP_DELAY_BEFORE_SIGKILL_MS, 60000);
@@ -103,8 +103,8 @@ public void testCleanup() throws Exception {
ArgumentCaptor.forClass(ContainerSignalContext.class);
verify(executor, Mockito.times(1)).signalContainer(captor.capture());
- Assert.assertEquals("signal", ContainerExecutor.Signal.TERM,
- captor.getValue().getSignal());
+ assertEquals(ContainerExecutor.Signal.TERM,
+ captor.getValue().getSignal(), "signal");
}
@Test
@@ -115,7 +115,7 @@ public void testFailedExitCleanup() throws Exception {
ArgumentCaptor.forClass(ContainerSignalContext.class);
verify(executor, Mockito.times(1)).signalContainer(captor.capture());
- Assert.assertEquals("signal", ContainerExecutor.Signal.TERM,
- captor.getValue().getSignal());
+ assertEquals(ContainerExecutor.Signal.TERM,
+ captor.getValue().getSignal(), "signal");
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java
index 7c4815ff94b6f..467381749c26e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java
@@ -21,10 +21,24 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.apache.hadoop.test.PlatformAssumptions.assumeWindows;
import static org.apache.hadoop.test.PlatformAssumptions.assumeNotWindows;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.anyLong;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import java.io.BufferedReader;
import java.io.DataOutputStream;
@@ -126,10 +140,9 @@
import org.apache.hadoop.yarn.util.LinuxResourceCalculatorPlugin;
import org.apache.hadoop.yarn.util.ResourceCalculatorPlugin;
import org.apache.hadoop.yarn.util.resource.Resources;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@@ -154,7 +167,7 @@ public TestContainerLaunch() throws UnsupportedFileSystemException {
super();
}
- @Before
+ @BeforeEach
public void setup() throws IOException {
conf.setClass(
YarnConfiguration.NM_MON_RESOURCE_CALCULATOR,
@@ -240,7 +253,8 @@ public void testSpecialCharSymlinks() throws IOException {
}
// test the diagnostics are generated
- @Test (timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testInvalidSymlinkDiagnostics() throws IOException {
File shellFile = null;
@@ -290,12 +304,12 @@ public void testInvalidSymlinkDiagnostics() throws IOException {
String diagnostics = null;
try {
shexc.execute();
- Assert.fail("Should catch exception");
+ fail("Should catch exception");
} catch(ExitCodeException e){
diagnostics = e.getMessage();
}
- Assert.assertNotNull(diagnostics);
- Assert.assertTrue(shexc.getExitCode() != 0);
+ assertNotNull(diagnostics);
+ assertTrue(shexc.getExitCode() != 0);
symLinkFile = new File(tmpDir, symLink);
}
finally {
@@ -315,7 +329,8 @@ public void testInvalidSymlinkDiagnostics() throws IOException {
}
}
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testWriteEnvExport() throws Exception {
// Valid only for unix
assumeNotWindows();
@@ -348,22 +363,23 @@ protected String getNMEnvVar(String varname) {
String shellContent =
new String(Files.readAllBytes(Paths.get(shellFile.getAbsolutePath())),
StandardCharsets.UTF_8);
- Assert.assertTrue(shellContent
+ assertTrue(shellContent
.contains("export HADOOP_COMMON_HOME=\"/opt/hadoopcommon\""));
// Whitelisted variable overridden by container
- Assert.assertTrue(shellContent.contains(
+ assertTrue(shellContent.contains(
"export HADOOP_MAPRED_HOME=\"/opt/hadoopbuild\""));
// Available in env but not in whitelist
- Assert.assertFalse(shellContent.contains("HADOOP_HDFS_HOME"));
+ assertFalse(shellContent.contains("HADOOP_HDFS_HOME"));
// Available in env and in whitelist
- Assert.assertTrue(shellContent.contains(
+ assertTrue(shellContent.contains(
"export HADOOP_YARN_HOME=${HADOOP_YARN_HOME:-\"nodemanager_yarn_home\"}"
));
fos.flush();
fos.close();
}
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testWriteEnvExportDocker() throws Exception {
// Valid only for unix
assumeNotWindows();
@@ -399,22 +415,23 @@ protected String getNMEnvVar(String varname) {
String shellContent =
new String(Files.readAllBytes(Paths.get(shellFile.getAbsolutePath())),
StandardCharsets.UTF_8);
- Assert.assertTrue(shellContent
+ assertTrue(shellContent
.contains("export HADOOP_COMMON_HOME=\"/opt/hadoopcommon\""));
// Whitelisted variable overridden by container
- Assert.assertTrue(shellContent.contains(
+ assertTrue(shellContent.contains(
"export HADOOP_MAPRED_HOME=\"/opt/hadoopbuild\""));
// Available in env but not in whitelist
- Assert.assertFalse(shellContent.contains("HADOOP_HDFS_HOME"));
+ assertFalse(shellContent.contains("HADOOP_HDFS_HOME"));
// Available in env and in whitelist
- Assert.assertTrue(shellContent.contains(
+ assertTrue(shellContent.contains(
"export HADOOP_YARN_HOME=${HADOOP_YARN_HOME:-\"nodemanager_yarn_home\"}"
));
fos.flush();
fos.close();
}
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testWriteEnvOrder() throws Exception {
// Valid only for unix
assumeNotWindows();
@@ -475,18 +492,18 @@ protected String getNMEnvVar(String varname) {
StandardCharsets.UTF_8);
// First make sure everything is there that's supposed to be
for (String envVar : env.keySet()) {
- Assert.assertTrue(shellContent.contains(envVar + "="));
+ assertTrue(shellContent.contains(envVar + "="));
}
// The whitelist vars should not have been added to env
// They should only be in the launch script
for (String wlVar : whitelistVars) {
- Assert.assertFalse(env.containsKey(wlVar));
- Assert.assertTrue(shellContent.contains(wlVar + "="));
+ assertFalse(env.containsKey(wlVar));
+ assertTrue(shellContent.contains(wlVar + "="));
}
// Non-whitelist nm vars should be in neither env nor in launch script
for (String nwlVar : nonWhiteListEnv) {
- Assert.assertFalse(env.containsKey(nwlVar));
- Assert.assertFalse(shellContent.contains(nwlVar + "="));
+ assertFalse(env.containsKey(nwlVar));
+ assertFalse(shellContent.contains(nwlVar + "="));
}
// Explicitly Set NM vars should be before user vars
for (String nmVar : trackedNmVars) {
@@ -494,7 +511,7 @@ protected String getNMEnvVar(String varname) {
// Need to skip nm vars and whitelist vars
if (!trackedNmVars.contains(userVar) &&
!whitelistVars.contains(userVar)) {
- Assert.assertTrue(shellContent.indexOf(nmVar + "=") <
+ assertTrue(shellContent.indexOf(nmVar + "=") <
shellContent.indexOf(userVar + "="));
}
}
@@ -502,13 +519,14 @@ protected String getNMEnvVar(String varname) {
// Whitelisted vars should be before explicitly set NM vars
for (String wlVar : whitelistVars) {
for (String nmVar : trackedNmVars) {
- Assert.assertTrue(shellContent.indexOf(wlVar + "=") <
+ assertTrue(shellContent.indexOf(wlVar + "=") <
shellContent.indexOf(nmVar + "="));
}
}
}
- @Test (timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testInvalidEnvSyntaxDiagnostics() throws IOException {
File shellFile = null;
@@ -544,17 +562,17 @@ public void testInvalidEnvSyntaxDiagnostics() throws IOException {
String diagnostics = null;
try {
shexc.execute();
- Assert.fail("Should catch exception");
+ fail("Should catch exception");
} catch(ExitCodeException e){
//Capture diagnostics from prelaunch.stderr
List error = Files.readAllLines(Paths.get(localLogDir.getAbsolutePath(), ContainerLaunch.CONTAINER_PRE_LAUNCH_STDERR),
StandardCharsets.UTF_8);
diagnostics = StringUtils.join("\n", error);
}
- Assert.assertTrue(diagnostics.contains(Shell.WINDOWS ?
+ assertTrue(diagnostics.contains(Shell.WINDOWS ?
"is not recognized as an internal or external command" :
"command not found"));
- Assert.assertTrue(shexc.getExitCode() != 0);
+ assertTrue(shexc.getExitCode() != 0);
}
finally {
// cleanup
@@ -565,7 +583,8 @@ public void testInvalidEnvSyntaxDiagnostics() throws IOException {
}
}
- @Test(timeout = 10000)
+ @Test
+ @Timeout(value = 10)
public void testEnvExpansion() throws IOException {
Path logPath = new Path("/nm/container/logs");
String input =
@@ -586,18 +605,19 @@ public void testEnvExpansion() throws IOException {
String expectedAddOpens = Shell.isJavaVersionAtLeast(17) ? additionalJdk17PlusOptions : "";
if (Shell.WINDOWS) {
- Assert.assertEquals("%HADOOP_HOME%/share/hadoop/common/*;"
+ assertEquals("%HADOOP_HOME%/share/hadoop/common/*;"
+ "%HADOOP_HOME%/share/hadoop/common/lib/*;"
+ "%HADOOP_LOG_HOME%/nm/container/logs" + " " + expectedAddOpens, res);
} else {
- Assert.assertEquals("$HADOOP_HOME/share/hadoop/common/*:"
+ assertEquals("$HADOOP_HOME/share/hadoop/common/*:"
+ "$HADOOP_HOME/share/hadoop/common/lib/*:"
+ "$HADOOP_LOG_HOME/nm/container/logs" + " " + expectedAddOpens, res);
}
System.out.println(res);
}
- @Test (timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testContainerLaunchStdoutAndStderrDiagnostics() throws IOException {
File shellFile = null;
@@ -631,15 +651,15 @@ public void testContainerLaunchStdoutAndStderrDiagnostics() throws IOException {
String diagnostics = null;
try {
shexc.execute();
- Assert.fail("Should catch exception");
+ fail("Should catch exception");
} catch(ExitCodeException e){
diagnostics = e.getMessage();
}
// test stderr
- Assert.assertTrue(diagnostics.contains("error"));
+ assertTrue(diagnostics.contains("error"));
// test stdout
- Assert.assertTrue(shexc.getOutput().contains("hello"));
- Assert.assertTrue(shexc.getExitCode() == 2);
+ assertTrue(shexc.getOutput().contains("hello"));
+ assertTrue(shexc.getExitCode() == 2);
}
finally {
// cleanup
@@ -684,9 +704,9 @@ public void testPrependDistcache() throws Exception {
Dispatcher dispatcher = mock(Dispatcher.class);
EventHandler eventHandler = new EventHandler() {
public void handle(Event event) {
- Assert.assertTrue(event instanceof ContainerExitEvent);
+ assertTrue(event instanceof ContainerExitEvent);
ContainerExitEvent exitEvent = (ContainerExitEvent) event;
- Assert.assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
+ assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
exitEvent.getType());
}
};
@@ -719,9 +739,8 @@ public void handle(Event event) {
List result =
getJarManifestClasspath(userSetEnv.get(Environment.CLASSPATH.name()));
- Assert.assertTrue(result.size() > 1);
- Assert.assertTrue(
- result.get(result.size() - 1).endsWith("userjarlink.jar"));
+ assertTrue(result.size() > 1);
+ assertTrue(result.get(result.size() - 1).endsWith("userjarlink.jar"));
//Then, with user classpath first
userSetEnv.put(Environment.CLASSPATH_PREPEND_DISTCACHE.name(), "true");
@@ -738,9 +757,8 @@ public void handle(Event event) {
result =
getJarManifestClasspath(userSetEnv.get(Environment.CLASSPATH.name()));
- Assert.assertTrue(result.size() > 1);
- Assert.assertTrue(
- result.get(0).endsWith("userjarlink.jar"));
+ assertTrue(result.size() > 1);
+ assertTrue(result.get(0).endsWith("userjarlink.jar"));
}
@@ -778,9 +796,9 @@ public void testSanitizeNMEnvVars() throws Exception {
Dispatcher dispatcher = mock(Dispatcher.class);
EventHandler eventHandler = new EventHandler() {
public void handle(Event event) {
- Assert.assertTrue(event instanceof ContainerExitEvent);
+ assertTrue(event instanceof ContainerExitEvent);
ContainerExitEvent exitEvent = (ContainerExitEvent) event;
- Assert.assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
+ assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
exitEvent.getType());
}
};
@@ -818,15 +836,15 @@ public void handle(Event event) {
launch.addConfigsToEnv(userSetEnv);
launch.sanitizeEnv(userSetEnv, pwd, appDirs, userLocalDirs, containerLogs,
resources, nmp, nmEnvTrack);
- Assert.assertTrue(userSetEnv.containsKey("MALLOC_ARENA_MAX"));
- Assert.assertTrue(userSetEnv.containsKey(testKey1));
- Assert.assertTrue(userSetEnv.containsKey(testKey2));
- Assert.assertTrue(userSetEnv.containsKey(testKey3));
- Assert.assertEquals(userMallocArenaMaxVal + File.pathSeparator
+ assertTrue(userSetEnv.containsKey("MALLOC_ARENA_MAX"));
+ assertTrue(userSetEnv.containsKey(testKey1));
+ assertTrue(userSetEnv.containsKey(testKey2));
+ assertTrue(userSetEnv.containsKey(testKey3));
+ assertEquals(userMallocArenaMaxVal + File.pathSeparator
+ mallocArenaMaxVal, userSetEnv.get("MALLOC_ARENA_MAX"));
- Assert.assertEquals(testVal1, userSetEnv.get(testKey1));
- Assert.assertEquals(testVal2, userSetEnv.get(testKey2));
- Assert.assertEquals(testVal3, userSetEnv.get(testKey3));
+ assertEquals(testVal1, userSetEnv.get(testKey1));
+ assertEquals(testVal2, userSetEnv.get(testKey2));
+ assertEquals(testVal3, userSetEnv.get(testKey3));
}
@Test
@@ -849,9 +867,9 @@ public void testNmForcePath() throws Exception {
Dispatcher dispatcher = mock(Dispatcher.class);
EventHandler eventHandler = new EventHandler() {
public void handle(Event event) {
- Assert.assertTrue(event instanceof ContainerExitEvent);
+ assertTrue(event instanceof ContainerExitEvent);
ContainerExitEvent exitEvent = (ContainerExitEvent) event;
- Assert.assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
+ assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
exitEvent.getType());
}
};
@@ -876,8 +894,8 @@ public void handle(Event event) {
launch.sanitizeEnv(userSetEnv, pwd, appDirs, userLocalDirs, containerLogs,
resources, nmp, nmEnvTrack);
- Assert.assertTrue(userSetEnv.containsKey(Environment.PATH.name()));
- Assert.assertEquals(forcePath + ":$PATH",
+ assertTrue(userSetEnv.containsKey(Environment.PATH.name()));
+ assertEquals(forcePath + ":$PATH",
userSetEnv.get(Environment.PATH.name()));
String userPath = "/usr/bin:/usr/local/bin";
@@ -889,8 +907,8 @@ public void handle(Event event) {
launch.sanitizeEnv(userSetEnv, pwd, appDirs, userLocalDirs, containerLogs,
resources, nmp, nmEnvTrack);
- Assert.assertTrue(userSetEnv.containsKey(Environment.PATH.name()));
- Assert.assertEquals(forcePath + ":" + userPath,
+ assertTrue(userSetEnv.containsKey(Environment.PATH.name()));
+ assertEquals(forcePath + ":" + userPath,
userSetEnv.get(Environment.PATH.name()));
}
@@ -994,8 +1012,8 @@ private void verifyTailErrorLogOnContainerExit(Configuration conf,
ContainerLaunch launch = new ContainerLaunch(context, conf, dispatcher,
exec, app, container, dirsHandler, containerManager);
launch.call();
- Assert.assertTrue("ContainerExitEvent should have occurred",
- eventHandler.isContainerExitEventOccurred());
+ assertTrue(eventHandler.isContainerExitEventOccurred(),
+ "ContainerExitEvent should have occurred");
}
private static class ContainerExitHandler implements EventHandler {
@@ -1015,22 +1033,19 @@ public void handle(Event event) {
if (event instanceof ContainerExitEvent) {
containerExitEventOccurred = true;
ContainerExitEvent exitEvent = (ContainerExitEvent) event;
- Assert.assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
+ assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
exitEvent.getType());
LOG.info("Diagnostic Info : " + exitEvent.getDiagnosticInfo());
if (testForMultiFile) {
- Assert.assertTrue("Should contain the Multi file information",
- exitEvent.getDiagnosticInfo().contains("Error files: "));
+ assertTrue(exitEvent.getDiagnosticInfo().contains("Error files: "),
+ "Should contain the Multi file information");
}
- Assert.assertTrue(
- "Should contain the error Log message with tail size info",
- exitEvent.getDiagnosticInfo()
- .contains("Last "
- + YarnConfiguration.DEFAULT_NM_CONTAINER_STDERR_BYTES
- + " bytes of"));
- Assert.assertTrue("Should contain contents of error Log",
- exitEvent.getDiagnosticInfo().contains(
- INVALID_JAVA_HOME + "/bin/java"));
+ assertTrue(exitEvent.getDiagnosticInfo().contains("Last "
+ + YarnConfiguration.DEFAULT_NM_CONTAINER_STDERR_BYTES
+ + " bytes of"), "Should contain the error Log message with tail size info");
+ assertTrue(exitEvent.getDiagnosticInfo()
+ .contains(INVALID_JAVA_HOME + "/bin/java"),
+ "Should contain contents of error Log");
}
}
}
@@ -1053,7 +1068,9 @@ private static List getJarManifestClasspath(String path)
* See if environment variable is forwarded using sanitizeEnv.
* @throws Exception
*/
- @Test (timeout = 60000)
+ @Test
+ @Timeout(value = 60)
+ @SuppressWarnings("checkstyle:methodlength")
public void testContainerEnvVariables() throws Exception {
containerManager.start();
@@ -1207,14 +1224,14 @@ public Boolean get() {
}
BufferedReader reader =
new BufferedReader(new FileReader(processFinalFile));
- Assert.assertEquals(cId.toString(), reader.readLine());
- Assert.assertEquals(context.getNodeId().getHost(), reader.readLine());
- Assert.assertEquals(String.valueOf(context.getNodeId().getPort()),
+ assertEquals(cId.toString(), reader.readLine());
+ assertEquals(context.getNodeId().getHost(), reader.readLine());
+ assertEquals(String.valueOf(context.getNodeId().getPort()),
reader.readLine());
- Assert.assertEquals(String.valueOf(HTTP_PORT), reader.readLine());
- Assert.assertEquals(StringUtils.join(",", appDirs), reader.readLine());
- Assert.assertEquals(user, reader.readLine());
- Assert.assertEquals(user, reader.readLine());
+ assertEquals(String.valueOf(HTTP_PORT), reader.readLine());
+ assertEquals(StringUtils.join(",", appDirs), reader.readLine());
+ assertEquals(user, reader.readLine());
+ assertEquals(user, reader.readLine());
String obtainedPWD = reader.readLine();
boolean found = false;
for (Path localDir : appDirs) {
@@ -1223,34 +1240,34 @@ public Boolean get() {
break;
}
}
- Assert.assertTrue("Wrong local-dir found : " + obtainedPWD, found);
- Assert.assertEquals(
+ assertTrue(found, "Wrong local-dir found : " + obtainedPWD);
+ assertEquals(
conf.get(
YarnConfiguration.NM_USER_HOME_DIR,
YarnConfiguration.DEFAULT_NM_USER_HOME_DIR),
reader.readLine());
- Assert.assertEquals(userConfDir, reader.readLine());
+ assertEquals(userConfDir, reader.readLine());
for (String serviceName : containerManager.getAuxServiceMetaData().keySet()) {
- Assert.assertEquals(
+ assertEquals(
containerManager.getAuxServiceMetaData().get(serviceName),
ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes())));
}
- Assert.assertEquals(cId.toString(), containerLaunchContext
+ assertEquals(cId.toString(), containerLaunchContext
.getEnvironment().get(Environment.CONTAINER_ID.name()));
- Assert.assertEquals(context.getNodeId().getHost(), containerLaunchContext
+ assertEquals(context.getNodeId().getHost(), containerLaunchContext
.getEnvironment().get(Environment.NM_HOST.name()));
- Assert.assertEquals(String.valueOf(context.getNodeId().getPort()),
+ assertEquals(String.valueOf(context.getNodeId().getPort()),
containerLaunchContext.getEnvironment().get(Environment.NM_PORT.name()));
- Assert.assertEquals(String.valueOf(HTTP_PORT), containerLaunchContext
+ assertEquals(String.valueOf(HTTP_PORT), containerLaunchContext
.getEnvironment().get(Environment.NM_HTTP_PORT.name()));
- Assert.assertEquals(StringUtils.join(",", appDirs), containerLaunchContext
+ assertEquals(StringUtils.join(",", appDirs), containerLaunchContext
.getEnvironment().get(Environment.LOCAL_DIRS.name()));
- Assert.assertEquals(StringUtils.join(",", containerLogDirs),
+ assertEquals(StringUtils.join(",", containerLogDirs),
containerLaunchContext.getEnvironment().get(Environment.LOG_DIRS.name()));
- Assert.assertEquals(user, containerLaunchContext.getEnvironment()
+ assertEquals(user, containerLaunchContext.getEnvironment()
.get(Environment.USER.name()));
- Assert.assertEquals(user, containerLaunchContext.getEnvironment()
+ assertEquals(user, containerLaunchContext.getEnvironment()
.get(Environment.LOGNAME.name()));
found = false;
obtainedPWD =
@@ -1261,29 +1278,29 @@ public Boolean get() {
break;
}
}
- Assert.assertTrue("Wrong local-dir found : " + obtainedPWD, found);
- Assert.assertEquals(
+ assertTrue(found, "Wrong local-dir found : " + obtainedPWD);
+ assertEquals(
conf.get(
YarnConfiguration.NM_USER_HOME_DIR,
YarnConfiguration.DEFAULT_NM_USER_HOME_DIR),
containerLaunchContext.getEnvironment()
.get(Environment.HOME.name()));
- Assert.assertEquals(userConfDir, containerLaunchContext.getEnvironment()
+ assertEquals(userConfDir, containerLaunchContext.getEnvironment()
.get(Environment.HADOOP_CONF_DIR.name()));
// Get the pid of the process
String pid = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
// Now test the stop functionality.
// Assert that the process is alive
- Assert.assertTrue("Process is not alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is not alive!");
// Once more
- Assert.assertTrue("Process is not alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertTrue(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is not alive!");
// Now test the stop functionality.
List containerIds = new ArrayList();
@@ -1300,20 +1317,20 @@ public Boolean get() {
ContainerStatus containerStatus =
containerManager.getContainerStatuses(gcsRequest).getContainerStatuses().get(0);
int expectedExitCode = ContainerExitStatus.KILLED_BY_APPMASTER;
- Assert.assertEquals(expectedExitCode, containerStatus.getExitStatus());
+ assertEquals(expectedExitCode, containerStatus.getExitStatus());
// Assert that the process is not alive anymore
- Assert.assertFalse("Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pid), "Process is still alive!");
}
- @Test (timeout = 5000)
+ @Test
+ @Timeout(value = 5)
public void testAuxiliaryServiceHelper() throws Exception {
Map env = new HashMap();
String serviceName = "testAuxiliaryService";
ByteBuffer bb = ByteBuffer.wrap("testAuxiliaryService".getBytes());
AuxiliaryServiceHelper.setServiceDataIntoEnv(serviceName, bb, env);
- Assert.assertEquals(bb,
+ assertEquals(bb,
AuxiliaryServiceHelper.getServiceDataFromEnv(serviceName, env));
}
@@ -1392,13 +1409,12 @@ private void internalKillTest(boolean delayed) throws Exception {
Thread.sleep(1000);
LOG.info("Waiting for process start-file to be created");
}
- Assert.assertTrue("ProcessStartFile doesn't exist!",
- processStartFile.exists());
+ assertTrue(processStartFile.exists(), "ProcessStartFile doesn't exist!");
NMContainerStatus nmContainerStatus =
containerManager.getContext().getContainers().get(cId)
.getNMContainerStatus();
- Assert.assertEquals(priority, nmContainerStatus.getPriority());
+ assertEquals(priority, nmContainerStatus.getPriority());
// Now test the stop functionality.
List containerIds = new ArrayList();
@@ -1418,7 +1434,7 @@ private void internalKillTest(boolean delayed) throws Exception {
ContainerStatus containerStatus =
containerManager.getContainerStatuses(gcsRequest)
.getContainerStatuses().get(0);
- Assert.assertEquals(ContainerExitStatus.KILLED_BY_APPMASTER,
+ assertEquals(ContainerExitStatus.KILLED_BY_APPMASTER,
containerStatus.getExitStatus());
// Now verify the contents of the file. Script generates a message when it
@@ -1427,8 +1443,8 @@ private void internalKillTest(boolean delayed) throws Exception {
// There is no way for the process to trap and respond. Instead, we can
// verify that the job object with ID matching container ID no longer exists.
if (Shell.WINDOWS || !delayed) {
- Assert.assertFalse("Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(cId.toString()));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(cId.toString()),
+ "Process is still alive!");
} else {
BufferedReader reader =
new BufferedReader(new FileReader(processStartFile));
@@ -1444,23 +1460,26 @@ private void internalKillTest(boolean delayed) throws Exception {
break;
}
}
- Assert.assertTrue("Did not find sigterm message", foundSigTermMessage);
+ assertTrue(foundSigTermMessage, "Did not find sigterm message");
reader.close();
}
}
- @Test (timeout = 30000)
+ @Test
+ @Timeout(value = 30)
public void testDelayedKill() throws Exception {
internalKillTest(true);
}
- @Test (timeout = 30000)
+ @Test
+ @Timeout(value = 30)
public void testImmediateKill() throws Exception {
internalKillTest(false);
}
@SuppressWarnings("rawtypes")
- @Test (timeout = 10000)
+ @Test
+ @Timeout(value = 10)
public void testCallFailureWithNullLocalizedResources() {
Container container = mock(Container.class);
when(container.getContainerId()).thenReturn(ContainerId.newContainerId(
@@ -1474,9 +1493,9 @@ public void testCallFailureWithNullLocalizedResources() {
EventHandler eventHandler = new EventHandler() {
@Override
public void handle(Event event) {
- Assert.assertTrue(event instanceof ContainerExitEvent);
+ assertTrue(event instanceof ContainerExitEvent);
ContainerExitEvent exitEvent = (ContainerExitEvent) event;
- Assert.assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
+ assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
exitEvent.getType());
}
};
@@ -1505,7 +1524,8 @@ protected Token createContainerToken(ContainerId cId, Priority priority,
* Test that script exists with non-zero exit code when command fails.
* @throws IOException
*/
- @Test (timeout = 10000)
+ @Test
+ @Timeout(value = 10)
public void testShellScriptBuilderNonZeroExitCode() throws IOException {
ShellScriptBuilder builder = ShellScriptBuilder.create();
builder.command(Arrays.asList(new String[] {"unknownCommand"}));
@@ -1534,7 +1554,8 @@ public void testShellScriptBuilderNonZeroExitCode() throws IOException {
private static final String expectedMessage = "The command line has a length of";
- @Test (timeout = 10000)
+ @Test
+ @Timeout(value = 10)
public void testWindowsShellScriptBuilderCommand() throws IOException {
String callCmd = "@call ";
@@ -1584,7 +1605,8 @@ public void testWindowsShellScriptBuilderCommand() throws IOException {
}
}
- @Test (timeout = 10000)
+ @Test
+ @Timeout(value = 10)
public void testWindowsShellScriptBuilderEnv() throws IOException {
// Test is only relevant on Windows
assumeWindows();
@@ -1607,7 +1629,8 @@ public void testWindowsShellScriptBuilderEnv() throws IOException {
}
}
- @Test (timeout = 10000)
+ @Test
+ @Timeout(value = 10)
public void testWindowsShellScriptBuilderMkdir() throws IOException {
String mkDirCmd = "@if not exist \"\" mkdir \"\"";
@@ -1632,7 +1655,8 @@ public void testWindowsShellScriptBuilderMkdir() throws IOException {
}
}
- @Test (timeout = 10000)
+ @Test
+ @Timeout(value = 10)
public void testWindowsShellScriptBuilderLink() throws IOException {
// Test is only relevant on Windows
assumeWindows();
@@ -1665,7 +1689,7 @@ public void testWindowsShellScriptBuilderLink() throws IOException {
@Test
public void testKillProcessGroup() throws Exception {
- Assume.assumeTrue(Shell.isSetsidAvailable);
+ assumeTrue(Shell.isSetsidAvailable);
containerManager.start();
// Construct the Container-id
@@ -1732,15 +1756,15 @@ public void testKillProcessGroup() throws Exception {
Thread.sleep(1000);
LOG.info("Waiting for process start-file to be created");
}
- Assert.assertTrue("ProcessStartFile doesn't exist!",
- processStartFile.exists());
+ assertTrue(processStartFile.exists(),
+ "ProcessStartFile doesn't exist!");
BufferedReader reader =
new BufferedReader(new FileReader(processStartFile));
// Get the pid of the process
String pid = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
reader.close();
reader =
@@ -1748,7 +1772,7 @@ public void testKillProcessGroup() throws Exception {
// Get the pid of the child process
String child = reader.readLine().trim();
// No more lines
- Assert.assertEquals(null, reader.readLine());
+ assertEquals(null, reader.readLine());
reader.close();
LOG.info("Manually killing pid " + pid + ", but not child pid " + child);
@@ -1757,8 +1781,8 @@ public void testKillProcessGroup() throws Exception {
BaseContainerManagerTest.waitForContainerState(containerManager, cId,
ContainerState.COMPLETE);
- Assert.assertFalse("Process is still alive!",
- DefaultContainerExecutor.containerIsAlive(pid));
+ assertFalse(DefaultContainerExecutor.containerIsAlive(pid),
+ "Process is still alive!");
List containerIds = new ArrayList();
containerIds.add(cId);
@@ -1769,7 +1793,7 @@ public void testKillProcessGroup() throws Exception {
ContainerStatus containerStatus =
containerManager.getContainerStatuses(gcsRequest)
.getContainerStatuses().get(0);
- Assert.assertEquals(ExitCode.FORCE_KILLED.getExitCode(),
+ assertEquals(ExitCode.FORCE_KILLED.getExitCode(),
containerStatus.getExitStatus());
}
@@ -1825,15 +1849,13 @@ public void testDebuggingInformation() throws IOException {
new File(localLogDir, ContainerExecutor.DIRECTORY_CONTENTS);
File scriptCopy = new File(localLogDir, tempFile.getName());
- Assert.assertEquals("Directory info file missing", debugLogsExist,
- directorInfo.exists());
- Assert.assertEquals("Copy of launch script missing", debugLogsExist,
- scriptCopy.exists());
+ assertEquals(debugLogsExist, directorInfo.exists(), "Directory info file missing");
+ assertEquals(debugLogsExist,
+ scriptCopy.exists(), "Copy of launch script missing");
if (debugLogsExist) {
- Assert.assertTrue("Directory info file size is 0",
- directorInfo.length() > 0);
- Assert.assertTrue("Size of copy of launch script is 0",
- scriptCopy.length() > 0);
+ assertTrue(directorInfo.length() > 0, "Directory info file size is 0");
+ assertTrue(scriptCopy.length() > 0,
+ "Size of copy of launch script is 0");
}
}
} finally {
@@ -1889,10 +1911,8 @@ public void testDebuggingInformationOnError() throws IOException {
File directorInfo =
new File(localLogDir, ContainerExecutor.DIRECTORY_CONTENTS);
File scriptCopy = new File(localLogDir, tempFile.getName());
- Assert.assertFalse("Directory info file missing",
- directorInfo.exists());
- Assert.assertFalse("Copy of launch script missing",
- scriptCopy.exists());
+ assertFalse(directorInfo.exists(), "Directory info file missing");
+ assertFalse(scriptCopy.exists(), "Copy of launch script missing");
} finally {
// cleanup
if (shellFile != null && shellFile.exists()) {
@@ -1995,17 +2015,17 @@ public void testShellScriptBuilderStdOutandErrRedirection() throws IOException {
// expected
System.out.println("Received an expected exception: " + e.getMessage());
- Assert.assertEquals(true, stdout.exists());
+ assertEquals(true, stdout.exists());
BufferedReader stdoutReader = new BufferedReader(new FileReader(stdout));
// Get the pid of the process
String line = stdoutReader.readLine().trim();
- Assert.assertEquals(TEST_STDOUT_ECHO, line);
+ assertEquals(TEST_STDOUT_ECHO, line);
// No more lines
- Assert.assertEquals(null, stdoutReader.readLine());
+ assertEquals(null, stdoutReader.readLine());
stdoutReader.close();
- Assert.assertEquals(true, stderr.exists());
- Assert.assertTrue(stderr.length() > 0);
+ assertEquals(true, stderr.exists());
+ assertTrue(stderr.length() > 0);
}
}
finally {
@@ -2051,8 +2071,8 @@ public void testShellScriptBuilderWithNoRedirection() throws IOException {
// expected
System.out.println("Received an expected exception: " + e.getMessage());
- Assert.assertEquals(false, stdout.exists());
- Assert.assertEquals(false, stderr.exists());
+ assertEquals(false, stdout.exists());
+ assertEquals(false, stderr.exists());
}
} finally {
FileUtil.fullyDelete(shellFile);
@@ -2113,9 +2133,9 @@ private void validateShellExecutorForDifferentEnvs(Map env)
new String[] { shellFile.getAbsolutePath() }, tmpDir, cmdEnv);
try {
shexc.execute();
- Assert.fail("Should catch exception");
+ fail("Should catch exception");
} catch (ExitCodeException e) {
- Assert.assertTrue(shexc.getExitCode() != 0);
+ assertTrue(shexc.getExitCode() != 0);
}
} finally {
// cleanup
@@ -2161,9 +2181,9 @@ public void testValidEnvVariableSubstitution() throws IOException {
try {
shexc.execute();
} catch(ExitCodeException e){
- Assert.fail("Should not catch exception");
+ fail("Should not catch exception");
}
- Assert.assertTrue(shexc.getExitCode() == 0);
+ assertTrue(shexc.getExitCode() == 0);
}
finally {
// cleanup
@@ -2182,32 +2202,28 @@ private static void assertOrderEnvByDependencies(
copy.putAll(env);
Map ordered = sb.orderEnvByDependencies(env);
// 1st, check that env and copy are the same
- Assert.assertEquals(
- "Input env map has been altered because its size changed",
- copy.size(), env.size()
- );
+ assertEquals(copy.size(), env.size(),
+ "Input env map has been altered because its size changed");
final Iterator> ai = env.entrySet().iterator();
for (Map.Entry e : copy.entrySet()) {
Map.Entry a = ai.next();
- Assert.assertTrue(
- "Keys have been reordered in input env map",
+ assertTrue(
// env must not be altered at all, so we don't use String.equals
// copy and env must use the same String refs
- e.getKey() == a.getKey()
+ e.getKey() == a.getKey(), "Keys have been reordered in input env map"
);
- Assert.assertTrue(
- "Key "+e.getKey()+" does not longer points to its "
- +"original value have been reordered in input env map",
+ assertTrue(
// env must be altered at all, so we don't use String.equals
// copy and env must use the same String refs
- e.getValue() == a.getValue()
+ e.getValue() == a.getValue(), "Key "+e.getKey()+" does not longer points to its "
+ +"original value have been reordered in input env map"
);
}
// 2nd, check the ordered version as the expected ordering
// and did not altered values
- Assert.assertEquals(
+ assertEquals(env.size(), ordered.size(),
"Input env map and ordered env map must have the same size, env="+env+
- ", ordered="+ordered, env.size(), ordered.size()
+ ", ordered="+ordered
);
int iA = -1;
int iB = -1;
@@ -2233,7 +2249,7 @@ private static void assertOrderEnvByDependencies(
} else if ("cyclic_C".equals(e.getKey())) {
icC = i++;
} else {
- Assert.fail("Test need to ne fixed, got an unexpected env entry "+
+ fail("Test need to ne fixed, got an unexpected env entry "+
e.getKey());
}
}
@@ -2241,31 +2257,31 @@ private static void assertOrderEnvByDependencies(
// B depends on A, C depends on B so there are assertion on B>A and C>B
// but there is no assertion about C>A because B might be missing in some
// broken envs
- Assert.assertTrue("when reordering "+env+" into "+ordered+
- ", B should be after A", iA<0 || iB<0 || iA=0 ||
- icA<0 || icB<0 || icB=0 ||
- icB<0 || icC<0 || icC=0 ||
- icC<0 || icA<0 || icA=0 ||
+ icA<0 || icB<0 || icB=0 ||
+ icB<0 || icC<0 || icC=0 ||
+ icC<0 || icA<0 || icA asSet(String...str) {
@@ -2274,7 +2290,8 @@ private Set asSet(String...str) {
return set;
}
- @Test(timeout = 5000)
+ @Test
+ @Timeout(value = 5)
public void testOrderEnvByDependencies() {
final Map> fakeDeps = new HashMap<>();
fakeDeps.put("Aval", Collections.emptySet()); // A has no dependencies
@@ -2312,19 +2329,17 @@ public void testOrderEnvByDependencies() {
};
try {
- Assert.assertNull("Ordering a null env map must return a null value.",
- sb.orderEnvByDependencies(null));
+ assertNull(sb.orderEnvByDependencies(null),
+ "Ordering a null env map must return a null value.");
} catch (Exception e) {
- Assert.fail("null value is to be supported");
+ fail("null value is to be supported");
}
try {
- Assert.assertEquals(
- "Ordering an empty env map must return an empty map.",
- 0, sb.orderEnvByDependencies(Collections.emptyMap()).size()
- );
+ assertEquals(0, sb.orderEnvByDependencies(Collections.emptyMap()).size(),
+ "Ordering an empty env map must return an empty map.");
} catch (Exception e) {
- Assert.fail("Empty map is to be supported");
+ fail("Empty map is to be supported");
}
final Map combination = new LinkedHashMap<>();
@@ -2442,20 +2457,22 @@ public void testDistributedCacheDirs() throws Exception {
verify(mockExecutor, times(1)).launchContainer(ctxCaptor.capture());
ContainerStartContext ctx = ctxCaptor.getValue();
- Assert.assertEquals(StringUtils.join(",",
+ assertEquals(StringUtils.join(",",
launch.getNMFilecacheDirs(localDirsForRead)),
StringUtils.join(",", ctx.getFilecacheDirs()));
- Assert.assertEquals(StringUtils.join(",",
+ assertEquals(StringUtils.join(",",
launch.getUserFilecacheDirs(localDirsForRead)),
StringUtils.join(",", ctx.getUserFilecacheDirs()));
}
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testFilesAndEnvWithoutHTTPS() throws Exception {
testFilesAndEnv(false);
}
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testFilesAndEnvWithHTTPS() throws Exception {
testFilesAndEnv(true);
}
@@ -2529,27 +2546,27 @@ public Void answer(InvocationOnMock invocation) throws Throwable {
Path nmPrivate = dirsHandler.getLocalPathForWrite(
ResourceLocalizationService.NM_PRIVATE_DIR + Path.SEPARATOR +
appId.toString() + Path.SEPARATOR + id.toString());
- Assert.assertEquals(new Path(nmPrivate, ContainerLaunch.CONTAINER_SCRIPT),
+ assertEquals(new Path(nmPrivate, ContainerLaunch.CONTAINER_SCRIPT),
csc.getNmPrivateContainerScriptPath());
- Assert.assertEquals(new Path(nmPrivate,
+ assertEquals(new Path(nmPrivate,
String.format(ContainerExecutor.TOKEN_FILE_NAME_FMT,
id.toString())), csc.getNmPrivateTokensPath());
- Assert.assertEquals("script",
+ assertEquals("script",
readStringFromPath(csc.getNmPrivateContainerScriptPath()));
- Assert.assertEquals("credentials",
+ assertEquals("credentials",
readStringFromPath(csc.getNmPrivateTokensPath()));
if (https) {
- Assert.assertEquals(new Path(nmPrivate, ContainerLaunch.KEYSTORE_FILE),
+ assertEquals(new Path(nmPrivate, ContainerLaunch.KEYSTORE_FILE),
csc.getNmPrivateKeystorePath());
- Assert.assertEquals(new Path(nmPrivate, ContainerLaunch.TRUSTSTORE_FILE),
+ assertEquals(new Path(nmPrivate, ContainerLaunch.TRUSTSTORE_FILE),
csc.getNmPrivateTruststorePath());
- Assert.assertEquals("keystore",
+ assertEquals("keystore",
readStringFromPath(csc.getNmPrivateKeystorePath()));
- Assert.assertEquals("truststore",
+ assertEquals("truststore",
readStringFromPath(csc.getNmPrivateTruststorePath()));
} else {
- Assert.assertNull(csc.getNmPrivateKeystorePath());
- Assert.assertNull(csc.getNmPrivateTruststorePath());
+ assertNull(csc.getNmPrivateKeystorePath());
+ assertNull(csc.getNmPrivateTruststorePath());
}
// verify env
@@ -2562,25 +2579,25 @@ public Void answer(InvocationOnMock invocation) throws Throwable {
Path.SEPARATOR + ContainerLocalizer.APPCACHE + Path.SEPARATOR +
app.getAppId().toString() + Path.SEPARATOR +
container.getContainerId().toString());
- Assert.assertEquals(new Path(workDir,
+ assertEquals(new Path(workDir,
ContainerLaunch.FINAL_CONTAINER_TOKENS_FILE).toUri().getPath(),
env.get(ApplicationConstants.CONTAINER_TOKEN_FILE_ENV_NAME));
if (https) {
- Assert.assertEquals(new Path(workDir,
+ assertEquals(new Path(workDir,
ContainerLaunch.KEYSTORE_FILE).toUri().getPath(),
env.get(ApplicationConstants.KEYSTORE_FILE_LOCATION_ENV_NAME));
- Assert.assertEquals("keystore_password",
+ assertEquals("keystore_password",
env.get(ApplicationConstants.KEYSTORE_PASSWORD_ENV_NAME));
- Assert.assertEquals(new Path(workDir,
+ assertEquals(new Path(workDir,
ContainerLaunch.TRUSTSTORE_FILE).toUri().getPath(),
env.get(ApplicationConstants.TRUSTSTORE_FILE_LOCATION_ENV_NAME));
- Assert.assertEquals("truststore_password",
+ assertEquals("truststore_password",
env.get(ApplicationConstants.TRUSTSTORE_PASSWORD_ENV_NAME));
} else {
- Assert.assertNull(env.get("KEYSTORE_FILE_LOCATION"));
- Assert.assertNull(env.get("KEYSTORE_PASSWORD"));
- Assert.assertNull(env.get("TRUSTSTORE_FILE_LOCATION"));
- Assert.assertNull(env.get("TRUSTSTORE_PASSWORD"));
+ assertNull(env.get("KEYSTORE_FILE_LOCATION"));
+ assertNull(env.get("KEYSTORE_PASSWORD"));
+ assertNull(env.get("TRUSTSTORE_FILE_LOCATION"));
+ assertNull(env.get("TRUSTSTORE_PASSWORD"));
}
}
@@ -2592,7 +2609,8 @@ private String readStringFromPath(Path p) throws IOException {
}
}
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testExpandNmAdmEnv() throws Exception {
// setup mocks
Dispatcher dispatcher = mock(Dispatcher.class);
@@ -2668,7 +2686,7 @@ public Void answer(InvocationOnMock invocation) throws Throwable {
ArgumentCaptor.forClass(ContainerStartContext.class);
verify(containerExecutor, times(1)).launchContainer(cscArgument.capture());
ContainerStartContext csc = cscArgument.getValue();
- Assert.assertEquals("script",
+ assertEquals("script",
readStringFromPath(csc.getNmPrivateContainerScriptPath()));
// verify env
@@ -2676,9 +2694,9 @@ public Void answer(InvocationOnMock invocation) throws Throwable {
verify(containerExecutor, times(1)).writeLaunchEnv(any(),
envArgument.capture(), any(), any(), any(), any(), any());
Map env = envArgument.getValue();
- Assert.assertEquals(userVarVal, env.get(userVar));
- Assert.assertEquals(testVal1Expanded, env.get(testKey1));
- Assert.assertEquals(testVal2Expanded, env.get(testKey2));
+ assertEquals(userVarVal, env.get(userVar));
+ assertEquals(testVal1Expanded, env.get(testKey1));
+ assertEquals(testVal2Expanded, env.get(testKey2));
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunchParameterized.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunchParameterized.java
index a36d5efc2c3bb..dba9c1ca57ae0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunchParameterized.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunchParameterized.java
@@ -20,7 +20,6 @@
import org.apache.hadoop.util.Sets;
import org.apache.hadoop.util.Shell;
-import org.junit.Assert;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@@ -28,6 +27,8 @@
import java.util.Set;
import java.util.stream.Stream;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public class TestContainerLaunchParameterized {
private static Stream inputForGetEnvDependenciesLinux() {
return Stream.of(
@@ -104,8 +105,8 @@ void testGetEnvDependenciesLinux(String input,
Set expected) {
ContainerLaunch.ShellScriptBuilder bash =
ContainerLaunch.ShellScriptBuilder.create(Shell.OSType.OS_TYPE_LINUX);
- Assert.assertEquals("Failed to parse " + input, expected,
- bash.getEnvDependencies(input));
+ assertEquals(expected,
+ bash.getEnvDependencies(input), "Failed to parse " + input);
}
private static Stream inputForGetEnvDependenciesWin() {
@@ -141,8 +142,8 @@ void testGetEnvDependenciesWin(String input,
Set expected) {
ContainerLaunch.ShellScriptBuilder win =
ContainerLaunch.ShellScriptBuilder.create(Shell.OSType.OS_TYPE_WIN);
- Assert.assertEquals("Failed to parse " + input, expected,
- win.getEnvDependencies(input));
+ assertEquals(expected,
+ win.getEnvDependencies(input), "Failed to parse " + input);
}
private static Set asSet(String... str) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerRelaunch.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerRelaunch.java
index 9ff926c2cf682..08466f3de5b29 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerRelaunch.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerRelaunch.java
@@ -34,12 +34,12 @@
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerStartContext;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
import org.apache.hadoop.yarn.server.security.AMSecretKeys;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;
@@ -98,32 +98,32 @@ private void testRelaunchContext(boolean https) throws Exception {
ContainerRelaunch cr = new ContainerRelaunch(mockContext, conf, dispatcher,
mockExecutor, mockApp, mockContainer, mockDirsHandler, null);
int result = cr.call();
- assertEquals("relaunch failed", 0, result);
+ assertEquals(0, result, "relaunch failed");
ArgumentCaptor captor =
ArgumentCaptor.forClass(ContainerStartContext.class);
verify(mockExecutor).relaunchContainer(captor.capture());
ContainerStartContext csc = captor.getValue();
- assertNotNull("app ID null", csc.getAppId());
- assertNotNull("container null", csc.getContainer());
- assertNotNull("container local dirs null", csc.getContainerLocalDirs());
- assertNotNull("container log dirs null", csc.getContainerLogDirs());
- assertNotNull("work dir null", csc.getContainerWorkDir());
- assertNotNull("filecache dirs null", csc.getFilecacheDirs());
- assertNotNull("local dirs null", csc.getLocalDirs());
- assertNotNull("localized resources null", csc.getLocalizedResources());
- assertNotNull("log dirs null", csc.getLogDirs());
- assertNotNull("script path null", csc.getNmPrivateContainerScriptPath());
- assertNotNull("tokens path null", csc.getNmPrivateTokensPath());
+ assertNotNull(csc.getAppId(), "app ID null");
+ assertNotNull(csc.getContainer(), "container null");
+ assertNotNull(csc.getContainerLocalDirs(), "container local dirs null");
+ assertNotNull(csc.getContainerLogDirs(), "container log dirs null");
+ assertNotNull(csc.getContainerWorkDir(), "work dir null");
+ assertNotNull(csc.getFilecacheDirs(), "filecache dirs null");
+ assertNotNull(csc.getLocalDirs(), "local dirs null");
+ assertNotNull(csc.getLocalizedResources(), "localized resources null");
+ assertNotNull(csc.getLogDirs(), "log dirs null");
+ assertNotNull(csc.getNmPrivateContainerScriptPath(), "script path null");
+ assertNotNull(csc.getNmPrivateTokensPath(), "tokens path null");
if (https) {
- assertNotNull("keystore path null", csc.getNmPrivateKeystorePath());
- assertNotNull("truststore path null", csc.getNmPrivateTruststorePath());
+ assertNotNull(csc.getNmPrivateKeystorePath(), "keystore path null");
+ assertNotNull(csc.getNmPrivateTruststorePath(), "truststore path null");
} else {
- assertNull("keystore path not null", csc.getNmPrivateKeystorePath());
- assertNull("truststore path not null", csc.getNmPrivateTruststorePath());
+ assertNull(csc.getNmPrivateKeystorePath(), "keystore path not null");
+ assertNull(csc.getNmPrivateTruststorePath(), "truststore path not null");
}
- assertNotNull("user null", csc.getUser());
- assertNotNull("user local dirs null", csc.getUserLocalDirs());
- assertNotNull("user filecache dirs null", csc.getUserFilecacheDirs());
- assertNotNull("application local dirs null", csc.getApplicationLocalDirs());
+ assertNotNull(csc.getUser(), "user null");
+ assertNotNull(csc.getUserLocalDirs(), "user local dirs null");
+ assertNotNull(csc.getUserFilecacheDirs(), "user filecache dirs null");
+ assertNotNull(csc.getApplicationLocalDirs(), "application local dirs null");
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainersLauncher.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainersLauncher.java
index d1b1650731727..c720ad7ad4d1e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainersLauncher.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainersLauncher.java
@@ -30,9 +30,8 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationImpl;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl;
-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.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
@@ -45,8 +44,15 @@
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
/**
* Tests to verify all the Container's Launcher Events in
@@ -98,7 +104,7 @@ public class TestContainersLauncher {
private ContainersLauncher spy;
- @Before
+ @BeforeEach
public void setup() throws IllegalArgumentException, IllegalAccessException {
MockitoAnnotations.initMocks(this);
ContainersLauncher tempContainersLauncher = new ContainersLauncher(
@@ -206,8 +212,7 @@ public void testCleanupContainerForReINITEvent()
return null;
}).when(spy).cleanup(any(), any(), anyBoolean());
spy.handle(event);
- Assert.assertEquals("container not cleaned", containerId,
- cleanedContainers.get(0));
+ assertEquals(containerId, cleanedContainers.get(0), "container not cleaned");
}
@Test
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java
index 0823801f7f612..9e5747afbc473 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/privileged/TestPrivilegedOperationExecutor.java
@@ -22,9 +22,8 @@
import org.apache.hadoop.conf.Configuration;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,6 +32,9 @@
import java.util.Arrays;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
+
public class TestPrivilegedOperationExecutor {
private static final Logger LOG =
LoggerFactory.getLogger(TestPrivilegedOperationExecutor.class);
@@ -54,7 +56,7 @@ public class TestPrivilegedOperationExecutor {
private PrivilegedOperation opTasks2;
private PrivilegedOperation opTasks3;
- @Before
+ @BeforeEach
public void setup() {
localDataDir = System.getProperty("test.build.data");
customExecutorPath = localDataDir + "/bin/container-executor";
@@ -100,17 +102,17 @@ public void testExecutorPath() {
: new File("").getAbsolutePath();
String expectedPath = yarnHome + "/bin/container-executor";
- Assert.assertEquals(expectedPath, containerExePath);
+ assertEquals(expectedPath, containerExePath);
containerExePath = PrivilegedOperationExecutor
.getContainerExecutorExecutablePath(emptyConf);
- Assert.assertEquals(expectedPath, containerExePath);
+ assertEquals(expectedPath, containerExePath);
//if NM_LINUX_CONTAINER_EXECUTOR_PATH is set, this must be returned
expectedPath = customExecutorPath;
containerExePath = PrivilegedOperationExecutor
.getContainerExecutorExecutablePath(confWithExecutorPath);
- Assert.assertEquals(expectedPath, containerExePath);
+ assertEquals(expectedPath, containerExePath);
}
@Test
@@ -123,9 +125,9 @@ public void testExecutionCommand() {
//No arguments added - so the resulting array should consist of
//1)full path to executor 2) cli switch
- Assert.assertEquals(2, cmdArray.length);
- Assert.assertEquals(customExecutorPath, cmdArray[0]);
- Assert.assertEquals(op.getOperationType().getOption(), cmdArray[1]);
+ assertEquals(2, cmdArray.length);
+ assertEquals(customExecutorPath, cmdArray[0]);
+ assertEquals(op.getOperationType().getOption(), cmdArray[1]);
//other (dummy) arguments to tc modify state
String[] additionalArgs = { "cmd_file_1", "cmd_file_2", "cmd_file_3"};
@@ -136,13 +138,13 @@ public void testExecutionCommand() {
//Resulting array should be of length 2 greater than the number of
//additional arguments added.
- Assert.assertEquals(2 + additionalArgs.length, cmdArray.length);
- Assert.assertEquals(customExecutorPath, cmdArray[0]);
- Assert.assertEquals(op.getOperationType().getOption(), cmdArray[1]);
+ assertEquals(2 + additionalArgs.length, cmdArray.length);
+ assertEquals(customExecutorPath, cmdArray[0]);
+ assertEquals(op.getOperationType().getOption(), cmdArray[1]);
//Rest of args should be same as additional args.
for (int i = 0; i < additionalArgs.length; ++i) {
- Assert.assertEquals(additionalArgs[i], cmdArray[2 + i]);
+ assertEquals(additionalArgs[i], cmdArray[2 + i]);
}
//Now test prefix commands
@@ -151,23 +153,23 @@ public void testExecutionCommand() {
int prefixLength = prefixCommands.size();
//Resulting array should be of length of prefix command args + 2 (exec
// path + switch) + length of additional args.
- Assert.assertEquals(prefixLength + 2 + additionalArgs.length,
+ assertEquals(prefixLength + 2 + additionalArgs.length,
cmdArray.length);
//Prefix command array comes first
for (int i = 0; i < prefixLength; ++i) {
- Assert.assertEquals(prefixCommands.get(i), cmdArray[i]);
+ assertEquals(prefixCommands.get(i), cmdArray[i]);
}
//Followed by the container executor path and the cli switch
- Assert.assertEquals(customExecutorPath, cmdArray[prefixLength]);
- Assert.assertEquals(op.getOperationType().getOption(),
+ assertEquals(customExecutorPath, cmdArray[prefixLength]);
+ assertEquals(op.getOperationType().getOption(),
cmdArray[prefixLength + 1]);
//Followed by the rest of the args
//Rest of args should be same as additional args.
for (int i = 0; i < additionalArgs.length; ++i) {
- Assert.assertEquals(additionalArgs[i], cmdArray[prefixLength + 2 + i]);
+ assertEquals(additionalArgs[i], cmdArray[prefixLength + 2 + i]);
}
}
@@ -181,7 +183,7 @@ public void testSquashCGroupOperationsWithInvalidOperations() {
try {
PrivilegedOperationExecutor.squashCGroupOperations(ops);
- Assert.fail("Expected squash operation to fail with an exception!");
+ fail("Expected squash operation to fail with an exception!");
} catch (PrivilegedOperationException e) {
LOG.info("Caught expected exception : " + e);
}
@@ -193,7 +195,7 @@ public void testSquashCGroupOperationsWithInvalidOperations() {
try {
PrivilegedOperationExecutor.squashCGroupOperations(ops);
- Assert.fail("Expected squash operation to fail with an exception!");
+ fail("Expected squash operation to fail with an exception!");
} catch (PrivilegedOperationException e) {
LOG.info("Caught expected exception : " + e);
}
@@ -222,12 +224,12 @@ public void testSquashCGroupOperationsWithValidOperations() {
.append(cGroupTasks3).toString();
//We expect axactly one argument
- Assert.assertEquals(1, op.getArguments().size());
+ assertEquals(1, op.getArguments().size());
//Squashed list of tasks files
- Assert.assertEquals(expected, op.getArguments().get(0));
+ assertEquals(expected, op.getArguments().get(0));
} catch (PrivilegedOperationException e) {
LOG.info("Caught unexpected exception : " + e);
- Assert.fail("Caught unexpected exception: " + e);
+ fail("Caught unexpected exception: " + e);
}
}
}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupElasticMemoryController.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupElasticMemoryController.java
index 71b392f2d329e..0d2b903e7d441 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupElasticMemoryController.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupElasticMemoryController.java
@@ -23,14 +23,16 @@
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
@@ -53,17 +55,19 @@ public class TestCGroupElasticMemoryController {
* Test that at least one memory type is requested.
* @throws YarnException on exception
*/
- @Test(expected = YarnException.class)
+ @Test
public void testConstructorOff()
throws YarnException {
- new CGroupElasticMemoryController(
- conf,
- null,
- null,
- false,
- false,
- 10000
- );
+ assertThrows(YarnException.class, () -> {
+ new CGroupElasticMemoryController(
+ conf,
+ null,
+ null,
+ false,
+ false,
+ 10000
+ );
+ });
}
/**
@@ -91,15 +95,15 @@ public void testConstructorHandler()
* Test that the handler is notified about multiple OOM events.
* @throws Exception on exception
*/
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testMultipleOOMEvents() throws Exception {
conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH,
script.getAbsolutePath());
try {
FileUtils.writeStringToFile(script,
"#!/bin/bash\nprintf oomevent;printf oomevent;\n", StandardCharsets.UTF_8, false);
- assertTrue("Could not set executable",
- script.setExecutable(true));
+ assertTrue(script.setExecutable(true), "Could not set executable");
CGroupsHandler cgroups = mock(CGroupsHandler.class);
when(cgroups.getPathForCGroup(any(), any())).thenReturn("");
@@ -122,8 +126,9 @@ public void testMultipleOOMEvents() throws Exception {
controller.run();
verify(handler, times(2)).run();
} finally {
- assertTrue(String.format("Could not clean up script %s",
- script.getAbsolutePath()), script.delete());
+ assertTrue(script.delete(),
+ String.format("Could not clean up script %s",
+ script.getAbsolutePath()));
}
}
@@ -132,15 +137,15 @@ public void testMultipleOOMEvents() throws Exception {
* the child process starts
* @throws Exception one exception
*/
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testStopBeforeStart() throws Exception {
conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH,
script.getAbsolutePath());
try {
FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;printf oomevent;\n",
StandardCharsets.UTF_8, false);
- assertTrue("Could not set executable",
- script.setExecutable(true));
+ assertTrue(script.setExecutable(true), "Could not set executable");
CGroupsHandler cgroups = mock(CGroupsHandler.class);
when(cgroups.getPathForCGroup(any(), any())).thenReturn("");
@@ -164,8 +169,8 @@ public void testStopBeforeStart() throws Exception {
controller.run();
verify(handler, times(0)).run();
} finally {
- assertTrue(String.format("Could not clean up script %s",
- script.getAbsolutePath()), script.delete());
+ assertTrue(script.delete(), String.format("Could not clean up script %s",
+ script.getAbsolutePath()));
}
}
@@ -173,40 +178,42 @@ public void testStopBeforeStart() throws Exception {
* Test the edge case that OOM is never resolved.
* @throws Exception on exception
*/
- @Test(timeout = 20000, expected = YarnRuntimeException.class)
+ @Test
+ @Timeout(value = 20)
public void testInfiniteOOM() throws Exception {
- conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH,
- script.getAbsolutePath());
- Runnable handler = mock(Runnable.class);
- try {
- FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;sleep 1000;\n",
- StandardCharsets.UTF_8, false);
- assertTrue("Could not set executable",
- script.setExecutable(true));
+ assertThrows(YarnRuntimeException.class, () -> {
+ conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH,
+ script.getAbsolutePath());
+ Runnable handler = mock(Runnable.class);
+ try {
+ FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;sleep 1000;\n",
+ StandardCharsets.UTF_8, false);
+ assertTrue(script.setExecutable(true), "Could not set executable");
- CGroupsHandler cgroups = mock(CGroupsHandler.class);
- when(cgroups.getPathForCGroup(any(), any())).thenReturn("");
- when(cgroups.getCGroupParam(any(), any(), any()))
- .thenReturn("under_oom 1");
+ CGroupsHandler cgroups = mock(CGroupsHandler.class);
+ when(cgroups.getPathForCGroup(any(), any())).thenReturn("");
+ when(cgroups.getCGroupParam(any(), any(), any()))
+ .thenReturn("under_oom 1");
- doNothing().when(handler).run();
+ doNothing().when(handler).run();
- CGroupElasticMemoryController controller =
- new CGroupElasticMemoryController(
- conf,
- null,
- cgroups,
- true,
- false,
- 10000,
- handler
- );
- controller.run();
- } finally {
- verify(handler, times(1)).run();
- assertTrue(String.format("Could not clean up script %s",
- script.getAbsolutePath()), script.delete());
- }
+ CGroupElasticMemoryController controller =
+ new CGroupElasticMemoryController(
+ conf,
+ null,
+ cgroups,
+ true,
+ false,
+ 10000,
+ handler
+ );
+ controller.run();
+ } finally {
+ verify(handler, times(1)).run();
+ assertTrue(script.delete(), String.format("Could not clean up script %s",
+ script.getAbsolutePath()));
+ }
+ });
}
/**
@@ -214,40 +221,43 @@ public void testInfiniteOOM() throws Exception {
* containers.
* @throws Exception on exception
*/
- @Test(timeout = 20000, expected = YarnRuntimeException.class)
+ @Test
+ @Timeout(value = 20)
public void testNothingToKill() throws Exception {
- conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH,
- script.getAbsolutePath());
- Runnable handler = mock(Runnable.class);
- try {
- FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;sleep 1000;\n",
- StandardCharsets.UTF_8, false);
- assertTrue("Could not set executable",
- script.setExecutable(true));
+ assertThrows(YarnRuntimeException.class, () -> {
+ conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH,
+ script.getAbsolutePath());
+ Runnable handler = mock(Runnable.class);
+ try {
+ FileUtils.writeStringToFile(script, "#!/bin/bash\nprintf oomevent;sleep 1000;\n",
+ StandardCharsets.UTF_8, false);
+ assertTrue(
+ script.setExecutable(true), "Could not set executable");
- CGroupsHandler cgroups = mock(CGroupsHandler.class);
- when(cgroups.getPathForCGroup(any(), any())).thenReturn("");
- when(cgroups.getCGroupParam(any(), any(), any()))
- .thenReturn("under_oom 1");
+ CGroupsHandler cgroups = mock(CGroupsHandler.class);
+ when(cgroups.getPathForCGroup(any(), any())).thenReturn("");
+ when(cgroups.getCGroupParam(any(), any(), any()))
+ .thenReturn("under_oom 1");
- doThrow(new YarnRuntimeException("Expected")).when(handler).run();
+ doThrow(new YarnRuntimeException("Expected")).when(handler).run();
- CGroupElasticMemoryController controller =
- new CGroupElasticMemoryController(
- conf,
- null,
- cgroups,
- true,
- false,
- 10000,
- handler
- );
- controller.run();
- } finally {
- verify(handler, times(1)).run();
- assertTrue(String.format("Could not clean up script %s",
- script.getAbsolutePath()), script.delete());
- }
+ CGroupElasticMemoryController controller =
+ new CGroupElasticMemoryController(
+ conf,
+ null,
+ cgroups,
+ true,
+ false,
+ 10000,
+ handler
+ );
+ controller.run();
+ } finally {
+ verify(handler, times(1)).run();
+ assertTrue(script.delete(), String.format("Could not clean up script %s",
+ script.getAbsolutePath()));
+ }
+ });
}
/**
@@ -257,7 +267,8 @@ public void testNothingToKill() throws Exception {
* We do not use a script this time to avoid leaking the child process.
* @throws Exception exception occurred
*/
- @Test(timeout = 20000)
+ @Test
+ @Timeout(value = 20)
public void testNormalExit() throws Exception {
conf.set(YarnConfiguration.NM_ELASTIC_MEMORY_CONTROL_OOM_LISTENER_PATH,
"sleep");
@@ -287,7 +298,7 @@ public void testNormalExit() throws Exception {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
- assertTrue("Wait interrupted.", false);
+ assertTrue(false, "Wait interrupted.");
}
LOG.info(String.format("Calling process destroy in %d ms",
System.currentTimeMillis() - start));
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsBlkioResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsBlkioResourceHandlerImpl.java
index 65a5c667b68ad..975190bace70a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsBlkioResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsBlkioResourceHandlerImpl.java
@@ -23,16 +23,18 @@
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
-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.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
/**
* Tests for the cgroups disk handler implementation.
@@ -42,7 +44,7 @@ public class TestCGroupsBlkioResourceHandlerImpl {
private CGroupsHandler mockCGroupsHandler;
private CGroupsBlkioResourceHandlerImpl cGroupsBlkioResourceHandlerImpl;
- @Before
+ @BeforeEach
public void setup() {
mockCGroupsHandler = mock(CGroupsHandler.class);
cGroupsBlkioResourceHandlerImpl =
@@ -56,7 +58,7 @@ public void testBootstrap() throws Exception {
cGroupsBlkioResourceHandlerImpl.bootstrap(conf);
verify(mockCGroupsHandler, times(1)).initializeCGroupController(
CGroupsHandler.CGroupController.BLKIO);
- Assert.assertNull(ret);
+ assertNull(ret);
}
@Test
@@ -79,21 +81,21 @@ public void testPreStart() throws Exception {
CGroupsHandler.CGroupController.BLKIO, id,
CGroupsHandler.CGROUP_PARAM_WEIGHT,
CGroupsBlkioResourceHandlerImpl.DEFAULT_WEIGHT);
- Assert.assertNotNull(ret);
- Assert.assertEquals(1, ret.size());
+ assertNotNull(ret);
+ assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@Test
public void testReacquireContainer() throws Exception {
ContainerId containerIdMock = mock(ContainerId.class);
- Assert.assertNull(cGroupsBlkioResourceHandlerImpl
+ assertNull(cGroupsBlkioResourceHandlerImpl
.reacquireContainer(containerIdMock));
}
@@ -102,7 +104,7 @@ public void testPostComplete() throws Exception {
String id = "container_01_01";
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
- Assert.assertNull(cGroupsBlkioResourceHandlerImpl
+ assertNull(cGroupsBlkioResourceHandlerImpl
.postComplete(mockContainerId));
verify(mockCGroupsHandler, times(1)).deleteCGroup(
CGroupsHandler.CGroupController.BLKIO, id);
@@ -110,7 +112,7 @@ public void testPostComplete() throws Exception {
@Test
public void testTeardown() throws Exception {
- Assert.assertNull(cGroupsBlkioResourceHandlerImpl.teardown());
+ assertNull(cGroupsBlkioResourceHandlerImpl.teardown());
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsCpuResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsCpuResourceHandlerImpl.java
index 9fbf9f03d2bc2..0fee5fadf9293 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsCpuResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsCpuResourceHandlerImpl.java
@@ -28,17 +28,26 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.util.ResourceCalculatorPlugin;
-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.mockito.InOrder;
import org.mockito.Mockito;
import java.io.File;
import java.util.List;
-import static org.mockito.Mockito.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.anyString;
+import static org.mockito.Mockito.eq;
+import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class TestCGroupsCpuResourceHandlerImpl {
@@ -47,7 +56,7 @@ public class TestCGroupsCpuResourceHandlerImpl {
private ResourceCalculatorPlugin plugin;
final int numProcessors = 4;
- @Before
+ @BeforeEach
public void setup() {
mockCGroupsHandler = mock(CGroupsHandler.class);
when(mockCGroupsHandler.getPathForCGroup(any(), any())).thenReturn(".");
@@ -73,7 +82,7 @@ public void testBootstrap() throws Exception {
verify(mockCGroupsHandler, times(0))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_QUOTA_US, "");
- Assert.assertNull(ret);
+ assertNull(ret);
}
@Test
@@ -96,7 +105,7 @@ public void testBootstrapLimits() throws Exception {
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_QUOTA_US,
String.valueOf(CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US));
- Assert.assertNull(ret);
+ assertNull(ret);
}
@Test
@@ -117,7 +126,7 @@ public void testBootstrapExistingLimits() throws Exception {
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_QUOTA_US, "-1");
- Assert.assertNull(ret);
+ assertNull(ret);
} finally {
FileUtils.deleteQuietly(existingLimit);
}
@@ -152,14 +161,14 @@ public void testPreStart() throws Exception {
verify(mockCGroupsHandler, never())
.updateCGroupParam(eq(CGroupsHandler.CGroupController.CPU), eq(id),
eq(CGroupsHandler.CGROUP_CPU_QUOTA_US), anyString());
- Assert.assertNotNull(ret);
- Assert.assertEquals(1, ret.size());
+ assertNotNull(ret);
+ assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@@ -200,14 +209,14 @@ public void testPreStartStrictUsage() throws Exception {
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
CGroupsHandler.CGROUP_CPU_QUOTA_US, String.valueOf(
(int) (CGroupsCpuResourceHandlerImpl.MAX_QUOTA_US * share)));
- Assert.assertNotNull(ret);
- Assert.assertEquals(1, ret.size());
+ assertNotNull(ret);
+ assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@@ -277,7 +286,7 @@ public void testPreStartRestrictedContainers() throws Exception {
@Test
public void testReacquireContainer() throws Exception {
ContainerId containerIdMock = mock(ContainerId.class);
- Assert.assertNull(
+ assertNull(
cGroupsCpuResourceHandler.reacquireContainer(containerIdMock));
}
@@ -286,19 +295,19 @@ public void testPostComplete() throws Exception {
String id = "container_01_01";
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
- Assert.assertNull(cGroupsCpuResourceHandler.postComplete(mockContainerId));
+ assertNull(cGroupsCpuResourceHandler.postComplete(mockContainerId));
verify(mockCGroupsHandler, times(1))
.deleteCGroup(CGroupsHandler.CGroupController.CPU, id);
}
@Test
public void testTeardown() throws Exception {
- Assert.assertNull(cGroupsCpuResourceHandler.teardown());
+ assertNull(cGroupsCpuResourceHandler.teardown());
}
@Test
public void testStrictResourceUsage() throws Exception {
- Assert.assertNull(cGroupsCpuResourceHandler.teardown());
+ assertNull(cGroupsCpuResourceHandler.teardown());
}
@Test
@@ -318,7 +327,7 @@ public void testOpportunistic() throws Exception {
cGroupsCpuResourceHandler.preStart(container);
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, id,
- CGroupsHandler.CGROUP_CPU_SHARES, "2");
+ CGroupsHandler.CGROUP_CPU_SHARES, "2");
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerBase.java
index f3d57f0458394..ae2f8c08104c3 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerBase.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerBase.java
@@ -25,15 +25,15 @@
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.Permission;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
/**
@@ -46,7 +46,7 @@ public abstract class TestCGroupsHandlerBase {
protected CGroupsHandler.CGroupController controller;
protected String controllerPath;
- @Before
+ @BeforeEach
public void setup() {
privilegedOperationExecutorMock = mock(PrivilegedOperationExecutor.class);
@@ -64,7 +64,7 @@ public void setup() {
controllerPath = getControllerFilePath(controller.getName());
}
- @After
+ @AfterEach
public void teardown() {
FileUtil.fullyDelete(new File(tmpPath));
}
@@ -116,7 +116,7 @@ protected Configuration createNoMountConfiguration(String myHierarchy) {
*/
protected File createEmptyMtabFile() throws IOException {
File emptyMtab = new File(tmpPath, "mtab");
- assertTrue("New file should have been created", emptyMtab.createNewFile());
+ assertTrue(emptyMtab.createNewFile(), "New file should have been created");
return emptyMtab;
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerImpl.java
index a776b63405661..668877a74cc91 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsHandlerImpl.java
@@ -28,8 +28,7 @@
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.File;
@@ -43,9 +42,10 @@
import java.util.UUID;
import static org.apache.hadoop.test.MockitoUtil.verifyZeroInteractions;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@@ -82,13 +82,13 @@ public static File createPremountedCgroups(File parentDir, boolean cpuAcct)
+ " cgroup rw,relatime,cpu"
+ (cpuAcct ? ",cpuacct" :"")
+ " 0 0\n";
- assertTrue("Directory should be created", cpuCgroup.mkdirs());
+ assertTrue(cpuCgroup.mkdirs(), "Directory should be created");
File blkioCgroup = new File(parentDir, "blkio");
String blkioMtabContent =
"none " + blkioCgroup.getAbsolutePath()
+ " cgroup rw,relatime,blkio 0 0\n";
- assertTrue("Directory should be created", blkioCgroup.mkdirs());
+ assertTrue(blkioCgroup.mkdirs(), "Directory should be created");
File mockMtab = new File(parentDir, UUID.randomUUID().toString());
if (!mockMtab.exists()) {
@@ -111,7 +111,7 @@ public static File createPremountedCgroups(File parentDir, boolean cpuAcct)
public void testMountController() throws IOException {
File parentDir = new File(tmpPath);
File cgroup = new File(parentDir, controller.getName());
- assertTrue("cgroup dir should be cerated", cgroup.mkdirs());
+ assertTrue(cgroup.mkdirs(), "cgroup dir should be cerated");
//Since we enabled (deferred) cgroup controller mounting, no interactions
//should have occurred, with this mock
verifyZeroInteractions(privilegedOperationExecutorMock);
@@ -139,7 +139,7 @@ public void testMountController() throws IOException {
//we'll explicitly capture and assert that the
//captured op and the expected op are identical.
- Assert.assertEquals(expectedOp, opCaptor.getValue());
+ assertEquals(expectedOp, opCaptor.getValue());
verifyNoMoreInteractions(privilegedOperationExecutorMock);
//Try mounting the same controller again - this should be a no-op
@@ -166,8 +166,8 @@ public void testCGroupPaths() throws IOException {
// Let's manually create a path to (partially) simulate a controller mounted
// later in the test. This is required because the handler uses a mocked
// privileged operation executor
- assertTrue("Sample subsystem should be created",
- new File(controllerPath).mkdirs());
+ assertTrue(new File(controllerPath).mkdirs(),
+ "Sample subsystem should be created");
try {
cGroupsHandler = new CGroupsHandlerImpl(createMountConfiguration(),
@@ -182,18 +182,18 @@ public void testCGroupPaths() throws IOException {
String expectedPath =
controllerPath + Path.SEPARATOR + testCGroup;
String path = cGroupsHandler.getPathForCGroup(controller, testCGroup);
- Assert.assertEquals(expectedPath, path);
+ assertEquals(expectedPath, path);
String expectedPathTasks = expectedPath + Path.SEPARATOR
+ CGroupsHandler.CGROUP_PROCS_FILE;
path = cGroupsHandler.getPathForCGroupTasks(controller, testCGroup);
- Assert.assertEquals(expectedPathTasks, path);
+ assertEquals(expectedPathTasks, path);
String param = CGroupsHandler.CGROUP_PARAM_CLASSID;
String expectedPathParam = expectedPath + Path.SEPARATOR
+ controller.getName() + "." + param;
path = cGroupsHandler.getPathForCGroupParam(controller, testCGroup, param);
- Assert.assertEquals(expectedPathParam, path);
+ assertEquals(expectedPathParam, path);
}
@Test
@@ -207,8 +207,8 @@ public void testCGroupOperations() throws IOException {
// Lets manually create a path to (partially) simulate a controller mounted
// later in the test. This is required because the handler uses a mocked
// privileged operation executor
- assertTrue("Sample subsystem should be created",
- new File(controllerPath).mkdirs());
+ assertTrue(new File(controllerPath).mkdirs(),
+ "Sample subsystem should be created");
try {
cGroupsHandler = new CGroupsHandlerImpl(createMountConfiguration(),
@@ -216,9 +216,8 @@ public void testCGroupOperations() throws IOException {
cGroupsHandler.initializeCGroupController(controller);
} catch (ResourceHandlerException e) {
LOG.error("Caught exception: " + e);
- assertTrue(
- "Unexpected ResourceHandlerException when mounting controller!",
- false);
+ assertTrue(false,
+ "Unexpected ResourceHandlerException when mounting controller!");
}
String testCGroup = "container_01";
@@ -228,7 +227,7 @@ public void testCGroupOperations() throws IOException {
String path = cGroupsHandler.createCGroup(controller, testCGroup);
assertTrue(new File(expectedPath).exists());
- Assert.assertEquals(expectedPath, path);
+ assertEquals(expectedPath, path);
//update param and read param tests.
//We don't use net_cls.classid because as a test param here because
@@ -247,14 +246,14 @@ public void testCGroupOperations() throws IOException {
assertTrue(paramFile.exists());
try {
- Assert.assertEquals(paramValue, new String(Files.readAllBytes(
+ assertEquals(paramValue, new String(Files.readAllBytes(
paramFile.toPath())));
} catch (IOException e) {
LOG.error("Caught exception: " + e);
- Assert.fail("Unexpected IOException trying to read cgroup param!");
+ fail("Unexpected IOException trying to read cgroup param!");
}
- Assert.assertEquals(paramValue,
+ assertEquals(paramValue,
cGroupsHandler.getCGroupParam(controller, testCGroup, param));
//We can't really do a delete test here. Linux cgroups
@@ -267,8 +266,7 @@ public void testCGroupOperations() throws IOException {
//deletion is not possible with a regular non-empty directory.
} catch (ResourceHandlerException e) {
LOG.error("Caught exception: " + e);
- Assert
- .fail("Unexpected ResourceHandlerException during cgroup operations!");
+ fail("Unexpected ResourceHandlerException during cgroup operations!");
}
}
@@ -295,7 +293,7 @@ public void testMtabParsing() throws Exception {
newMtab);
// Verify
- Assert.assertEquals(2, controllerPaths.size());
+ assertEquals(2, controllerPaths.size());
assertTrue(controllerPaths
.containsKey(CGroupsHandler.CGroupController.CPU));
assertTrue(controllerPaths
@@ -303,8 +301,8 @@ public void testMtabParsing() throws Exception {
String cpuDir = controllerPaths.get(CGroupsHandler.CGroupController.CPU);
String blkioDir =
controllerPaths.get(CGroupsHandler.CGroupController.BLKIO);
- Assert.assertEquals(parentDir.getAbsolutePath() + "/cpu", cpuDir);
- Assert.assertEquals(parentDir.getAbsolutePath() + "/blkio", blkioDir);
+ assertEquals(parentDir.getAbsolutePath() + "/cpu", cpuDir);
+ assertEquals(parentDir.getAbsolutePath() + "/blkio", blkioDir);
}
/**
@@ -329,59 +327,58 @@ private void testPreMountedControllerInitialization(String myHierarchy)
""));
// Test that a missing yarn hierarchy will be created automatically
if (!cpuCgroupMountDir.equals(mountPoint)) {
- assertFalse("Directory should be deleted", cpuCgroupMountDir.exists());
+ assertFalse(cpuCgroupMountDir.exists(), "Directory should be deleted");
}
cGroupsHandler.initializeCGroupController(
CGroupsHandler.CGroupController.CPU);
- assertTrue("Cgroups not writable", cpuCgroupMountDir.exists() &&
- cpuCgroupMountDir.canWrite());
+ assertTrue(cpuCgroupMountDir.exists() &&
+ cpuCgroupMountDir.canWrite(), "Cgroups not writable");
// Test that an inaccessible yarn hierarchy results in an exception
assertTrue(cpuCgroupMountDir.setWritable(false));
try {
cGroupsHandler.initializeCGroupController(
CGroupsHandler.CGroupController.CPU);
- Assert.fail("An inaccessible path should result in an exception");
+ fail("An inaccessible path should result in an exception");
} catch (Exception e) {
- assertTrue("Unexpected exception " + e.getClass().toString(),
- e instanceof ResourceHandlerException);
+ assertTrue(e instanceof ResourceHandlerException,
+ "Unexpected exception " + e.getClass().toString());
} finally {
- assertTrue("Could not revert writable permission",
- cpuCgroupMountDir.setWritable(true));
+ assertTrue(cpuCgroupMountDir.setWritable(true),
+ "Could not revert writable permission");
}
// Test that a non-accessible mount directory results in an exception
if (!cpuCgroupMountDir.equals(mountPoint)) {
- assertTrue("Could not delete cgroups", cpuCgroupMountDir.delete());
- assertFalse("Directory should be deleted", cpuCgroupMountDir.exists());
+ assertTrue(cpuCgroupMountDir.delete(), "Could not delete cgroups");
+ assertFalse(cpuCgroupMountDir.exists(), "Directory should be deleted");
}
assertTrue(mountPoint.setWritable(false));
try {
cGroupsHandler.initializeCGroupController(
CGroupsHandler.CGroupController.CPU);
- Assert.fail("An inaccessible path should result in an exception");
+ fail("An inaccessible path should result in an exception");
} catch (Exception e) {
- assertTrue("Unexpected exception " + e.getClass().toString(),
- e instanceof ResourceHandlerException);
+ assertTrue(e instanceof ResourceHandlerException,
+ "Unexpected exception " + e.getClass().toString());
} finally {
- assertTrue("Could not revert writable permission",
- mountPoint.setWritable(true));
+ assertTrue(mountPoint.setWritable(true),
+ "Could not revert writable permission");
}
// Test that a SecurityException results in an exception
if (!cpuCgroupMountDir.equals(mountPoint)) {
- Assert.assertFalse("Could not delete cgroups",
- cpuCgroupMountDir.delete());
- assertFalse("Directory should be deleted", cpuCgroupMountDir.exists());
+ assertFalse(cpuCgroupMountDir.delete(), "Could not delete cgroups");
+ assertFalse(cpuCgroupMountDir.exists(), "Directory should be deleted");
SecurityManager manager = System.getSecurityManager();
System.setSecurityManager(new MockSecurityManagerDenyWrite());
try {
cGroupsHandler.initializeCGroupController(
CGroupsHandler.CGroupController.CPU);
- Assert.fail("An inaccessible path should result in an exception");
+ fail("An inaccessible path should result in an exception");
} catch (Exception e) {
- assertTrue("Unexpected exception " + e.getClass().toString(),
- e instanceof ResourceHandlerException);
+ assertTrue(e instanceof ResourceHandlerException,
+ "Unexpected exception " + e.getClass().toString());
} finally {
System.setSecurityManager(manager);
}
@@ -389,19 +386,18 @@ private void testPreMountedControllerInitialization(String myHierarchy)
// Test that a non-existing mount directory results in an exception
if (!cpuCgroupMountDir.equals(mountPoint)) {
- Assert.assertFalse("Could not delete cgroups",
- cpuCgroupMountDir.delete());
- assertFalse("Directory should be deleted", cpuCgroupMountDir.exists());
+ assertFalse(cpuCgroupMountDir.delete(), "Could not delete cgroups");
+ assertFalse(cpuCgroupMountDir.exists(), "Directory should be deleted");
}
FileUtils.deleteQuietly(mountPoint);
- assertFalse("cgroups mount point should be deleted", mountPoint.exists());
+ assertFalse(mountPoint.exists(), "cgroups mount point should be deleted");
try {
cGroupsHandler.initializeCGroupController(
CGroupsHandler.CGroupController.CPU);
- Assert.fail("An inaccessible path should result in an exception");
+ fail("An inaccessible path should result in an exception");
} catch (Exception e) {
- assertTrue("Unexpected exception " + e.getClass().toString(),
- e instanceof ResourceHandlerException);
+ assertTrue(e instanceof ResourceHandlerException,
+ "Unexpected exception " + e.getClass().toString());
}
}
@@ -416,9 +412,9 @@ public void testSelectCgroup() throws Exception {
privilegedOperationExecutorMock);
Map> cgroups = new LinkedHashMap<>();
- Assert.assertTrue("temp dir should be created", cpu.mkdirs());
- Assert.assertTrue("temp dir should be created", memory.mkdirs());
- Assert.assertFalse("temp dir should not be created", cpuNoExist.exists());
+ assertTrue(cpu.mkdirs(), "temp dir should be created");
+ assertTrue(memory.mkdirs(), "temp dir should be created");
+ assertFalse(cpuNoExist.exists(), "temp dir should not be created");
cgroups.put(
memory.getAbsolutePath(), Collections.singleton("memory"));
@@ -426,8 +422,8 @@ public void testSelectCgroup() throws Exception {
cpuNoExist.getAbsolutePath(), Collections.singleton("cpu"));
cgroups.put(cpu.getAbsolutePath(), Collections.singleton("cpu"));
String selectedCPU = handler.findControllerInMtab("cpu", cgroups);
- Assert.assertEquals("Wrong CPU mount point selected",
- cpu.getAbsolutePath(), selectedCPU);
+ assertEquals(cpu.getAbsolutePath(), selectedCPU,
+ "Wrong CPU mount point selected");
} finally {
FileUtils.deleteQuietly(cpu);
FileUtils.deleteQuietly(memory);
@@ -470,8 +466,8 @@ public void testRemount()
oldMountPoint, true);
File newMountPoint = new File(parentDir, newMountPointDir);
- assertTrue("Could not create dirs",
- new File(newMountPoint, "cpu").mkdirs());
+ assertTrue(new File(newMountPoint, "cpu").mkdirs(),
+ "Could not create dirs");
// Initialize YARN classes
Configuration confMount = createMountConfiguration();
@@ -489,7 +485,7 @@ public void testRemount()
.executePrivilegedOperation(opCaptor.capture(), eq(false));
File hierarchyFile =
new File(new File(newMountPoint, "cpu"), this.hierarchy);
- assertTrue("Yarn cgroup should exist", hierarchyFile.exists());
+ assertTrue(hierarchyFile.exists(), "Yarn cgroup should exist");
}
@@ -502,15 +498,16 @@ public void testManualCgroupSetting() throws ResourceHandlerException {
File cpu = new File(new File(tmpPath, "cpuacct,cpu"), "/hadoop-yarn");
try {
- Assert.assertTrue("temp dir should be created", cpu.mkdirs());
+ assertTrue(cpu.mkdirs(), "temp dir should be created");
CGroupsHandlerImpl cGroupsHandler = new CGroupsHandlerImpl(conf, null);
cGroupsHandler.initializeCGroupController(
CGroupsHandler.CGroupController.CPU);
- Assert.assertEquals("CPU CGRoup path was not set", cpu.getAbsolutePath(),
- new File(cGroupsHandler.getPathForCGroup(
- CGroupsHandler.CGroupController.CPU, "")).getAbsolutePath());
+ assertEquals(cpu.getAbsolutePath(),
+ new File(cGroupsHandler.getPathForCGroup(
+ CGroupsHandler.CGroupController.CPU, "")).getAbsolutePath(),
+ "CPU CGRoup path was not set");
} finally {
FileUtils.deleteQuietly(cpu);
@@ -526,32 +523,32 @@ public void testCgroupsHierarchySetting() throws ResourceHandlerException {
"/hadoop-yarn");
CGroupsHandlerImpl cGroupsHandler = new CGroupsHandlerImpl(conf, null);
String expectedRelativePath = "hadoop-yarn/c1";
- Assert.assertEquals(expectedRelativePath,
+ assertEquals(expectedRelativePath,
cGroupsHandler.getRelativePathForCGroup("c1"));
conf.set(YarnConfiguration.NM_LINUX_CONTAINER_CGROUPS_HIERARCHY,
"hadoop-yarn");
cGroupsHandler = new CGroupsHandlerImpl(conf, null);
- Assert.assertEquals(expectedRelativePath,
+ assertEquals(expectedRelativePath,
cGroupsHandler.getRelativePathForCGroup("c1"));
conf.set(YarnConfiguration.NM_LINUX_CONTAINER_CGROUPS_HIERARCHY,
"hadoop-yarn/");
cGroupsHandler = new CGroupsHandlerImpl(conf, null);
- Assert.assertEquals(expectedRelativePath,
+ assertEquals(expectedRelativePath,
cGroupsHandler.getRelativePathForCGroup("c1"));
conf.set(YarnConfiguration.NM_LINUX_CONTAINER_CGROUPS_HIERARCHY,
"//hadoop-yarn//");
cGroupsHandler = new CGroupsHandlerImpl(conf, null);
- Assert.assertEquals(expectedRelativePath,
+ assertEquals(expectedRelativePath,
cGroupsHandler.getRelativePathForCGroup("c1"));
expectedRelativePath = "hadoop-yarn/root/c1";
conf.set(YarnConfiguration.NM_LINUX_CONTAINER_CGROUPS_HIERARCHY,
"//hadoop-yarn/root//");
cGroupsHandler = new CGroupsHandlerImpl(conf, null);
- Assert.assertEquals(expectedRelativePath,
+ assertEquals(expectedRelativePath,
cGroupsHandler.getRelativePathForCGroup("c1"));
}
}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsMemoryResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsMemoryResourceHandlerImpl.java
index 0d001bc21f026..40576b6983232 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsMemoryResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsMemoryResourceHandlerImpl.java
@@ -26,12 +26,19 @@
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.Assert;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.mockito.Mockito.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
/**
* Unit test for CGroupsMemoryResourceHandlerImpl.
@@ -41,7 +48,7 @@ public class TestCGroupsMemoryResourceHandlerImpl {
private CGroupsHandler mockCGroupsHandler;
private CGroupsMemoryResourceHandlerImpl cGroupsMemoryResourceHandler;
- @Before
+ @BeforeEach
public void setup() {
mockCGroupsHandler = mock(CGroupsHandler.class);
when(mockCGroupsHandler.getPathForCGroup(any(), any())).thenReturn(".");
@@ -58,21 +65,21 @@ public void testBootstrap() throws Exception {
cGroupsMemoryResourceHandler.bootstrap(conf);
verify(mockCGroupsHandler, times(1))
.initializeCGroupController(CGroupsHandler.CGroupController.MEMORY);
- Assert.assertNull(ret);
- Assert.assertEquals("Default swappiness value incorrect", 0,
- cGroupsMemoryResourceHandler.getSwappiness());
+ assertNull(ret);
+ assertEquals(0, cGroupsMemoryResourceHandler.getSwappiness(),
+ "Default swappiness value incorrect");
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, true);
try {
cGroupsMemoryResourceHandler.bootstrap(conf);
} catch(ResourceHandlerException re) {
- Assert.fail("Pmem check should be allowed to run with cgroups");
+ fail("Pmem check should be allowed to run with cgroups");
}
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, true);
try {
cGroupsMemoryResourceHandler.bootstrap(conf);
} catch(ResourceHandlerException re) {
- Assert.fail("Vmem check should be allowed to run with cgroups");
+ fail("Vmem check should be allowed to run with cgroups");
}
}
@@ -84,22 +91,22 @@ public void testSwappinessValues() throws Exception {
conf.setInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, -1);
try {
cGroupsMemoryResourceHandler.bootstrap(conf);
- Assert.fail("Negative values for swappiness should not be allowed.");
+ fail("Negative values for swappiness should not be allowed.");
} catch (ResourceHandlerException re) {
// do nothing
}
try {
conf.setInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, 101);
cGroupsMemoryResourceHandler.bootstrap(conf);
- Assert.fail("Values greater than 100 for swappiness"
+ fail("Values greater than 100 for swappiness"
+ " should not be allowed.");
} catch (ResourceHandlerException re) {
// do nothing
}
conf.setInt(YarnConfiguration.NM_MEMORY_RESOURCE_CGROUPS_SWAPPINESS, 60);
cGroupsMemoryResourceHandler.bootstrap(conf);
- Assert.assertEquals("Swappiness value incorrect", 60,
- cGroupsMemoryResourceHandler.getSwappiness());
+ assertEquals(60, cGroupsMemoryResourceHandler.getSwappiness(),
+ "Swappiness value incorrect");
}
@Test
@@ -135,14 +142,14 @@ public void testPreStart() throws Exception {
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, String.valueOf(0));
- Assert.assertNotNull(ret);
- Assert.assertEquals(1, ret.size());
+ assertNotNull(ret);
+ assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@@ -180,21 +187,21 @@ public void testPreStartNonEnforced() throws Exception {
verify(mockCGroupsHandler, times(0))
.updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
CGroupsHandler.CGROUP_PARAM_MEMORY_SWAPPINESS, String.valueOf(0));
- Assert.assertNotNull(ret);
- Assert.assertEquals(1, ret.size());
+ assertNotNull(ret);
+ assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@Test
public void testReacquireContainer() throws Exception {
ContainerId containerIdMock = mock(ContainerId.class);
- Assert.assertNull(
+ assertNull(
cGroupsMemoryResourceHandler.reacquireContainer(containerIdMock));
}
@@ -203,15 +210,14 @@ public void testPostComplete() throws Exception {
String id = "container_01_01";
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
- Assert
- .assertNull(cGroupsMemoryResourceHandler.postComplete(mockContainerId));
+ assertNull(cGroupsMemoryResourceHandler.postComplete(mockContainerId));
verify(mockCGroupsHandler, times(1))
.deleteCGroup(CGroupsHandler.CGroupController.MEMORY, id);
}
@Test
public void testTeardown() throws Exception {
- Assert.assertNull(cGroupsMemoryResourceHandler.teardown());
+ assertNull(cGroupsMemoryResourceHandler.teardown());
}
@Test
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsResourceCalculator.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsResourceCalculator.java
index 6b02b296a8ff4..413c33f06e641 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsResourceCalculator.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsResourceCalculator.java
@@ -25,14 +25,14 @@
import java.util.Arrays;
import java.util.stream.Collectors;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.util.CpuTimeTracker;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -44,12 +44,12 @@ public class TestCGroupsResourceCalculator {
private Path root;
- @Before
+ @BeforeEach
public void before() throws IOException {
root = Files.createTempDirectory("TestCGroupsResourceCalculator");
}
- @After
+ @AfterEach
public void after() throws IOException {
FileUtils.deleteDirectory(root.toFile());
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2CpuResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2CpuResourceHandlerImpl.java
index 1d77d8adc62e4..bc2280909878f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2CpuResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2CpuResourceHandlerImpl.java
@@ -29,13 +29,15 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.util.ResourceCalculatorPlugin;
-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.mockito.Mockito;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -52,7 +54,7 @@ public class TestCGroupsV2CpuResourceHandlerImpl {
private ResourceCalculatorPlugin plugin;
final int numProcessors = 4;
- @Before
+ @BeforeEach
public void setup() {
mockCGroupsHandler = mock(CGroupsHandler.class);
when(mockCGroupsHandler.getPathForCGroup(any(), any())).thenReturn(".");
@@ -75,7 +77,7 @@ public void testBootstrap() throws Exception {
verify(mockCGroupsHandler, times(0))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_MAX, "");
- Assert.assertNull(ret);
+ assertNull(ret);
}
@Test
@@ -95,7 +97,7 @@ public void testBootstrapLimits() throws Exception {
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_MAX, cpuMaxValue);
- Assert.assertNull(ret);
+ assertNull(ret);
}
@Test
@@ -117,7 +119,7 @@ public void testBootstrapExistingLimits() throws Exception {
verify(mockCGroupsHandler, times(1))
.updateCGroupParam(CGroupsHandler.CGroupController.CPU, "",
CGroupsHandler.CGROUP_CPU_MAX, "max 100000");
- Assert.assertNull(ret);
+ assertNull(ret);
}
@Test
@@ -257,7 +259,7 @@ public void testPreStartRestrictedContainers() throws Exception {
@Test
public void testReacquireContainer() throws Exception {
ContainerId containerIdMock = mock(ContainerId.class);
- Assert.assertNull(
+ assertNull(
cGroupsCpuResourceHandler.reacquireContainer(containerIdMock));
}
@@ -266,14 +268,14 @@ public void testPostComplete() throws Exception {
String id = "container_01_01";
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
- Assert.assertNull(cGroupsCpuResourceHandler.postComplete(mockContainerId));
+ assertNull(cGroupsCpuResourceHandler.postComplete(mockContainerId));
verify(mockCGroupsHandler, times(1))
.deleteCGroup(CGroupsHandler.CGroupController.CPU, id);
}
@Test
public void testTeardown() throws Exception {
- Assert.assertNull(cGroupsCpuResourceHandler.teardown());
+ assertNull(cGroupsCpuResourceHandler.teardown());
}
@Test
@@ -300,14 +302,14 @@ public void testOpportunistic() throws Exception {
}
private void validatePrivilegedOperationList(List ops, String path) {
- Assert.assertNotNull(ops);
- Assert.assertEquals(1, ops.size());
+ assertNotNull(ops);
+ assertEquals(1, ops.size());
PrivilegedOperation op = ops.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2HandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2HandlerImpl.java
index d3667e917bf50..23ef0bcbc8231 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2HandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2HandlerImpl.java
@@ -24,8 +24,7 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -38,7 +37,9 @@
import java.util.UUID;
import static org.apache.hadoop.test.MockitoUtil.verifyZeroInteractions;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for the CGroups handler implementation.
@@ -75,8 +76,8 @@ public File createPremountedCgroups(File parentDir)
enabledControllers);
File subtreeControlFile = new File(parentDir, CGroupsHandler.CGROUP_SUBTREE_CONTROL_FILE);
- Assert.assertTrue("empty subtree_control file should be created",
- subtreeControlFile.createNewFile());
+ assertTrue(subtreeControlFile.createNewFile(),
+ "empty subtree_control file should be created");
File hierarchyDir = new File(parentDir, hierarchy);
if (!hierarchyDir.mkdirs()) {
@@ -98,8 +99,8 @@ public void testCGroupPaths() throws IOException, ResourceHandlerException {
verifyZeroInteractions(privilegedOperationExecutorMock);
File parentDir = new File(tmpPath);
File mtab = createPremountedCgroups(parentDir);
- assertTrue("Sample subsystem should be created",
- new File(controllerPath).exists());
+ assertTrue(new File(controllerPath).exists(),
+ "Sample subsystem should be created");
CGroupsHandler cGroupsHandler = new CGroupsV2HandlerImpl(createNoMountConfiguration(hierarchy),
privilegedOperationExecutorMock, mtab.getAbsolutePath());
@@ -109,34 +110,36 @@ public void testCGroupPaths() throws IOException, ResourceHandlerException {
String expectedPath =
controllerPath + Path.SEPARATOR + testCGroup;
String path = cGroupsHandler.getPathForCGroup(controller, testCGroup);
- Assert.assertEquals(expectedPath, path);
+ assertEquals(expectedPath, path);
String expectedPathTasks = expectedPath + Path.SEPARATOR
+ CGroupsHandler.CGROUP_PROCS_FILE;
path = cGroupsHandler.getPathForCGroupTasks(controller, testCGroup);
- Assert.assertEquals(expectedPathTasks, path);
+ assertEquals(expectedPathTasks, path);
String param = CGroupsHandler.CGROUP_PARAM_CLASSID;
String expectedPathParam = expectedPath + Path.SEPARATOR
+ controller.getName() + "." + param;
path = cGroupsHandler.getPathForCGroupParam(controller, testCGroup, param);
- Assert.assertEquals(expectedPathParam, path);
+ assertEquals(expectedPathParam, path);
}
- @Test(expected = UnsupportedOperationException.class)
+ @Test
public void testUnsupportedMountConfiguration() throws Exception {
- //As per junit behavior, we expect a new mock object to be available
- //in this test.
- verifyZeroInteractions(privilegedOperationExecutorMock);
- CGroupsHandler cGroupsHandler;
- File mtab = createEmptyMtabFile();
-
- assertTrue("Sample subsystem should be created",
- new File(controllerPath).mkdirs());
-
- cGroupsHandler = new CGroupsV2HandlerImpl(createMountConfiguration(),
- privilegedOperationExecutorMock, mtab.getAbsolutePath());
- cGroupsHandler.initializeCGroupController(controller);
+ assertThrows(UnsupportedOperationException.class, () -> {
+ //As per junit behavior, we expect a new mock object to be available
+ //in this test.
+ verifyZeroInteractions(privilegedOperationExecutorMock);
+ CGroupsHandler cGroupsHandler;
+ File mtab = createEmptyMtabFile();
+
+ assertTrue(new File(controllerPath).mkdirs(),
+ "Sample subsystem should be created");
+
+ cGroupsHandler = new CGroupsV2HandlerImpl(createMountConfiguration(),
+ privilegedOperationExecutorMock, mtab.getAbsolutePath());
+ cGroupsHandler.initializeCGroupController(controller);
+ });
}
@Test
@@ -144,8 +147,8 @@ public void testCGroupOperations() throws IOException, ResourceHandlerException
verifyZeroInteractions(privilegedOperationExecutorMock);
File parentDir = new File(tmpPath);
File mtab = createPremountedCgroups(parentDir);
- assertTrue("Sample subsystem should be created",
- new File(controllerPath).exists());
+ assertTrue(new File(controllerPath).exists(),
+ "Sample subsystem should be created");
CGroupsHandler cGroupsHandler = new CGroupsV2HandlerImpl(createNoMountConfiguration(hierarchy),
privilegedOperationExecutorMock, mtab.getAbsolutePath());
@@ -157,7 +160,7 @@ public void testCGroupOperations() throws IOException, ResourceHandlerException
String path = cGroupsHandler.createCGroup(controller, testCGroup);
assertTrue(new File(expectedPath).exists());
- Assert.assertEquals(expectedPath, path);
+ assertEquals(expectedPath, path);
String param = "test_param";
String paramValue = "test_param_value";
@@ -169,9 +172,9 @@ public void testCGroupOperations() throws IOException, ResourceHandlerException
File paramFile = new File(paramPath);
assertTrue(paramFile.exists());
- Assert.assertEquals(paramValue, new String(Files.readAllBytes(
+ assertEquals(paramValue, new String(Files.readAllBytes(
paramFile.toPath())));
- Assert.assertEquals(paramValue,
+ assertEquals(paramValue,
cGroupsHandler.getCGroupParam(controller, testCGroup, param));
}
@@ -198,7 +201,7 @@ public void testMtabParsing() throws Exception {
newMtab);
// Verify
- Assert.assertEquals(4, controllerPaths.size());
+ assertEquals(4, controllerPaths.size());
assertTrue(controllerPaths
.containsKey(CGroupsHandler.CGroupController.CPU));
assertTrue(controllerPaths
@@ -206,8 +209,8 @@ public void testMtabParsing() throws Exception {
String cpuDir = controllerPaths.get(CGroupsHandler.CGroupController.CPU);
String memoryDir =
controllerPaths.get(CGroupsHandler.CGroupController.MEMORY);
- Assert.assertEquals(parentDir.getAbsolutePath(), cpuDir);
- Assert.assertEquals(parentDir.getAbsolutePath(), memoryDir);
+ assertEquals(parentDir.getAbsolutePath(), cpuDir);
+ assertEquals(parentDir.getAbsolutePath(), memoryDir);
}
/*
@@ -245,8 +248,8 @@ public File createPremountedHybridCgroups(File v1ParentDir)
CGroupsHandler.CGROUP_CONTROLLERS_FILE, enabledV2Controllers);
File subtreeControlFile = new File(v2ParentDir, CGroupsHandler.CGROUP_SUBTREE_CONTROL_FILE);
- Assert.assertTrue("empty subtree_control file should be created",
- subtreeControlFile.createNewFile());
+ assertTrue(subtreeControlFile.createNewFile(),
+ "empty subtree_control file should be created");
File hierarchyDir = new File(v2ParentDir, hierarchy);
if (!hierarchyDir.mkdirs()) {
@@ -269,7 +272,7 @@ public void testHybridMtabParsing() throws Exception {
File v1ParentDir = new File(tmpPath);
File v2ParentDir = new File(v1ParentDir, "unified");
- Assert.assertTrue("temp dir should be created", v2ParentDir.mkdirs());
+ assertTrue(v2ParentDir.mkdirs(), "temp dir should be created");
v2ParentDir.deleteOnExit();
// create mock cgroup
@@ -277,7 +280,7 @@ public void testHybridMtabParsing() throws Exception {
// create memory cgroup for v1
File memoryCgroup = new File(v1ParentDir, "memory");
- assertTrue("Directory should be created", memoryCgroup.mkdirs());
+ assertTrue(memoryCgroup.mkdirs(), "Directory should be created");
// init v1 and v2 handlers
CGroupsHandlerImpl cGroupsHandler = new CGroupsHandlerImpl(
@@ -294,12 +297,12 @@ public void testHybridMtabParsing() throws Exception {
cGroupsHandler.initializeControllerPathsFromMtab(
newMtab);
- Assert.assertEquals(1, controllerv1Paths.size());
+ assertEquals(1, controllerv1Paths.size());
assertTrue(controllerv1Paths
.containsKey(CGroupsHandler.CGroupController.MEMORY));
String memoryDir =
controllerv1Paths.get(CGroupsHandler.CGroupController.MEMORY);
- Assert.assertEquals(memoryCgroup.getAbsolutePath(), memoryDir);
+ assertEquals(memoryCgroup.getAbsolutePath(), memoryDir);
// Verify resource handlers that are enabled in v2
newMtab =
@@ -308,11 +311,11 @@ public void testHybridMtabParsing() throws Exception {
cGroupsV2Handler.initializeControllerPathsFromMtab(
newMtab);
- Assert.assertEquals(3, controllerPaths.size());
+ assertEquals(3, controllerPaths.size());
assertTrue(controllerPaths
.containsKey(CGroupsHandler.CGroupController.CPU));
String cpuDir = controllerPaths.get(CGroupsHandler.CGroupController.CPU);
- Assert.assertEquals(v2ParentDir.getAbsolutePath(), cpuDir);
+ assertEquals(v2ParentDir.getAbsolutePath(), cpuDir);
}
@Test
@@ -343,7 +346,7 @@ private void validateCgroupV2Controllers(YarnConfiguration conf, String mountPat
throws Exception {
File baseCgroup = new File(mountPath);
File subCgroup = new File(mountPath, "/hadoop-yarn");
- Assert.assertTrue("temp dir should be created", subCgroup.mkdirs());
+ assertTrue(subCgroup.mkdirs(), "temp dir should be created");
subCgroup.deleteOnExit();
String enabledControllers = "cpuset cpu io memory hugetlb pids rdma misc\n";
@@ -352,36 +355,37 @@ private void validateCgroupV2Controllers(YarnConfiguration conf, String mountPat
File subtreeControlFile = new File(subCgroup.getAbsolutePath(),
CGroupsHandler.CGROUP_SUBTREE_CONTROL_FILE);
- Assert.assertTrue("empty subtree_control file should be created",
- subtreeControlFile.createNewFile());
+ assertTrue(subtreeControlFile.createNewFile(),
+ "empty subtree_control file should be created");
CGroupsV2HandlerImpl cGroupsHandler = new CGroupsV2HandlerImpl(conf, null);
cGroupsHandler.initializeCGroupController(CGroupsHandler.CGroupController.CPU);
- Assert.assertEquals("CPU cgroup path was not set", subCgroup.getAbsolutePath(),
+ assertEquals(subCgroup.getAbsolutePath(),
new File(cGroupsHandler.getPathForCGroup(
- CGroupsHandler.CGroupController.CPU, "")).getAbsolutePath());
+ CGroupsHandler.CGroupController.CPU, "")).getAbsolutePath(),
+ "CPU cgroup path was not set");
// Verify that the subtree control file was updated
String subtreeControllersEnabledString = FileUtils.readFileToString(subtreeControlFile,
StandardCharsets.UTF_8);
- Assert.assertEquals("The newly added controller doesn't contain + sign",
- 1, StringUtils.countMatches(subtreeControllersEnabledString, "+"));
- Assert.assertEquals("Controller is not enabled in subtree control file",
- controller.getName(), subtreeControllersEnabledString.replace("+", "").trim());
+ assertEquals(1, StringUtils.countMatches(subtreeControllersEnabledString, "+"),
+ "The newly added controller doesn't contain + sign");
+ assertEquals(controller.getName(), subtreeControllersEnabledString.replace("+", "").trim(),
+ "Controller is not enabled in subtree control file");
cGroupsHandler.initializeCGroupController(CGroupsHandler.CGroupController.MEMORY);
subtreeControllersEnabledString = FileUtils.readFileToString(subtreeControlFile,
StandardCharsets.UTF_8);
- Assert.assertEquals("The newly added controllers doesn't contain + signs",
- 2, StringUtils.countMatches(subtreeControllersEnabledString, "+"));
+ assertEquals(2, StringUtils.countMatches(subtreeControllersEnabledString, "+"),
+ "The newly added controllers doesn't contain + signs");
Set subtreeControllersEnabled = new HashSet<>(Arrays.asList(
subtreeControllersEnabledString.replace("+", " ").trim().split(" ")));
- Assert.assertEquals(2, subtreeControllersEnabled.size());
- Assert.assertTrue("Controller is not enabled in subtree control file",
- cGroupsHandler.getValidCGroups().containsAll(subtreeControllersEnabled));
+ assertEquals(2, subtreeControllersEnabled.size());
+ assertTrue(cGroupsHandler.getValidCGroups().containsAll(subtreeControllersEnabled),
+ "Controller is not enabled in subtree control file");
// Test that the subtree control file is appended correctly
// even if some controllers are present
@@ -391,29 +395,30 @@ private void validateCgroupV2Controllers(YarnConfiguration conf, String mountPat
subtreeControllersEnabledString = FileUtils.readFileToString(subtreeControlFile,
StandardCharsets.UTF_8);
- Assert.assertEquals("The newly added controller doesn't contain + sign",
- 1, StringUtils.countMatches(subtreeControllersEnabledString, "+"));
+ assertEquals(1, StringUtils.countMatches(subtreeControllersEnabledString, "+"),
+ "The newly added controller doesn't contain + sign");
subtreeControllersEnabled = new HashSet<>(Arrays.asList(
subtreeControllersEnabledString.replace("+", " ").split(" ")));
- Assert.assertEquals(3, subtreeControllersEnabled.size());
- Assert.assertTrue("Controllers not enabled in subtree control file",
- cGroupsHandler.getValidCGroups().containsAll(subtreeControllersEnabled));
+ assertEquals(3, subtreeControllersEnabled.size());
+ assertTrue(cGroupsHandler.getValidCGroups().containsAll(subtreeControllersEnabled),
+ "Controllers not enabled in subtree control file");
}
private void validateCgroupV1Controllers(YarnConfiguration conf, String mountPath)
throws ResourceHandlerException {
File blkio = new File(new File(mountPath, "blkio"), "/hadoop-yarn");
- Assert.assertTrue("temp dir should be created", blkio.mkdirs());
+ assertTrue(blkio.mkdirs(), "temp dir should be created");
CGroupsHandlerImpl cGroupsv1Handler = new CGroupsHandlerImpl(conf, null);
cGroupsv1Handler.initializeCGroupController(
CGroupsHandler.CGroupController.BLKIO);
- Assert.assertEquals("BLKIO CGRoup path was not set", blkio.getAbsolutePath(),
+ assertEquals(blkio.getAbsolutePath(),
new File(cGroupsv1Handler.getPathForCGroup(
- CGroupsHandler.CGroupController.BLKIO, "")).getAbsolutePath());
+ CGroupsHandler.CGroupController.BLKIO, "")).getAbsolutePath(),
+ "BLKIO CGRoup path was not set");
FileUtils.deleteQuietly(blkio);
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2ResourceCalculator.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2ResourceCalculator.java
index 63a67eb0b19c5..e51f45d43a71c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2ResourceCalculator.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCGroupsV2ResourceCalculator.java
@@ -25,14 +25,14 @@
import java.util.Arrays;
import java.util.stream.Collectors;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.util.CpuTimeTracker;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -44,12 +44,12 @@ public class TestCGroupsV2ResourceCalculator {
private Path root;
- @Before
+ @BeforeEach
public void before() throws IOException {
root = Files.createTempDirectory("TestCGroupsV2ResourceCalculator");
}
- @After
+ @AfterEach
public void after() throws IOException {
FileUtils.deleteDirectory(root.toFile());
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCgroupsV2MemoryResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCgroupsV2MemoryResourceHandlerImpl.java
index 064bc1a0ee532..655c5e748d2a3 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCgroupsV2MemoryResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestCgroupsV2MemoryResourceHandlerImpl.java
@@ -26,12 +26,15 @@
import org.apache.hadoop.yarn.security.ContainerTokenIdentifier;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
-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.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -43,7 +46,7 @@ public class TestCgroupsV2MemoryResourceHandlerImpl {
private CGroupsHandler mockCGroupsHandler;
private CGroupsV2MemoryResourceHandlerImpl cGroupsMemoryResourceHandler;
- @Before
+ @BeforeEach
public void setup() {
mockCGroupsHandler = mock(CGroupsHandler.class);
when(mockCGroupsHandler.getPathForCGroup(any(), any())).thenReturn(".");
@@ -60,19 +63,19 @@ public void testBootstrap() throws Exception {
cGroupsMemoryResourceHandler.bootstrap(conf);
verify(mockCGroupsHandler, times(1))
.initializeCGroupController(CGroupsHandler.CGroupController.MEMORY);
- Assert.assertNull(ret);
+ assertNull(ret);
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, true);
try {
cGroupsMemoryResourceHandler.bootstrap(conf);
} catch (ResourceHandlerException re) {
- Assert.fail("Pmem check should be allowed to run with cgroups");
+ fail("Pmem check should be allowed to run with cgroups");
}
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, true);
try {
cGroupsMemoryResourceHandler.bootstrap(conf);
} catch (ResourceHandlerException re) {
- Assert.fail("Vmem check should be allowed to run with cgroups");
+ fail("Vmem check should be allowed to run with cgroups");
}
}
@@ -106,14 +109,14 @@ public void testPreStart() throws Exception {
.updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
CGroupsHandler.CGROUP_MEMORY_LOW,
String.valueOf((int) (memory * 0.9)) + "M");
- Assert.assertNotNull(ret);
- Assert.assertEquals(1, ret.size());
+ assertNotNull(ret);
+ assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@@ -148,21 +151,21 @@ public void testPreStartNonEnforced() throws Exception {
.updateCGroupParam(CGroupsHandler.CGroupController.MEMORY, id,
CGroupsHandler.CGROUP_MEMORY_LOW,
String.valueOf((int) (memory * 0.9)) + "M");
- Assert.assertNotNull(ret);
- Assert.assertEquals(1, ret.size());
+ assertNotNull(ret);
+ assertEquals(1, ret.size());
PrivilegedOperation op = ret.get(0);
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
op.getOperationType());
List args = op.getArguments();
- Assert.assertEquals(1, args.size());
- Assert.assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
+ assertEquals(1, args.size());
+ assertEquals(PrivilegedOperation.CGROUP_ARG_PREFIX + path,
args.get(0));
}
@Test
public void testReacquireContainer() throws Exception {
ContainerId containerIdMock = mock(ContainerId.class);
- Assert.assertNull(
+ assertNull(
cGroupsMemoryResourceHandler.reacquireContainer(containerIdMock));
}
@@ -171,15 +174,14 @@ public void testPostComplete() throws Exception {
String id = "container_01_01";
ContainerId mockContainerId = mock(ContainerId.class);
when(mockContainerId.toString()).thenReturn(id);
- Assert
- .assertNull(cGroupsMemoryResourceHandler.postComplete(mockContainerId));
+ assertNull(cGroupsMemoryResourceHandler.postComplete(mockContainerId));
verify(mockCGroupsHandler, times(1))
.deleteCGroup(CGroupsHandler.CGroupController.MEMORY, id);
}
@Test
public void testTeardown() throws Exception {
- Assert.assertNull(cGroupsMemoryResourceHandler.teardown());
+ assertNull(cGroupsMemoryResourceHandler.teardown());
}
@Test
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestDefaultOOMHandler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestDefaultOOMHandler.java
index 9773d90ed0cf2..bfb7ff8605855 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestDefaultOOMHandler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestDefaultOOMHandler.java
@@ -28,7 +28,7 @@
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.executor.ContainerSignalContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@@ -37,6 +37,7 @@
import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsHandler.CGROUP_PARAM_MEMORY_MEMSW_USAGE_BYTES;
import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsHandler.CGROUP_PARAM_MEMORY_OOM_CONTROL;
import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.CGroupsHandler.CGROUP_PARAM_MEMORY_USAGE_BYTES;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -51,59 +52,63 @@ public class TestDefaultOOMHandler {
/**
* Test an OOM situation where there are no containers that can be killed.
*/
- @Test(expected = YarnRuntimeException.class)
+ @Test
public void testExceptionThrownWithNoContainersToKill() throws Exception {
- Context context = mock(Context.class);
-
- when(context.getContainers()).thenReturn(new ConcurrentHashMap<>(0));
-
- CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
- when(cGroupsHandler.getCGroupParam(
- CGroupsHandler.CGroupController.MEMORY,
- "",
- CGROUP_PARAM_MEMORY_OOM_CONTROL))
- .thenReturn("under_oom 1").thenReturn("under_oom 0");
-
- DefaultOOMHandler handler = new DefaultOOMHandler(context, false) {
- @Override
- protected CGroupsHandler getCGroupsHandler() {
- return cGroupsHandler;
- }
- };
-
- handler.run();
+ assertThrows(YarnRuntimeException.class, () -> {
+ Context context = mock(Context.class);
+
+ when(context.getContainers()).thenReturn(new ConcurrentHashMap<>(0));
+
+ CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
+ when(cGroupsHandler.getCGroupParam(
+ CGroupsHandler.CGroupController.MEMORY,
+ "",
+ CGROUP_PARAM_MEMORY_OOM_CONTROL))
+ .thenReturn("under_oom 1").thenReturn("under_oom 0");
+
+ DefaultOOMHandler handler = new DefaultOOMHandler(context, false) {
+ @Override
+ protected CGroupsHandler getCGroupsHandler() {
+ return cGroupsHandler;
+ }
+ };
+
+ handler.run();
+ });
}
/**
* Test an OOM situation where there are no running containers that
* can be killed.
*/
- @Test(expected = YarnRuntimeException.class)
+ @Test
public void testExceptionThrownWithNoRunningContainersToKill()
throws Exception {
- ConcurrentHashMap containers =
- new ConcurrentHashMap<>();
- Container c1 = createContainer(1, true, 1L, false);
- containers.put(c1.getContainerId(), c1);
-
- Context context = mock(Context.class);
- when(context.getContainers()).thenReturn(containers);
-
- CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
- when(cGroupsHandler.getCGroupParam(
- CGroupsHandler.CGroupController.MEMORY,
- "",
- CGROUP_PARAM_MEMORY_OOM_CONTROL))
- .thenReturn("under_oom 1").thenReturn("under_oom 0");
-
- DefaultOOMHandler handler = new DefaultOOMHandler(context, false) {
- @Override
- protected CGroupsHandler getCGroupsHandler() {
- return cGroupsHandler;
- }
- };
-
- handler.run();
+ assertThrows(YarnRuntimeException.class, () -> {
+ ConcurrentHashMap containers =
+ new ConcurrentHashMap<>();
+ Container c1 = createContainer(1, true, 1L, false);
+ containers.put(c1.getContainerId(), c1);
+
+ Context context = mock(Context.class);
+ when(context.getContainers()).thenReturn(containers);
+
+ CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
+ when(cGroupsHandler.getCGroupParam(
+ CGroupsHandler.CGroupController.MEMORY,
+ "",
+ CGROUP_PARAM_MEMORY_OOM_CONTROL))
+ .thenReturn("under_oom 1").thenReturn("under_oom 0");
+
+ DefaultOOMHandler handler = new DefaultOOMHandler(context, false) {
+ @Override
+ protected CGroupsHandler getCGroupsHandler() {
+ return cGroupsHandler;
+ }
+ };
+
+ handler.run();
+ });
}
/**
@@ -489,46 +494,46 @@ protected CGroupsHandler getCGroupsHandler() {
* running as processes. Their cgroup.procs file is not available,
* so kill them won't succeed.
*/
- @Test(expected = YarnRuntimeException.class)
+ @Test
public void testExceptionThrownWhenNoContainersKilledSuccessfully()
throws Exception {
- ConcurrentHashMap containers =
- new ConcurrentHashMap<>();
- Container c1 = createContainer(1, false, 1L, true);
- containers.put(c1.getContainerId(), c1);
- Container c2 = createContainer(2, false, 2L, true);
- containers.put(c2.getContainerId(), c2);
-
- ContainerExecutor ex = createContainerExecutor(containers);
- Context context = mock(Context.class);
- when(context.getContainers()).thenReturn(containers);
- when(context.getContainerExecutor()).thenReturn(ex);
-
- CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
- when(cGroupsHandler.getCGroupParam(
- CGroupsHandler.CGroupController.MEMORY,
- "",
- CGROUP_PARAM_MEMORY_OOM_CONTROL))
- .thenReturn("under_oom 1").thenReturn("under_oom 0");
- // c1 process has not started, hence no cgroup.procs file yet
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c1.getContainerId().toString(), CGROUP_PROCS_FILE))
- .thenThrow(
- new ResourceHandlerException(CGROUP_PROCS_FILE + " not found"));
- // c2 process has not started, hence no cgroup.procs file yet
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c2.getContainerId().toString(), CGROUP_PROCS_FILE))
- .thenThrow(
- new ResourceHandlerException(CGROUP_PROCS_FILE + " not found"));
-
- DefaultOOMHandler handler =
- new DefaultOOMHandler(context, false) {
- @Override
- protected CGroupsHandler getCGroupsHandler() {
- return cGroupsHandler;
- }
- };
- handler.run();
+ assertThrows(YarnRuntimeException.class, () -> {
+ ConcurrentHashMap containers =
+ new ConcurrentHashMap<>();
+ Container c1 = createContainer(1, false, 1L, true);
+ containers.put(c1.getContainerId(), c1);
+ Container c2 = createContainer(2, false, 2L, true);
+ containers.put(c2.getContainerId(), c2);
+
+ ContainerExecutor ex = createContainerExecutor(containers);
+ Context context = mock(Context.class);
+ when(context.getContainers()).thenReturn(containers);
+ when(context.getContainerExecutor()).thenReturn(ex);
+
+ CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
+ when(cGroupsHandler.getCGroupParam(
+ CGroupsHandler.CGroupController.MEMORY,
+ "",
+ CGROUP_PARAM_MEMORY_OOM_CONTROL))
+ .thenReturn("under_oom 1").thenReturn("under_oom 0");
+ // c1 process has not started, hence no cgroup.procs file yet
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c1.getContainerId().toString(), CGROUP_PROCS_FILE))
+ .thenThrow(new ResourceHandlerException(CGROUP_PROCS_FILE + " not found"));
+ // c2 process has not started, hence no cgroup.procs file yet
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c2.getContainerId().toString(), CGROUP_PROCS_FILE))
+ .thenThrow(new ResourceHandlerException(CGROUP_PROCS_FILE + " not found"));
+
+ DefaultOOMHandler handler =
+ new DefaultOOMHandler(context, false) {
+ @Override
+ protected CGroupsHandler getCGroupsHandler() {
+ return cGroupsHandler;
+ }
+ };
+ handler.run();
+ });
}
/**
@@ -1160,69 +1165,70 @@ protected CGroupsHandler getCGroupsHandler() {
* OOM is not resolved even after killing all running containers.
* A YarnRuntimeException is excepted to be thrown.
*/
- @Test(expected = YarnRuntimeException.class)
+ @Test
public void testOOMUnresolvedAfterKillingAllContainers() throws Exception {
- int currentContainerId = 0;
-
- ConcurrentHashMap containers =
- new ConcurrentHashMap<>();
- Container c1 = createContainer(currentContainerId++, false, 1, true);
- containers.put(c1.getContainerId(), c1);
- Container c2 = createContainer(currentContainerId++, false, 2, true);
- containers.put(c2.getContainerId(), c2);
- Container c3 = createContainer(currentContainerId++, true, 3, true);
- containers.put(c3.getContainerId(), c3);
-
- ContainerExecutor ex = createContainerExecutor(containers);
- Context context = mock(Context.class);
- when(context.getContainers()).thenReturn(containers);
- when(context.getContainerExecutor()).thenReturn(ex);
-
- CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
- when(cGroupsHandler.getCGroupParam(
- CGroupsHandler.CGroupController.MEMORY,
- "",
- CGROUP_PARAM_MEMORY_OOM_CONTROL))
- .thenReturn("under_oom 1")
- .thenReturn("under_oom 1")
- .thenReturn("under_oom 1")
- .thenReturn("under_oom 1");
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c1.getContainerId().toString(), CGROUP_PROCS_FILE))
- .thenReturn("1234").thenReturn("");
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c1.getContainerId().toString(), CGROUP_PARAM_MEMORY_USAGE_BYTES))
- .thenReturn(getMB(9));
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c1.getContainerId().toString(), CGROUP_PARAM_MEMORY_MEMSW_USAGE_BYTES))
- .thenReturn(getMB(9));
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c2.getContainerId().toString(), CGROUP_PROCS_FILE))
- .thenReturn("1235").thenReturn("");
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c2.getContainerId().toString(), CGROUP_PARAM_MEMORY_USAGE_BYTES))
- .thenReturn(getMB(9));
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c2.getContainerId().toString(), CGROUP_PARAM_MEMORY_MEMSW_USAGE_BYTES))
- .thenReturn(getMB(9));
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c3.getContainerId().toString(), CGROUP_PROCS_FILE))
- .thenReturn("1236").thenReturn("");
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c3.getContainerId().toString(), CGROUP_PARAM_MEMORY_USAGE_BYTES))
- .thenReturn(getMB(9));
- when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
- c3.getContainerId().toString(), CGROUP_PARAM_MEMORY_MEMSW_USAGE_BYTES))
- .thenReturn(getMB(9));
-
- DefaultOOMHandler handler =
- new DefaultOOMHandler(context, false) {
+ assertThrows(YarnRuntimeException.class, () -> {
+ int currentContainerId = 0;
+
+ ConcurrentHashMap containers =
+ new ConcurrentHashMap<>();
+ Container c1 = createContainer(currentContainerId++, false, 1, true);
+ containers.put(c1.getContainerId(), c1);
+ Container c2 = createContainer(currentContainerId++, false, 2, true);
+ containers.put(c2.getContainerId(), c2);
+ Container c3 = createContainer(currentContainerId++, true, 3, true);
+ containers.put(c3.getContainerId(), c3);
+
+ ContainerExecutor ex = createContainerExecutor(containers);
+ Context context = mock(Context.class);
+ when(context.getContainers()).thenReturn(containers);
+ when(context.getContainerExecutor()).thenReturn(ex);
+
+ CGroupsHandler cGroupsHandler = mock(CGroupsHandler.class);
+ when(cGroupsHandler.getCGroupParam(
+ CGroupsHandler.CGroupController.MEMORY,
+ "",
+ CGROUP_PARAM_MEMORY_OOM_CONTROL))
+ .thenReturn("under_oom 1")
+ .thenReturn("under_oom 1")
+ .thenReturn("under_oom 1")
+ .thenReturn("under_oom 1");
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c1.getContainerId().toString(), CGROUP_PROCS_FILE))
+ .thenReturn("1234").thenReturn("");
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c1.getContainerId().toString(), CGROUP_PARAM_MEMORY_USAGE_BYTES))
+ .thenReturn(getMB(9));
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c1.getContainerId().toString(), CGROUP_PARAM_MEMORY_MEMSW_USAGE_BYTES))
+ .thenReturn(getMB(9));
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c2.getContainerId().toString(), CGROUP_PROCS_FILE))
+ .thenReturn("1235").thenReturn("");
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c2.getContainerId().toString(), CGROUP_PARAM_MEMORY_USAGE_BYTES))
+ .thenReturn(getMB(9));
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c2.getContainerId().toString(), CGROUP_PARAM_MEMORY_MEMSW_USAGE_BYTES))
+ .thenReturn(getMB(9));
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c3.getContainerId().toString(), CGROUP_PROCS_FILE))
+ .thenReturn("1236").thenReturn("");
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c3.getContainerId().toString(), CGROUP_PARAM_MEMORY_USAGE_BYTES))
+ .thenReturn(getMB(9));
+ when(cGroupsHandler.getCGroupParam(CGroupsHandler.CGroupController.MEMORY,
+ c3.getContainerId().toString(), CGROUP_PARAM_MEMORY_MEMSW_USAGE_BYTES))
+ .thenReturn(getMB(9));
+
+ DefaultOOMHandler handler = new DefaultOOMHandler(context, false) {
@Override
protected CGroupsHandler getCGroupsHandler() {
return cGroupsHandler;
}
- };
- handler.run();
+ };
+ handler.run();
+ });
}
private static ContainerId createContainerId(int id) {
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestNetworkPacketTaggingHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestNetworkPacketTaggingHandlerImpl.java
index e2d107d068730..e3795a6347a2a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestNetworkPacketTaggingHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestNetworkPacketTaggingHandlerImpl.java
@@ -20,6 +20,9 @@
package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
@@ -39,10 +42,9 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,7 +67,7 @@ public class TestNetworkPacketTaggingHandlerImpl {
private ContainerId containerIdMock;
private Container containerMock;
- @Before
+ @BeforeEach
public void setup() {
privilegedOperationExecutorMock = mock(PrivilegedOperationExecutor.class);
cGroupsHandlerMock = mock(CGroupsHandler.class);
@@ -99,7 +101,7 @@ public void testBootstrap() {
verifyNoMoreInteractions(cGroupsHandlerMock);
} catch (ResourceHandlerException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected ResourceHandlerException!");
+ fail("Caught unexpected ResourceHandlerException!");
}
}
@@ -113,7 +115,7 @@ public void testLifeCycle() {
testPostComplete(handlerImpl);
} catch (ResourceHandlerException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected ResourceHandlerException!");
+ fail("Caught unexpected ResourceHandlerException!");
}
}
@@ -136,7 +138,7 @@ private void testPreStart(NetworkPacketTaggingHandlerImpl handlerImpl) throws
//Now check the privileged operations being returned
//We expect one operations - for adding pid to tasks file
- Assert.assertEquals(1, ops.size());
+ assertEquals(1, ops.size());
//Verify that the add pid op is correct
PrivilegedOperation addPidOp = ops.get(0);
@@ -144,10 +146,10 @@ private void testPreStart(NetworkPacketTaggingHandlerImpl handlerImpl) throws
TEST_TASKS_FILE;
List addPidOpArgs = addPidOp.getArguments();
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
addPidOp.getOperationType());
- Assert.assertEquals(1, addPidOpArgs.size());
- Assert.assertEquals(expectedAddPidOpArg, addPidOpArgs.get(0));
+ assertEquals(1, addPidOpArgs.size());
+ assertEquals(expectedAddPidOpArg, addPidOpArgs.get(0));
}
private void testPostComplete(NetworkPacketTaggingHandlerImpl handlerImpl)
@@ -160,7 +162,7 @@ private void testPostComplete(NetworkPacketTaggingHandlerImpl handlerImpl)
eq(CGroupsHandler.CGroupController.NET_CLS), eq(TEST_CONTAINER_ID_STR));
//We don't expect any operations to be returned here
- Assert.assertNull(ops);
+ assertNull(ops);
}
private NetworkPacketTaggingHandlerImpl
@@ -175,7 +177,7 @@ public NetworkTagMappingManager createNetworkTagMappingManager(
};
}
- @After
+ @AfterEach
public void teardown() {
FileUtil.fullyDelete(new File(tmpPath));
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestResourceHandlerModule.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestResourceHandlerModule.java
index 171bfafc4fe7f..ecc2ff004422e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestResourceHandlerModule.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestResourceHandlerModule.java
@@ -21,13 +21,16 @@
package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.nodemanager.Context;
-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.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,7 +44,7 @@ public class TestResourceHandlerModule {
private Configuration emptyConf;
private Configuration networkEnabledConf;
- @Before
+ @BeforeEach
public void setup() throws Exception {
emptyConf = new YarnConfiguration();
networkEnabledConf = new YarnConfiguration();
@@ -58,12 +61,12 @@ public void testOutboundBandwidthHandler() {
//is explicitly enabled
OutboundBandwidthResourceHandler resourceHandler = ResourceHandlerModule
.initOutboundBandwidthResourceHandler(emptyConf);
- Assert.assertNull(resourceHandler);
+ assertNull(resourceHandler);
//When network as a resource is enabled this should be non-null
resourceHandler = ResourceHandlerModule
.initOutboundBandwidthResourceHandler(networkEnabledConf);
- Assert.assertNotNull(resourceHandler);
+ assertNotNull(resourceHandler);
//Ensure that outbound bandwidth resource handler is present in the chain
ResourceHandlerChain resourceHandlerChain = ResourceHandlerModule
@@ -75,12 +78,12 @@ public void testOutboundBandwidthHandler() {
//Exactly one resource handler in chain
assertThat(resourceHandlers).hasSize(1);
//Same instance is expected to be in the chain.
- Assert.assertTrue(resourceHandlers.get(0) == resourceHandler);
+ assertTrue(resourceHandlers.get(0) == resourceHandler);
} else {
- Assert.fail("Null returned");
+ fail("Null returned");
}
} catch (ResourceHandlerException e) {
- Assert.fail("Unexpected ResourceHandlerException: " + e);
+ fail("Unexpected ResourceHandlerException: " + e);
}
}
@@ -89,13 +92,13 @@ public void testDiskResourceHandler() throws Exception {
DiskResourceHandler handler =
ResourceHandlerModule.initDiskResourceHandler(emptyConf);
- Assert.assertNull(handler);
+ assertNull(handler);
Configuration diskConf = new YarnConfiguration();
diskConf.setBoolean(YarnConfiguration.NM_DISK_RESOURCE_ENABLED, true);
handler = ResourceHandlerModule.initDiskResourceHandler(diskConf);
- Assert.assertNotNull(handler);
+ assertNotNull(handler);
ResourceHandlerChain resourceHandlerChain =
ResourceHandlerModule.getConfiguredResourceHandlerChain(diskConf,
@@ -106,9 +109,9 @@ public void testDiskResourceHandler() throws Exception {
// Exactly one resource handler in chain
assertThat(resourceHandlers).hasSize(1);
// Same instance is expected to be in the chain.
- Assert.assertTrue(resourceHandlers.get(0) == handler);
+ assertTrue(resourceHandlers.get(0) == handler);
} else {
- Assert.fail("Null returned");
+ fail("Null returned");
}
}
}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficControlBandwidthHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficControlBandwidthHandlerImpl.java
index 08f5ee390a13f..af5c884791ea1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficControlBandwidthHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficControlBandwidthHandlerImpl.java
@@ -28,10 +28,9 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,6 +38,10 @@
import java.io.File;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@@ -67,7 +70,7 @@ public class TestTrafficControlBandwidthHandlerImpl {
ContainerId containerIdMock;
Container containerMock;
- @Before
+ @BeforeEach
public void setup() {
privilegedOperationExecutorMock = mock(PrivilegedOperationExecutor.class);
cGroupsHandlerMock = mock(CGroupsHandler.class);
@@ -108,7 +111,7 @@ public void testBootstrap() {
verifyNoMoreInteractions(trafficControllerMock);
} catch (ResourceHandlerException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected ResourceHandlerException!");
+ fail("Caught unexpected ResourceHandlerException!");
}
}
@@ -126,7 +129,7 @@ public void testLifeCycle() {
testPostComplete(trafficControllerSpy, handlerImpl);
} catch (ResourceHandlerException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected ResourceHandlerException!");
+ fail("Caught unexpected ResourceHandlerException!");
}
}
@@ -159,7 +162,7 @@ private void testPreStart(TrafficController trafficControllerSpy,
//Now check the privileged operations being returned
//We expect two operations - one for adding pid to tasks file and another
//for a tc modify operation
- Assert.assertEquals(2, ops.size());
+ assertEquals(2, ops.size());
//Verify that the add pid op is correct
PrivilegedOperation addPidOp = ops.get(0);
@@ -167,20 +170,20 @@ private void testPreStart(TrafficController trafficControllerSpy,
TEST_TASKS_FILE;
List addPidOpArgs = addPidOp.getArguments();
- Assert.assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
+ assertEquals(PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP,
addPidOp.getOperationType());
- Assert.assertEquals(1, addPidOpArgs.size());
- Assert.assertEquals(expectedAddPidOpArg, addPidOpArgs.get(0));
+ assertEquals(1, addPidOpArgs.size());
+ assertEquals(expectedAddPidOpArg, addPidOpArgs.get(0));
//Verify that that tc modify op is correct
PrivilegedOperation tcModifyOp = ops.get(1);
List tcModifyOpArgs = tcModifyOp.getArguments();
- Assert.assertEquals(PrivilegedOperation.OperationType.TC_MODIFY_STATE,
+ assertEquals(PrivilegedOperation.OperationType.TC_MODIFY_STATE,
tcModifyOp.getOperationType());
- Assert.assertEquals(1, tcModifyOpArgs.size());
+ assertEquals(1, tcModifyOpArgs.size());
//verify that the tc command file exists
- Assert.assertTrue(new File(tcModifyOpArgs.get(0)).exists());
+ assertTrue(new File(tcModifyOpArgs.get(0)).exists());
}
private void testPostComplete(TrafficController trafficControllerSpy,
@@ -208,23 +211,23 @@ private void testPostComplete(TrafficController trafficControllerSpy,
List args = opCaptor.getValue().getArguments();
- Assert.assertEquals(PrivilegedOperation.OperationType.TC_MODIFY_STATE,
+ assertEquals(PrivilegedOperation.OperationType.TC_MODIFY_STATE,
opCaptor.getValue().getOperationType());
- Assert.assertEquals(1, args.size());
+ assertEquals(1, args.size());
//ensure that tc command file exists
- Assert.assertTrue(new File(args.get(0)).exists());
+ assertTrue(new File(args.get(0)).exists());
verify(trafficControllerSpy).releaseClassId(TEST_CLASSID);
} catch (PrivilegedOperationException e) {
LOG.error("Caught exception: " + e);
- Assert.fail("Unexpected PrivilegedOperationException from mock!");
+ fail("Unexpected PrivilegedOperationException from mock!");
}
//We don't expect any operations to be returned here
- Assert.assertNull(ops);
+ assertNull(ops);
}
- @After
+ @AfterEach
public void teardown() {
FileUtil.fullyDelete(new File(tmpPath));
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficController.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficController.java
index fd77a953d1726..072e854a5618f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficController.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficController.java
@@ -26,10 +26,9 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationException;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperationExecutor;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,6 +40,9 @@
import java.util.Arrays;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -92,7 +94,7 @@ public class TestTrafficController {
private PrivilegedOperationExecutor privilegedOperationExecutorMock;
- @Before
+ @BeforeEach
public void setup() {
privilegedOperationExecutorMock = mock(PrivilegedOperationExecutor.class);
conf = new YarnConfiguration();
@@ -107,26 +109,26 @@ private void verifyTrafficControlOperation(PrivilegedOperation op,
List expectedTcCmds)
throws IOException {
//Verify that the optype matches
- Assert.assertEquals(expectedOpType, op.getOperationType());
+ assertEquals(expectedOpType, op.getOperationType());
List args = op.getArguments();
//Verify that arg count is always 1 (tc command file) for a tc operation
- Assert.assertEquals(1, args.size());
+ assertEquals(1, args.size());
File tcCmdsFile = new File(args.get(0));
//Verify that command file exists
- Assert.assertTrue(tcCmdsFile.exists());
+ assertTrue(tcCmdsFile.exists());
List tcCmds = Files.readAllLines(tcCmdsFile.toPath(),
StandardCharsets.UTF_8);
//Verify that the number of commands is the same as expected and verify
//that each command is the same, in sequence
- Assert.assertEquals(expectedTcCmds.size(), tcCmds.size());
+ assertEquals(expectedTcCmds.size(), tcCmds.size());
for (int i = 0; i < tcCmds.size(); ++i) {
- Assert.assertEquals(expectedTcCmds.get(i), tcCmds.get(i));
+ assertEquals(expectedTcCmds.get(i), tcCmds.get(i));
}
}
@@ -163,7 +165,7 @@ public void testBootstrapRecoveryDisabled() {
} catch (ResourceHandlerException | PrivilegedOperationException |
IOException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected exception: "
+ fail("Caught unexpected exception: "
+ e.getClass().getSimpleName());
}
}
@@ -215,7 +217,7 @@ public void testBootstrapRecoveryEnabled() {
} catch (ResourceHandlerException | PrivilegedOperationException |
IOException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected exception: "
+ fail("Caught unexpected exception: "
+ e.getClass().getSimpleName());
}
}
@@ -235,13 +237,13 @@ public void testInvalidBuilder() {
TrafficController.BatchBuilder invalidBuilder = trafficController.
new BatchBuilder(
PrivilegedOperation.OperationType.ADD_PID_TO_CGROUP);
- Assert.fail("Invalid builder check failed!");
+ fail("Invalid builder check failed!");
} catch (ResourceHandlerException e) {
//expected
}
} catch (ResourceHandlerException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected exception: "
+ fail("Caught unexpected exception: "
+ e.getClass().getSimpleName());
}
}
@@ -259,7 +261,7 @@ public void testClassIdFileContentParsing() {
int parsedClassId = trafficController.getClassIdFromFileContents
(TEST_CLASS_ID_DECIMAL_STR);
- Assert.assertEquals(TEST_CLASS_ID, parsedClassId);
+ assertEquals(TEST_CLASS_ID, parsedClassId);
}
@Test
@@ -274,8 +276,8 @@ public void testContainerOperations() {
int classId = trafficController.getNextClassId();
- Assert.assertTrue(classId >= MIN_CONTAINER_CLASS_ID);
- Assert.assertEquals(String.format(FORMAT_CONTAINER_CLASS_STR, classId),
+ assertTrue(classId >= MIN_CONTAINER_CLASS_ID);
+ assertEquals(String.format(FORMAT_CONTAINER_CLASS_STR, classId),
trafficController.getStringForNetClsClassId(classId));
//Verify that the operation is setup correctly with strictMode = false
@@ -316,12 +318,12 @@ public void testContainerOperations() {
Arrays.asList(expectedDeleteClassCmd));
} catch (ResourceHandlerException | IOException e) {
LOG.error("Unexpected exception: " + e);
- Assert.fail("Caught unexpected exception: "
+ fail("Caught unexpected exception: "
+ e.getClass().getSimpleName());
}
}
- @After
+ @AfterEach
public void teardown() {
FileUtil.fullyDelete(new File(tmpPath));
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/fpga/TestFpgaResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/fpga/TestFpgaResourceHandlerImpl.java
index 189639d82b759..813274b8bdb25 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/fpga/TestFpgaResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/fpga/TestFpgaResourceHandlerImpl.java
@@ -18,7 +18,10 @@
package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.fpga;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+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.anyList;
@@ -66,19 +69,14 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.resourceplugin.fpga.FpgaDevice;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.util.resource.CustomResourceTypesConfigurationProvider;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.apache.hadoop.thirdparty.com.google.common.io.FileWriteMode;
import org.apache.hadoop.thirdparty.com.google.common.io.Files;
public class TestFpgaResourceHandlerImpl {
- @Rule
- public ExpectedException expected = ExpectedException.none();
private static final String HASHABLE_STRING = "abcdef";
private static final String EXPECTED_HASH =
@@ -103,7 +101,7 @@ private String getTestParentFolder() {
return f.getAbsolutePath();
}
- @Before
+ @BeforeEach
public void setup() throws IOException, YarnException {
CustomResourceTypesConfigurationProvider.
initResourceTypes(ResourceInformation.FPGA_URI);
@@ -138,7 +136,7 @@ public void setup() throws IOException, YarnException {
.write(HASHABLE_STRING);
}
- @After
+ @AfterEach
public void teardown() {
if (dummyAocx != null) {
dummyAocx.delete();
@@ -155,9 +153,9 @@ public void testBootstrap() throws ResourceHandlerException {
verify(mockVendorPlugin, times(2)).initPlugin(configuration);
verify(mockCGroupsHandler, times(1)).initializeCGroupController(
CGroupsHandler.CGroupController.DEVICES);
- Assert.assertEquals(5, fpgaResourceHandler.getFpgaAllocator()
+ assertEquals(5, fpgaResourceHandler.getFpgaAllocator()
.getAvailableFpgaCount());
- Assert.assertEquals(5, fpgaResourceHandler.getFpgaAllocator()
+ assertEquals(5, fpgaResourceHandler.getFpgaAllocator()
.getAllowedFpga().size());
// Case 2. subset of devices
fpgaResourceHandler = new FpgaResourceHandlerImpl(mockContext,
@@ -166,7 +164,7 @@ public void testBootstrap() throws ResourceHandlerException {
allowed = "0,1,2";
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
fpgaResourceHandler.bootstrap(configuration);
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga().size());
List allowedDevices =
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga();
@@ -177,9 +175,9 @@ public void testBootstrap() throws ResourceHandlerException {
check = true;
}
}
- Assert.assertTrue("Minor:" + s +" found", check);
+ assertTrue(check, "Minor:" + s +" found");
}
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 3. User configuration contains invalid minor device number
@@ -189,9 +187,9 @@ public void testBootstrap() throws ResourceHandlerException {
allowed = "0,1,7";
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
fpgaResourceHandler.bootstrap(configuration);
- Assert.assertEquals(2,
+ assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
- Assert.assertEquals(2,
+ assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga().size());
}
@@ -202,9 +200,9 @@ public void testBootstrapWithInvalidUserConfiguration()
String allowed = "0,1,7";
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, allowed);
fpgaResourceHandler.bootstrap(configuration);
- Assert.assertEquals(2,
+ assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga().size());
- Assert.assertEquals(2,
+ assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
String[] invalidAllowedStrings = {"a,1,2,", "a,1,2", "0,1,2,#", "a", "1,"};
@@ -216,7 +214,7 @@ public void testBootstrapWithInvalidUserConfiguration()
} catch (ResourceHandlerException e) {
invalidConfiguration = true;
}
- Assert.assertTrue(invalidConfiguration);
+ assertTrue(invalidConfiguration);
}
String[] allowedStrings = {"1,2", "1"};
@@ -228,7 +226,7 @@ public void testBootstrapWithInvalidUserConfiguration()
} catch (ResourceHandlerException e) {
invalidConfiguration = true;
}
- Assert.assertFalse(invalidConfiguration);
+ assertFalse(invalidConfiguration);
}
}
@@ -244,7 +242,7 @@ public void testBootStrapWithEmptyUserConfiguration()
} catch (ResourceHandlerException e) {
invalidConfiguration = true;
}
- Assert.assertTrue(invalidConfiguration);
+ assertTrue(invalidConfiguration);
}
@Test
@@ -254,12 +252,12 @@ public void testAllocationWithPreference()
fpgaResourceHandler.bootstrap(configuration);
// Case 1. The id-0 container request 1 FPGA of IntelOpenCL type and GEMM IP
fpgaResourceHandler.preStart(mockContainer(0, 1, "GEMM"));
- Assert.assertEquals(1, fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
+ assertEquals(1, fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
verifyDeniedDevices(getContainerId(0), Arrays.asList(1, 2));
List list = fpgaResourceHandler.getFpgaAllocator()
.getUsedFpga().get(getContainerId(0).toString());
for (FpgaDevice device : list) {
- Assert.assertEquals("IP should be updated to GEMM", "GEMM", device.getIPID());
+ assertEquals("GEMM", device.getIPID(), "IP should be updated to GEMM");
}
// Case 2. The id-1 container request 3 FPGA of IntelOpenCL and GEMM IP. this should fail
boolean flag = false;
@@ -268,26 +266,26 @@ public void testAllocationWithPreference()
} catch (ResourceHandlerException e) {
flag = true;
}
- Assert.assertTrue(flag);
+ assertTrue(flag);
// Case 3. Release the id-0 container
fpgaResourceHandler.postComplete(getContainerId(0));
- Assert.assertEquals(0,
+ assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Now we have enough devices, re-allocate for the id-1 container
fpgaResourceHandler.preStart(mockContainer(1, 3, "GEMM"));
// Id-1 container should have 0 denied devices
verifyDeniedDevices(getContainerId(1), new ArrayList<>());
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(0,
+ assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Release container id-1
fpgaResourceHandler.postComplete(getContainerId(1));
- Assert.assertEquals(0,
+ assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 4. Now all 3 devices should have IPID GEMM
// Try container id-2 and id-3
@@ -299,32 +297,32 @@ public void testAllocationWithPreference()
list = fpgaResourceHandler.getFpgaAllocator()
.getUsedFpga().get(getContainerId(3).toString());
for (FpgaDevice device : list) {
- Assert.assertEquals("IPID should be GEMM", "GEMM", device.getIPID());
+ assertEquals("GEMM", device.getIPID(), "IPID should be GEMM");
}
- Assert.assertEquals(2,
+ assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(1,
+ assertEquals(1,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
fpgaResourceHandler.postComplete(getContainerId(3));
- Assert.assertEquals(0,
+ assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 5. id-4 request 0 FPGA device
fpgaResourceHandler.preStart(mockContainer(4, 0, ""));
// Deny all devices for id-4
verifyDeniedDevices(getContainerId(4), Arrays.asList(0, 1, 2));
- Assert.assertEquals(0,
+ assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 6. id-5 with invalid FPGA device
try {
fpgaResourceHandler.preStart(mockContainer(5, -2, ""));
} catch (ResourceHandlerException e) {
- Assert.assertTrue(true);
+ assertTrue(true);
}
}
@@ -336,7 +334,7 @@ public void testsAllocationWithExistingIPIDDevices()
fpgaResourceHandler.bootstrap(configuration);
// The id-0 container request 3 FPGA of IntelOpenCL type and GEMM IP
fpgaResourceHandler.preStart(mockContainer(0, 3, "GEMM"));
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
List list =
fpgaResourceHandler
@@ -345,8 +343,8 @@ public void testsAllocationWithExistingIPIDDevices()
.get(getContainerId(0).toString());
fpgaResourceHandler.postComplete(getContainerId(0));
for (FpgaDevice device : list) {
- Assert.assertEquals("IP should be updated to GEMM", "GEMM",
- device.getIPID());
+ assertEquals("GEMM", device.getIPID(),
+ "IP should be updated to GEMM");
}
// Case 1. id-1 container request preStart, with no plugin.configureIP called
@@ -419,9 +417,9 @@ public void testReacquireContainer() throws ResourceHandlerException {
// NM start
configuration.set(YarnConfiguration.NM_FPGA_ALLOWED_DEVICES, "0,1,2");
fpgaResourceHandler.bootstrap(configuration);
- Assert.assertEquals(0,
+ assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 1. try recover state for id-0 container
fpgaResourceHandler.reacquireContainer(getContainerId(0));
@@ -438,7 +436,7 @@ public void testReacquireContainer() throws ResourceHandlerException {
count++;
}
}
- Assert.assertEquals("Unexpected used minor number in allocator",2, count);
+ assertEquals(2, count, "Unexpected used minor number in allocator");
List available =
fpgaResourceHandler
.getFpgaAllocator()
@@ -450,8 +448,7 @@ public void testReacquireContainer() throws ResourceHandlerException {
count++;
}
}
- Assert.assertEquals("Unexpected available minor number in allocator",
- 1, count);
+ assertEquals(1, count, "Unexpected available minor number in allocator");
// Case 2. Recover a not allowed device with minor number 5
@@ -467,10 +464,10 @@ public void testReacquireContainer() throws ResourceHandlerException {
} catch (ResourceHandlerException e) {
flag = true;
}
- Assert.assertTrue(flag);
- Assert.assertEquals(2,
+ assertTrue(flag);
+ assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(1,
+ assertEquals(1,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 3. recover a already used device by other container
@@ -486,10 +483,10 @@ public void testReacquireContainer() throws ResourceHandlerException {
} catch (ResourceHandlerException e) {
flag = true;
}
- Assert.assertTrue(flag);
- Assert.assertEquals(2,
+ assertTrue(flag);
+ assertEquals(2,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(1,
+ assertEquals(1,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
// Case 4. recover a normal container c3 with remaining minor device number 2
@@ -500,19 +497,20 @@ public void testReacquireContainer() throws ResourceHandlerException {
// Mock we've stored the c2 states
mockStateStoreForContainer(c3, assigned);
fpgaResourceHandler.reacquireContainer(getContainerId(3));
- Assert.assertEquals(3,
+ assertEquals(3,
fpgaResourceHandler.getFpgaAllocator().getUsedFpgaCount());
- Assert.assertEquals(0,
+ assertEquals(0,
fpgaResourceHandler.getFpgaAllocator().getAvailableFpgaCount());
}
@Test
public void testSha256CalculationFails() throws ResourceHandlerException {
- expected.expect(ResourceHandlerException.class);
- expected.expectMessage("Could not calculate SHA-256");
-
- dummyAocx.delete();
- fpgaResourceHandler.preStart(mockContainer(0, 1, "GEMM"));
+ ResourceHandlerException exception =
+ assertThrows(ResourceHandlerException.class, () -> {
+ dummyAocx.delete();
+ fpgaResourceHandler.preStart(mockContainer(0, 1, "GEMM"));
+ });
+ assertEquals("Could not calculate SHA-256", exception.getMessage());
}
@Test
@@ -531,7 +529,7 @@ public void testSha256CalculationSucceeds()
List devices =
fpgaResourceHandler.getFpgaAllocator().getAllowedFpga();
FpgaDevice device = devices.get(0);
- assertEquals("Hash value", EXPECTED_HASH, device.getAocxHash());
+ assertEquals(EXPECTED_HASH, device.getAocxHash(), "Hash value");
}
private void verifyDeniedDevices(ContainerId containerId,
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceAllocator.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceAllocator.java
index ed8fe2df365b7..f82cf25e3dc7c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceAllocator.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceAllocator.java
@@ -19,7 +19,9 @@
import static org.apache.hadoop.test.MockitoUtil.verifyZeroInteractions;
import static org.apache.hadoop.yarn.api.records.ResourceInformation.GPU_URI;
import static org.apache.hadoop.yarn.util.resource.CustomResourceTypesConfigurationProvider.initResourceTypes;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
@@ -49,10 +51,8 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.gpu.GpuResourceAllocator.GpuAllocation;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.resourceplugin.gpu.GpuDevice;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher;
import org.mockito.Captor;
@@ -90,12 +90,9 @@ public boolean matches(Container other) {
@Mock
private NMStateStoreService nmStateStore;
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
private GpuResourceAllocator testSubject;
- @Before
+ @BeforeEach
public void setup() {
initResourceTypes(ResourceInformation.GPU_URI);
MockitoAnnotations.initMocks(this);
@@ -309,64 +306,68 @@ public void testRequestOneGpu() throws ResourceHandlerException, IOException {
@Test
public void testRequestMoreThanAvailableGpu()
throws ResourceHandlerException {
- addGpus(new GpuDevice(1, 1));
- Container container = createMockContainer(2, 5L);
-
- exception.expect(ResourceHandlerException.class);
- exception.expectMessage("Failed to find enough GPUs");
- testSubject.assignGpus(container);
+ ResourceHandlerException exception = assertThrows(ResourceHandlerException.class, () -> {
+ addGpus(new GpuDevice(1, 1));
+ Container container = createMockContainer(2, 5L);
+ testSubject.assignGpus(container);
+ });
+ assertThat(exception.getMessage()).contains("Failed to find enough GPUs");
}
@Test
public void testRequestMoreThanAvailableGpuAndOneContainerIsReleasingGpus()
throws ResourceHandlerException, IOException {
- addGpus(new GpuDevice(1, 1), new GpuDevice(1, 2), new GpuDevice(1, 3));
- Container container = createMockContainer(2, 5L);
- GpuAllocation allocation = testSubject.assignGpus(container);
- assertAllocatedGpus(2, 1, container, allocation);
+ ResourceHandlerException exception = assertThrows(ResourceHandlerException.class, () -> {
+ addGpus(new GpuDevice(1, 1), new GpuDevice(1, 2), new GpuDevice(1, 3));
+ Container container = createMockContainer(2, 5L);
+ GpuAllocation allocation = testSubject.assignGpus(container);
+ assertAllocatedGpus(2, 1, container, allocation);
- assertEquals(2, testSubject.getDeviceAllocationMapping().size());
- assertEquals(2, testSubject.getAssignedGpus().size());
- assertEquals(3, testSubject.getAllowedGpus().size());
- assertEquals(1, testSubject.getAvailableGpus());
+ assertEquals(2, testSubject.getDeviceAllocationMapping().size());
+ assertEquals(2, testSubject.getAssignedGpus().size());
+ assertEquals(3, testSubject.getAllowedGpus().size());
+ assertEquals(1, testSubject.getAvailableGpus());
- setupContainerAsReleasingGpus(container);
- Container container2 = createMockContainer(2, 6L);
+ setupContainerAsReleasingGpus(container);
+ Container container2 = createMockContainer(2, 6L);
+ GpuAllocation allocation2 = testSubject.assignGpus(container2);
+ assertAllocatedGpus(2, 1, container, allocation2);
+ });
- exception.expect(ResourceHandlerException.class);
- exception.expectMessage("as some other containers might not " +
- "releasing GPUs");
- GpuAllocation allocation2 = testSubject.assignGpus(container2);
- assertAllocatedGpus(2, 1, container, allocation2);
+ assertThat(exception.getMessage()).
+ contains("as some other containers might not releasing GPUs");
}
@Test
public void testThreeContainersJustTwoOfThemSatisfied()
throws ResourceHandlerException, IOException {
- addGpus(new GpuDevice(1, 1), new GpuDevice(1, 2),
- new GpuDevice(1, 3), new GpuDevice(1, 4),
- new GpuDevice(1, 5), new GpuDevice(1, 6));
- Container container = createMockContainer(3, 5L);
- Container container2 = createMockContainer(2, 6L);
- Container container3 = createMockContainer(2, 6L);
-
- GpuAllocation allocation = testSubject.assignGpus(container);
- assertAllocatedGpus(3, 3, container, allocation);
- assertEquals(3, testSubject.getDeviceAllocationMapping().size());
- assertEquals(3, testSubject.getAssignedGpus().size());
- assertEquals(6, testSubject.getAllowedGpus().size());
- assertEquals(3, testSubject.getAvailableGpus());
-
- GpuAllocation allocation2 = testSubject.assignGpus(container2);
- assertAllocatedGpus(2, 4, container2, allocation2);
- assertEquals(5, testSubject.getDeviceAllocationMapping().size());
- assertEquals(5, testSubject.getAssignedGpus().size());
- assertEquals(6, testSubject.getAllowedGpus().size());
- assertEquals(1, testSubject.getAvailableGpus());
-
- exception.expect(ResourceHandlerException.class);
- exception.expectMessage("Failed to find enough GPUs");
- testSubject.assignGpus(container3);
+ ResourceHandlerException exception =
+ assertThrows(ResourceHandlerException.class, () -> {
+ addGpus(new GpuDevice(1, 1), new GpuDevice(1, 2),
+ new GpuDevice(1, 3), new GpuDevice(1, 4),
+ new GpuDevice(1, 5), new GpuDevice(1, 6));
+ Container container = createMockContainer(3, 5L);
+ Container container2 = createMockContainer(2, 6L);
+ Container container3 = createMockContainer(2, 6L);
+
+ GpuAllocation allocation = testSubject.assignGpus(container);
+ assertAllocatedGpus(3, 3, container, allocation);
+ assertEquals(3, testSubject.getDeviceAllocationMapping().size());
+ assertEquals(3, testSubject.getAssignedGpus().size());
+ assertEquals(6, testSubject.getAllowedGpus().size());
+ assertEquals(3, testSubject.getAvailableGpus());
+
+ GpuAllocation allocation2 = testSubject.assignGpus(container2);
+ assertAllocatedGpus(2, 4, container2, allocation2);
+ assertEquals(5, testSubject.getDeviceAllocationMapping().size());
+ assertEquals(5, testSubject.getAssignedGpus().size());
+ assertEquals(6, testSubject.getAllowedGpus().size());
+ assertEquals(1, testSubject.getAvailableGpus());
+
+ testSubject.assignGpus(container3);
+ });
+
+ assertThat(exception.getMessage()).contains("Failed to find enough GPUs");
}
@Test
@@ -425,17 +426,15 @@ public void testCreateLotsOfContainersVerifyGpuAssignmentsAreCorrect()
@Test
public void testGpuGetsUnassignedWhenStateStoreThrowsException()
throws ResourceHandlerException, IOException {
- doThrow(new IOException("Failed to save container mappings " +
- "to NM state store!"))
- .when(nmStateStore).storeAssignedResources(any(Container.class),
- anyString(), anyList());
-
- createAndAddGpus(1);
-
- exception.expect(ResourceHandlerException.class);
- exception.expectMessage("Failed to save container mappings " +
- "to NM state store");
- Container container = createMockContainer(1, 5L);
- testSubject.assignGpus(container);
+ assertThrows(ResourceHandlerException.class, () -> {
+ doThrow(new IOException("Failed to save container mappings " +
+ "to NM state store!"))
+ .when(nmStateStore).storeAssignedResources(any(Container.class),
+ anyString(), anyList());
+
+ createAndAddGpus(1);
+ Container container = createMockContainer(1, 5L);
+ testSubject.assignGpus(container);
+ });
}
}
\ No newline at end of file
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceHandlerImpl.java
index a8914c318804e..93b36cb08ccc0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/gpu/TestGpuResourceHandlerImpl.java
@@ -46,11 +46,9 @@
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
import org.apache.hadoop.yarn.util.resource.CustomResourceTypesConfigurationProvider;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileOutputStream;
@@ -62,9 +60,10 @@
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+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.anyList;
import static org.mockito.ArgumentMatchers.anyString;
@@ -114,12 +113,9 @@ private File setupFakeGpuDiscoveryBinary() throws IOException {
return fakeBinary;
}
- @Rule
- public ExpectedException expected = ExpectedException.none();
-
private NvidiaBinaryHelper nvidiaBinaryHelper;
- @Before
+ @BeforeEach
public void setup() throws IOException {
createTestDataDirectory();
nvidiaBinaryHelper = new NvidiaBinaryHelper();
@@ -147,7 +143,7 @@ private Context createMockNmContext(Configuration conf) {
return nmctx;
}
- @After
+ @AfterEach
public void cleanupTestFiles() throws IOException {
FileUtils.deleteDirectory(testDataDirectory);
nvidiaBinaryHelper = new NvidiaBinaryHelper();
@@ -163,22 +159,22 @@ public void testBootstrapWithRealGpuDiscoverer() throws Exception {
List allowedGpus =
gpuResourceHandler.getGpuAllocator().getAllowedGpus();
- assertEquals("Unexpected number of allowed GPU devices!", 1,
- allowedGpus.size());
- assertEquals("Expected GPU device does not equal to found device!",
- new GpuDevice(0, 0), allowedGpus.get(0));
+ assertEquals(1, allowedGpus.size(),
+ "Unexpected number of allowed GPU devices!");
+ assertEquals(new GpuDevice(0, 0), allowedGpus.get(0),
+ "Expected GPU device does not equal to found device!");
verify(mockCGroupsHandler).initializeCGroupController(
CGroupsHandler.CGroupController.DEVICES);
}
@Test
public void testBootstrapWithMockGpuDiscoverer() throws Exception {
- GpuDiscoverer mockDiscoverer = mock(GpuDiscoverer.class);
- Configuration conf = new YarnConfiguration();
- mockDiscoverer.initialize(conf, nvidiaBinaryHelper);
-
- expected.expect(ResourceHandlerException.class);
- gpuResourceHandler.bootstrap(conf);
+ assertThrows(ResourceHandlerException.class, () -> {
+ GpuDiscoverer mockDiscoverer = mock(GpuDiscoverer.class);
+ Configuration conf = new YarnConfiguration();
+ mockDiscoverer.initialize(conf, nvidiaBinaryHelper);
+ gpuResourceHandler.bootstrap(conf);
+ });
}
private static ContainerId getContainerId(int id) {
@@ -259,9 +255,9 @@ private void startContainerWithGpuRequests(int id, int gpus)
private void verifyNumberOfAvailableGpus(int expectedAvailable,
GpuResourceHandlerImpl resourceHandler) {
- assertEquals("Unexpected number of available GPU devices!",
- expectedAvailable,
- resourceHandler.getGpuAllocator().getAvailableGpus());
+ assertEquals(expectedAvailable,
+ resourceHandler.getGpuAllocator().getAvailableGpus(),
+ "Unexpected number of available GPU devices!");
}
private void verifyCgroupsDeletedForContainer(int i)
@@ -300,7 +296,7 @@ public void testAllocationWhenDockerContainerEnabled() throws Exception {
} catch (ResourceHandlerException e) {
failedToAllocate = true;
}
- assertTrue("Container allocation is expected to fail!", failedToAllocate);
+ assertTrue(failedToAllocate, "Container allocation is expected to fail!");
startContainerWithGpuRequestsDocker(3, 1);
verifyDeniedDevices(getContainerId(3), Collections.emptyList());
@@ -333,7 +329,7 @@ public void testAllocation() throws Exception {
} catch (ResourceHandlerException e) {
failedToAllocate = true;
}
- assertTrue("Container allocation is expected to fail!", failedToAllocate);
+ assertTrue(failedToAllocate, "Container allocation is expected to fail!");
// Start container 3, ask 1 container, succeeded
// devices = 0/1/3 will be blocked
@@ -374,7 +370,7 @@ public void testAssignedGpuWillBeCleanedUpWhenStoreOpFails()
exception = true;
}
- assertTrue("preStart should throw exception", exception);
+ assertTrue(exception, "preStart should throw exception");
// After preStart, we still have 4 available GPU since the store op failed.
verifyNumberOfAvailableGpus(4, gpuResourceHandler);
@@ -406,7 +402,7 @@ public void testAllocationWithoutAllowedGpus() throws Exception {
} catch (ResourceHandlerException e) {
failedToAllocate = true;
}
- assertTrue("Container allocation is expected to fail!", failedToAllocate);
+ assertTrue(failedToAllocate, "Container allocation is expected to fail!");
/* Release container 1, expect cgroups deleted */
gpuResourceHandler.postComplete(getContainerId(1));
@@ -440,9 +436,9 @@ public void testAllocationStored() throws Exception {
verifyDeniedDevices(getContainerId(2), Arrays
.asList(new GpuDevice(0, 0), new GpuDevice(1, 1), new GpuDevice(2, 3),
new GpuDevice(3, 4)));
- assertEquals("Number of GPU device allocations is not the expected!", 0,
- container.getResourceMappings()
- .getAssignedResources(ResourceInformation.GPU_URI).size());
+ assertEquals(0, container.getResourceMappings()
+ .getAssignedResources(ResourceInformation.GPU_URI).size(),
+ "Number of GPU device allocations is not the expected!");
// Store assigned resource will not be invoked.
verify(mockNMStateStore, never()).storeAssignedResources(
@@ -502,15 +498,14 @@ public void testRecoverResourceAllocation() throws Exception {
Map deviceAllocationMapping =
gpuResourceHandler.getGpuAllocator().getDeviceAllocationMapping();
- assertEquals("Unexpected number of allocated GPU devices!", 2,
- deviceAllocationMapping.size());
- assertTrue("Expected GPU device is not found in allocations!",
- deviceAllocationMapping.keySet().contains(new GpuDevice(1, 1)));
- assertTrue("Expected GPU device is not found in allocations!",
- deviceAllocationMapping.keySet().contains(new GpuDevice(2, 3)));
- assertEquals("GPU device is not assigned to the expected container!",
- deviceAllocationMapping.get(new GpuDevice(1, 1)),
- getContainerId(1));
+ assertEquals(2, deviceAllocationMapping.size(),
+ "Unexpected number of allocated GPU devices!");
+ assertTrue(deviceAllocationMapping.keySet().contains(new GpuDevice(1, 1)),
+ "Expected GPU device is not found in allocations!");
+ assertTrue(deviceAllocationMapping.keySet().contains(new GpuDevice(2, 3)),
+ "Expected GPU device is not found in allocations!");
+ assertEquals(deviceAllocationMapping.get(new GpuDevice(1, 1)),
+ getContainerId(1), "GPU device is not assigned to the expected container!");
// TEST CASE
// Try to reacquire a container but requested device is not in allowed list.
@@ -531,21 +526,19 @@ public void testRecoverResourceAllocation() throws Exception {
} catch (ResourceHandlerException e) {
caughtException = true;
}
- assertTrue(
- "Should fail since requested device Id is not in allowed list",
- caughtException);
+ assertTrue(caughtException,
+ "Should fail since requested device Id is not in allowed list");
// Make sure internal state not changed.
deviceAllocationMapping =
gpuResourceHandler.getGpuAllocator().getDeviceAllocationMapping();
- assertEquals("Unexpected number of allocated GPU devices!",
- 2, deviceAllocationMapping.size());
- assertTrue("Expected GPU devices are not found in allocations!",
- deviceAllocationMapping.keySet()
- .containsAll(Arrays.asList(new GpuDevice(1, 1), new GpuDevice(2, 3))));
- assertEquals("GPU device is not assigned to the expected container!",
- deviceAllocationMapping.get(new GpuDevice(1, 1)),
- getContainerId(1));
+ assertEquals(2, deviceAllocationMapping.size(),
+ "Unexpected number of allocated GPU devices!");
+ assertTrue(deviceAllocationMapping.keySet()
+ .containsAll(Arrays.asList(new GpuDevice(1, 1), new GpuDevice(2, 3))),
+ "Expected GPU devices are not found in allocations!");
+ assertEquals(deviceAllocationMapping.get(new GpuDevice(1, 1)),
+ getContainerId(1), "GPU device is not assigned to the expected container!");
// TEST CASE
// Try to reacquire a container but requested device is already assigned.
@@ -566,20 +559,19 @@ public void testRecoverResourceAllocation() throws Exception {
} catch (ResourceHandlerException e) {
caughtException = true;
}
- assertTrue(
- "Should fail since requested device Id is already assigned",
- caughtException);
+ assertTrue(caughtException,
+ "Should fail since requested device Id is already assigned");
// Make sure internal state not changed.
deviceAllocationMapping =
gpuResourceHandler.getGpuAllocator().getDeviceAllocationMapping();
- assertEquals("Unexpected number of allocated GPU devices!",
- 2, deviceAllocationMapping.size());
- assertTrue("Expected GPU devices are not found in allocations!",
- deviceAllocationMapping.keySet()
- .containsAll(Arrays.asList(new GpuDevice(1, 1), new GpuDevice(2, 3))));
- assertEquals("GPU device is not assigned to the expected container!",
- deviceAllocationMapping.get(new GpuDevice(1, 1)),
- getContainerId(1));
+ assertEquals(2, deviceAllocationMapping.size(),
+ "Unexpected number of allocated GPU devices!");
+ assertTrue(deviceAllocationMapping.keySet()
+ .containsAll(Arrays.asList(new GpuDevice(1, 1), new GpuDevice(2, 3))),
+ "Expected GPU devices are not found in allocations!");
+ assertEquals(deviceAllocationMapping.get(new GpuDevice(1, 1)),
+ getContainerId(1),
+ "GPU device is not assigned to the expected container!");
}
}
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceAllocator.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceAllocator.java
index 42c495c88f8f6..abaddf438676d 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceAllocator.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceAllocator.java
@@ -17,8 +17,8 @@
*/
package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.numa;
-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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -40,9 +40,8 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ResourceMappings;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ResourceMappings.AssignedResources;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test class for NumaResourceAllocator.
@@ -52,7 +51,7 @@ public class TestNumaResourceAllocator {
private Configuration conf;
private NumaResourceAllocator numaResourceAllocator;
- @Before
+ @BeforeEach
public void setUp() throws IOException, YarnException {
conf = new YarnConfiguration();
Context mockContext = mock(Context.class);
@@ -76,7 +75,7 @@ public void testReadNumaTopologyFromConfigurations() throws Exception {
Collection nodesList = numaResourceAllocator
.getNumaNodesList();
Collection expectedNodesList = getExpectedNumaNodesList();
- Assert.assertEquals(expectedNodesList, nodesList);
+ assertEquals(expectedNodesList, nodesList);
}
@Test
@@ -104,7 +103,7 @@ public String executeNGetCmdOutput(Configuration config)
Collection nodesList = numaResourceAllocator
.getNumaNodesList();
Collection expectedNodesList = getExpectedNumaNodesList();
- Assert.assertEquals(expectedNodesList, nodesList);
+ assertEquals(expectedNodesList, nodesList);
}
@Test
@@ -113,8 +112,8 @@ public void testAllocateNumaNode() throws Exception {
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048, 2)));
- Assert.assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
- Assert.assertEquals("0", String.join(",", nodeInfo.getCpuNodes()));
+ assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
+ assertEquals("0", String.join(",", nodeInfo.getCpuNodes()));
}
@Test
@@ -124,29 +123,29 @@ public void testAllocateNumaNodeWithRoundRobinFashionAssignment()
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048, 2)));
- Assert.assertEquals("0", String.join(",", nodeInfo1.getMemNodes()));
- Assert.assertEquals("0", String.join(",", nodeInfo1.getCpuNodes()));
+ assertEquals("0", String.join(",", nodeInfo1.getMemNodes()));
+ assertEquals("0", String.join(",", nodeInfo1.getCpuNodes()));
NumaResourceAllocation nodeInfo2 = numaResourceAllocator
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000002"),
Resource.newInstance(2048, 2)));
- Assert.assertEquals("1", String.join(",", nodeInfo2.getMemNodes()));
- Assert.assertEquals("1", String.join(",", nodeInfo2.getCpuNodes()));
+ assertEquals("1", String.join(",", nodeInfo2.getMemNodes()));
+ assertEquals("1", String.join(",", nodeInfo2.getCpuNodes()));
NumaResourceAllocation nodeInfo3 = numaResourceAllocator
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000003"),
Resource.newInstance(2048, 2)));
- Assert.assertEquals("0", String.join(",", nodeInfo3.getMemNodes()));
- Assert.assertEquals("0", String.join(",", nodeInfo3.getCpuNodes()));
+ assertEquals("0", String.join(",", nodeInfo3.getMemNodes()));
+ assertEquals("0", String.join(",", nodeInfo3.getCpuNodes()));
NumaResourceAllocation nodeInfo4 = numaResourceAllocator
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000003"),
Resource.newInstance(2048, 2)));
- Assert.assertEquals("1", String.join(",", nodeInfo4.getMemNodes()));
- Assert.assertEquals("1", String.join(",", nodeInfo4.getCpuNodes()));
+ assertEquals("1", String.join(",", nodeInfo4.getMemNodes()));
+ assertEquals("1", String.join(",", nodeInfo4.getCpuNodes()));
}
@Test
@@ -156,8 +155,8 @@ public void testAllocateNumaNodeWithMultipleNodesForMemory()
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(102400, 2)));
- Assert.assertEquals("0,1", String.join(",", nodeInfo.getMemNodes()));
- Assert.assertEquals("0", String.join(",", nodeInfo.getCpuNodes()));
+ assertEquals("0,1", String.join(",", nodeInfo.getMemNodes()));
+ assertEquals("0", String.join(",", nodeInfo.getCpuNodes()));
}
@Test
@@ -166,8 +165,8 @@ public void testAllocateNumaNodeWithMultipleNodesForCpus() throws Exception {
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048, 6)));
- Assert.assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
- Assert.assertEquals("0,1", String.join(",", nodeInfo.getCpuNodes()));
+ assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
+ assertEquals("0,1", String.join(",", nodeInfo.getCpuNodes()));
}
@Test
@@ -177,8 +176,8 @@ public void testAllocateNumaNodeWhenNoNumaMemResourcesAvailable()
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048000, 6)));
- Assert.assertNull("Should not assign numa nodes when there"
- + " are no sufficient memory resources available.", nodeInfo);
+ assertNull(nodeInfo, "Should not assign numa nodes when there"
+ + " are no sufficient memory resources available.");
}
@Test
@@ -188,8 +187,8 @@ public void testAllocateNumaNodeWhenNoNumaCpuResourcesAvailable()
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048, 600)));
- Assert.assertNull("Should not assign numa nodes when there"
- + " are no sufficient cpu resources available.", nodeInfo);
+ assertNull(nodeInfo, "Should not assign numa nodes when there"
+ + " are no sufficient cpu resources available.");
}
@Test
@@ -198,15 +197,15 @@ public void testReleaseNumaResourcess() throws Exception {
.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000001"),
Resource.newInstance(2048, 8)));
- Assert.assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
- Assert.assertEquals("0,1", String.join(",", nodeInfo.getCpuNodes()));
+ assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
+ assertEquals("0,1", String.join(",", nodeInfo.getCpuNodes()));
// Request the resource when all cpu nodes occupied
nodeInfo = numaResourceAllocator.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000002"),
Resource.newInstance(2048, 4)));
- Assert.assertNull("Should not assign numa nodes when there"
- + " are no sufficient cpu resources available.", nodeInfo);
+ assertNull(nodeInfo, "Should not assign numa nodes when there"
+ + " are no sufficient cpu resources available.");
// Release the resources
numaResourceAllocator.releaseNumaResource(
@@ -215,8 +214,8 @@ public void testReleaseNumaResourcess() throws Exception {
nodeInfo = numaResourceAllocator.allocateNumaNodes(getContainer(
ContainerId.fromString("container_1481156246874_0001_01_000003"),
Resource.newInstance(1024, 2)));
- Assert.assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
- Assert.assertEquals("0", String.join(",", nodeInfo.getCpuNodes()));
+ assertEquals("0", String.join(",", nodeInfo.getMemNodes()));
+ assertEquals("0", String.join(",", nodeInfo.getCpuNodes()));
}
@Test
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceHandlerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceHandlerImpl.java
index fcef088ce629c..a59256d52dbb9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceHandlerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/numa/TestNumaResourceHandlerImpl.java
@@ -17,8 +17,8 @@
*/
package org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.numa;
-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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -38,8 +38,8 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.privileged.PrivilegedOperation;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.resources.ResourceHandlerException;
import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test class for NumaResourceHandlerImpl.
@@ -51,7 +51,7 @@ public class TestNumaResourceHandlerImpl {
private NumaResourceHandlerImpl numaResourceHandler;
private Container mockContainer;
- @Before
+ @BeforeEach
public void setUp() throws IOException, ResourceHandlerException {
conf = new YarnConfiguration();
setNumaTopologyConfigs();
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDelegatingLinuxContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDelegatingLinuxContainerRuntime.java
index fdccff83856cc..94f2b3a87a804 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDelegatingLinuxContainerRuntime.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDelegatingLinuxContainerRuntime.java
@@ -21,13 +21,15 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntime;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeConstants;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test container runtime delegation.
@@ -38,7 +40,7 @@ public class TestDelegatingLinuxContainerRuntime {
private Configuration conf;
private Map env = new HashMap<>();
- @Before
+ @BeforeEach
public void setUp() throws Exception {
delegatingLinuxContainerRuntime = new DelegatingLinuxContainerRuntime();
conf = new Configuration();
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java
index 0e575f9ce2aa0..84f262438341f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/TestDockerContainerRuntime.java
@@ -57,14 +57,10 @@
import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerExecutionException;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeConstants;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.runtime.ContainerRuntimeContext;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.slf4j.Logger;
@@ -122,6 +118,10 @@
import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.OCIContainerRuntime.CONTAINER_PID_NAMESPACE_SUFFIX;
import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.OCIContainerRuntime.RUN_PRIVILEGED_CONTAINER_SUFFIX;
import static org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.OCIContainerRuntime.formatOciEnvKey;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
@@ -132,7 +132,6 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-@RunWith(Parameterized.class)
public class TestDockerContainerRuntime {
private static final Logger LOG =
LoggerFactory.getLogger(TestDockerContainerRuntime.class);
@@ -183,20 +182,19 @@ public class TestDockerContainerRuntime {
private final static String ENV_OCI_CONTAINER_RUN_PRIVILEGED_CONTAINER =
formatOciEnvKey(RUNTIME_TYPE, RUN_PRIVILEGED_CONTAINER_SUFFIX);
- @Rule
- public TemporaryFolder tempDir = new TemporaryFolder();
-
- @Parameterized.Parameters(name = "https={0}")
public static Collection