diff --git a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarListInfoTest.java b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarListInfoTest.java index 54a886ae225dcc..dbbf1eeda3dc36 100644 --- a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarListInfoTest.java +++ b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarListInfoTest.java @@ -18,13 +18,13 @@ package org.apache.flink.runtime.webmonitor.handlers; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.ArrayList; import java.util.List; /** Tests that the {@link JarListInfo} can be marshalled and unmarshalled. */ -public class JarListInfoTest extends RestResponseMarshallingTestBase { +class JarListInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JarListInfo.class; diff --git a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunRequestBodyTest.java b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunRequestBodyTest.java index f76464b15bfe3d..fb0258431dd53b 100644 --- a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunRequestBodyTest.java +++ b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunRequestBodyTest.java @@ -20,7 +20,7 @@ import org.apache.flink.api.common.JobID; import org.apache.flink.runtime.jobgraph.RestoreMode; -import org.apache.flink.runtime.rest.messages.RestRequestMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestRequestUnmarshallingTestBase; import java.util.Arrays; import java.util.Collections; @@ -28,7 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JarRunRequestBody}. */ -public class JarRunRequestBodyTest extends RestRequestMarshallingTestBase { +public class JarRunRequestBodyTest extends RestRequestUnmarshallingTestBase { @Override protected Class getTestRequestClass() { diff --git a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunResponseBodyTest.java b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunResponseBodyTest.java index 01ee02ffe23ac6..dbc5d16df04a64 100644 --- a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunResponseBodyTest.java +++ b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarRunResponseBodyTest.java @@ -19,12 +19,12 @@ package org.apache.flink.runtime.webmonitor.handlers; import org.apache.flink.api.common.JobID; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JarRunResponseBody}. */ -public class JarRunResponseBodyTest extends RestResponseMarshallingTestBase { +class JarRunResponseBodyTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarUploadResponseBodyTest.java b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarUploadResponseBodyTest.java index 3e1f7b0d3de1bf..53a6a4eccb2396 100644 --- a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarUploadResponseBodyTest.java +++ b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/handlers/JarUploadResponseBodyTest.java @@ -18,13 +18,13 @@ package org.apache.flink.runtime.webmonitor.handlers; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JarUploadResponseBody}. */ -public class JarUploadResponseBodyTest - extends RestResponseMarshallingTestBase { +class JarUploadResponseBodyTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobIdsWithStatusOverviewTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobIdsWithStatusOverviewTest.java index 5925b77e0cff83..38de4a4e65a8bf 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobIdsWithStatusOverviewTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobIdsWithStatusOverviewTest.java @@ -20,13 +20,13 @@ import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.JobStatus; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.Arrays; /** Marshalling test for the {@link JobIdsWithStatusOverview} message. */ -public class JobIdsWithStatusOverviewTest - extends RestResponseMarshallingTestBase { +class JobIdsWithStatusOverviewTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobStatusInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobStatusInfoTest.java index 93afec08cccc72..77188f3d19e431 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobStatusInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/messages/webmonitor/JobStatusInfoTest.java @@ -19,10 +19,10 @@ package org.apache.flink.runtime.messages.webmonitor; import org.apache.flink.api.common.JobStatus; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; /** Tests for the {@link JobStatusInfo}. */ -public class JobStatusInfoTest extends RestResponseMarshallingTestBase { +class JobStatusInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobStatusInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestClientTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestClientTest.java index f85117cfb5033e..f1d8c5f349c41a 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestClientTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestClientTest.java @@ -27,10 +27,9 @@ import org.apache.flink.runtime.rest.messages.RuntimeMessageHeaders; import org.apache.flink.runtime.rest.versioning.RuntimeRestAPIVersion; import org.apache.flink.testutils.TestingUtils; -import org.apache.flink.testutils.executor.TestExecutorResource; +import org.apache.flink.testutils.executor.TestExecutorExtension; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.util.NetUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; import org.apache.flink.util.function.CheckedSupplier; @@ -41,10 +40,8 @@ import org.apache.flink.shaded.netty4.io.netty.channel.SelectStrategyFactory; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.function.ThrowingRunnable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; import java.net.ServerSocket; @@ -56,26 +53,21 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** Tests for {@link RestClient}. */ -public class RestClientTest extends TestLogger { - @ClassRule - public static final TestExecutorResource EXECUTOR_RESOURCE = - TestingUtils.defaultExecutorResource(); +class RestClientTest { + @RegisterExtension + static final TestExecutorExtension EXECUTOR_RESOURCE = + TestingUtils.defaultExecutorExtension(); private static final String unroutableIp = "240.0.0.0"; private static final long TIMEOUT = 10L; @Test - public void testConnectionTimeout() throws Exception { + void testConnectionTimeout() throws Exception { final Configuration config = new Configuration(); config.setLong(RestOptions.CONNECTION_TIMEOUT, 1); try (final RestClient restClient = new RestClient(config, Executors.directExecutor())) { @@ -87,14 +79,19 @@ public void testConnectionTimeout() throws Exception { EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance()); - final Throwable cause = assertThrows(ExecutionException.class, future::get).getCause(); - assertThat(cause, instanceOf(ConnectTimeoutException.class)); - assertThat(cause.getMessage(), containsString(unroutableIp)); + try { + future.get(); + fail("Expected exception not thrown."); + } catch (ExecutionException e) { + final Throwable cause = e.getCause(); + assertThat(cause).isInstanceOf(ConnectTimeoutException.class); + assertThat(cause.getMessage()).contains(unroutableIp); + } } } @Test - public void testInvalidVersionRejection() throws Exception { + void testInvalidVersionRejection() throws Exception { try (final RestClient restClient = new RestClient(new Configuration(), Executors.directExecutor())) { CompletableFuture invalidVersionResponse = @@ -106,7 +103,7 @@ public void testInvalidVersionRejection() throws Exception { EmptyRequestBody.getInstance(), Collections.emptyList(), RuntimeRestAPIVersion.V0); - Assert.fail("The request should have been rejected due to a version mismatch."); + fail("Expected exception not thrown."); } catch (IllegalArgumentException e) { // expected } @@ -114,7 +111,7 @@ public void testInvalidVersionRejection() throws Exception { /** Tests that we fail the operation if the remote connection closes. */ @Test - public void testConnectionClosedHandling() throws Exception { + void testConnectionClosedHandling() throws Exception { final Configuration config = new Configuration(); config.setLong(RestOptions.IDLENESS_TIMEOUT, 5000L); try (final ServerSocket serverSocket = new ServerSocket(0); @@ -165,7 +162,7 @@ public void testConnectionClosedHandling() throws Exception { /** Tests that we fail the operation if the client closes. */ @Test - public void testRestClientClosedHandling() throws Exception { + void testRestClientClosedHandling() throws Exception { final Configuration config = new Configuration(); config.setLong(RestOptions.IDLENESS_TIMEOUT, 5000L); @@ -223,7 +220,7 @@ public void testRestClientClosedHandling() throws Exception { *

See FLINK-32583 */ @Test - public void testCloseClientBeforeRequest() throws Exception { + void testCloseClientBeforeRequest() throws Exception { try (final RestClient restClient = new RestClient(new Configuration(), Executors.directExecutor())) { restClient.close(); // Intentionally close the client prior to the request @@ -236,19 +233,22 @@ public void testCloseClientBeforeRequest() throws Exception { EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance()); - // Call get() on the future with a timeout of 0s so we can test that the exception - // thrown is not a TimeoutException, which is what would be thrown if restClient were - // not already closed - final ThrowingRunnable getFuture = () -> future.get(0, TimeUnit.SECONDS); - - final Throwable cause = assertThrows(ExecutionException.class, getFuture).getCause(); - assertThat(cause, instanceOf(IllegalStateException.class)); - assertThat(cause.getMessage(), equalTo("RestClient is already closed")); + try { + // Call get() on the future with a timeout of 0s so we can test that the exception + // thrown is not a TimeoutException, which is what would be thrown if restClient + // were not already closed + future.get(0, TimeUnit.SECONDS); + fail("Expected exception not thrown."); + } catch (ExecutionException e) { + final Throwable cause = e.getCause(); + assertThat(cause).isInstanceOf(IllegalStateException.class); + assertThat(cause.getMessage()).isEqualTo("RestClient is already closed"); + } } } @Test - public void testCloseClientWhileProcessingRequest() throws Exception { + void testCloseClientWhileProcessingRequest() throws Exception { // Set up a Netty SelectStrategy with latches that allow us to step forward through Netty's // request state machine, closing the client at a particular moment final OneShotLatch connectTriggered = new OneShotLatch(); @@ -270,7 +270,7 @@ public void testCloseClientWhileProcessingRequest() throws Exception { new Configuration(), Executors.directExecutor(), selectStrategyFactory)) { // Check that client's internal collection of pending response futures is empty prior to // the request - assertThat(restClient.getResponseChannelFutures(), empty()); + assertThat(restClient.getResponseChannelFutures()).isEmpty(); final CompletableFuture requestFuture = restClient.sendRequest( @@ -282,7 +282,7 @@ public void testCloseClientWhileProcessingRequest() throws Exception { // Check that client's internal collection of pending response futures now has one // entry, presumably due to the call to sendRequest - assertThat(restClient.getResponseChannelFutures(), hasSize(1)); + assertThat(restClient.getResponseChannelFutures()).hasSize(1); // Wait for Netty to start connecting, then while it's paused in the SelectStrategy, // close the client before unpausing Netty @@ -293,18 +293,19 @@ public void testCloseClientWhileProcessingRequest() throws Exception { // Close should complete successfully closeFuture.get(); - final Throwable cause = - assertThrows( - ExecutionException.class, - () -> requestFuture.get(0, TimeUnit.SECONDS)) - .getCause(); - assertThat(cause, instanceOf(IllegalStateException.class)); - assertThat(cause.getMessage(), equalTo("executor not accepting a task")); + try { + requestFuture.get(0, TimeUnit.SECONDS); + fail("Expected exception not thrown."); + } catch (ExecutionException e) { + final Throwable cause = e.getCause(); + assertThat(cause).isInstanceOf(IllegalStateException.class); + assertThat(cause.getMessage()).isEqualTo("executor not accepting a task"); + } } } @Test - public void testResponseChannelFuturesResolvedExceptionallyOnClose() throws Exception { + void testResponseChannelFuturesResolvedExceptionallyOnClose() throws Exception { try (final RestClient restClient = new RestClient(new Configuration(), Executors.directExecutor())) { CompletableFuture responseChannelFuture = new CompletableFuture<>(); @@ -318,15 +319,17 @@ public void testResponseChannelFuturesResolvedExceptionallyOnClose() throws Exce // Ensure the client's internal collection of pending response futures was cleared after // close - assertThat(restClient.getResponseChannelFutures(), empty()); - - final Throwable cause = - assertThrows( - ExecutionException.class, - () -> responseChannelFuture.get(0, TimeUnit.SECONDS)) - .getCause(); - assertThat(cause, instanceOf(IllegalStateException.class)); - assertThat(cause.getMessage(), equalTo("RestClient closed before request completed")); + assertThat(restClient.getResponseChannelFutures()).isEmpty(); + + try { + responseChannelFuture.get(0, TimeUnit.SECONDS); + fail("Expected exception not thrown."); + } catch (ExecutionException e) { + final Throwable cause = e.getCause(); + assertThat(cause).isInstanceOf(IllegalStateException.class); + assertThat(cause.getMessage()) + .isEqualTo("RestClient closed before request completed"); + } } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestExternalHandlersITCase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestExternalHandlersITCase.java index 0509a15088ff06..d99aedb7a5e41c 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestExternalHandlersITCase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestExternalHandlersITCase.java @@ -33,14 +33,12 @@ import org.apache.flink.testutils.TestingUtils; import org.apache.flink.testutils.executor.TestExecutorExtension; import org.apache.flink.testutils.junit.extensions.ContextClassLoaderExtension; -import org.apache.flink.util.TestLoggerExtension; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.Extension; import org.junit.jupiter.api.extension.RegisterExtension; @@ -51,12 +49,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; -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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** IT cases for {@link RestClient} and {@link RestServerEndpoint}. */ -@ExtendWith(TestLoggerExtension.class) class RestExternalHandlersITCase { private static final Time timeout = Time.seconds(10L); @@ -128,21 +124,19 @@ void teardown() throws Exception { void testHandlersMustBeLoaded() { final List inboundChannelHandlerFactories = serverEndpoint.getInboundChannelHandlerFactories(); - assertEquals(inboundChannelHandlerFactories.size(), 2); - assertTrue( - inboundChannelHandlerFactories.get(0) instanceof Prio1InboundChannelHandlerFactory); - assertTrue( - inboundChannelHandlerFactories.get(1) instanceof Prio0InboundChannelHandlerFactory); + assertThat(inboundChannelHandlerFactories.size()).isEqualTo(2); + assertThat(inboundChannelHandlerFactories.get(0)) + .isInstanceOf(Prio1InboundChannelHandlerFactory.class); + assertThat(inboundChannelHandlerFactories.get(1)) + .isInstanceOf(Prio0InboundChannelHandlerFactory.class); final List outboundChannelHandlerFactories = restClient.getOutboundChannelHandlerFactories(); - assertEquals(outboundChannelHandlerFactories.size(), 2); - assertTrue( - outboundChannelHandlerFactories.get(0) - instanceof Prio1OutboundChannelHandlerFactory); - assertTrue( - outboundChannelHandlerFactories.get(1) - instanceof Prio0OutboundChannelHandlerFactory); + assertThat(outboundChannelHandlerFactories.size()).isEqualTo(2); + assertThat(outboundChannelHandlerFactories.get(0)) + .isInstanceOf(Prio1OutboundChannelHandlerFactory.class); + assertThat(outboundChannelHandlerFactories.get(1)) + .isInstanceOf(Prio0OutboundChannelHandlerFactory.class); try { final CompletableFuture response = @@ -150,7 +144,7 @@ void testHandlersMustBeLoaded() { response.get(); fail("Request must fail with 2 times redirected URL"); } catch (Exception e) { - assertTrue(e.getMessage().contains(REDIRECT2_URL)); + assertThat(e.getMessage().contains(REDIRECT2_URL)).isTrue(); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointConfigurationTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointConfigurationTest.java index 3fe95addd4d3c0..9d0192bb77d0ba 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointConfigurationTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointConfigurationTest.java @@ -22,42 +22,38 @@ import org.apache.flink.configuration.RestOptions; import org.apache.flink.configuration.WebOptions; import org.apache.flink.util.ConfigurationException; -import org.apache.flink.util.TestLogger; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import static org.hamcrest.CoreMatchers.containsString; +import java.io.File; + +import static org.assertj.core.api.Assertions.assertThat; /** Tests for the {@link RestServerEndpointConfiguration}. */ -public class RestServerEndpointConfigurationTest extends TestLogger { +class RestServerEndpointConfigurationTest { private static final String ADDRESS = "123.123.123.123"; private static final String BIND_ADDRESS = "023.023.023.023"; private static final String BIND_PORT = "7282"; private static final int CONTENT_LENGTH = 1234; - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Test - public void testBasicMapping() throws ConfigurationException { + void testBasicMapping(@TempDir File temporaryFolder) throws ConfigurationException { Configuration originalConfig = new Configuration(); originalConfig.setString(RestOptions.ADDRESS, ADDRESS); originalConfig.setString(RestOptions.BIND_ADDRESS, BIND_ADDRESS); originalConfig.setString(RestOptions.BIND_PORT, BIND_PORT); originalConfig.setInteger(RestOptions.SERVER_MAX_CONTENT_LENGTH, CONTENT_LENGTH); - originalConfig.setString(WebOptions.TMP_DIR, temporaryFolder.getRoot().getAbsolutePath()); + originalConfig.setString(WebOptions.TMP_DIR, temporaryFolder.getAbsolutePath()); final RestServerEndpointConfiguration result = RestServerEndpointConfiguration.fromConfiguration(originalConfig); - Assert.assertEquals(ADDRESS, result.getRestAddress()); - Assert.assertEquals(BIND_ADDRESS, result.getRestBindAddress()); - Assert.assertEquals(BIND_PORT, result.getRestBindPortRange()); - Assert.assertEquals(CONTENT_LENGTH, result.getMaxContentLength()); - Assert.assertThat( - result.getUploadDir().toAbsolutePath().toString(), - containsString(temporaryFolder.getRoot().getAbsolutePath())); + assertThat(result.getRestAddress()).isEqualTo(ADDRESS); + assertThat(result.getRestBindAddress()).isEqualTo(BIND_ADDRESS); + assertThat(result.getRestBindPortRange()).isEqualTo(BIND_PORT); + assertThat(result.getMaxContentLength()).isEqualTo(CONTENT_LENGTH); + assertThat(result.getUploadDir().toAbsolutePath().toString()) + .contains(temporaryFolder.getAbsolutePath()); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointITCase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointITCase.java index 06ee7017a6c9ba..09e04092769298 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointITCase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointITCase.java @@ -54,10 +54,11 @@ import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; import org.apache.flink.testutils.TestingUtils; -import org.apache.flink.testutils.executor.TestExecutorResource; +import org.apache.flink.testutils.executor.TestExecutorExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.util.FlinkRuntimeException; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator; @@ -69,15 +70,12 @@ import okhttp3.Request; import okhttp3.Response; import org.apache.commons.io.IOUtils; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.ClassRule; -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.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; import javax.annotation.Nonnull; import javax.net.ssl.HttpsURLConnection; @@ -109,22 +107,13 @@ import static java.util.Objects.requireNonNull; import static org.apache.flink.core.testutils.CommonTestUtils.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** IT cases for {@link RestClient} and {@link RestServerEndpoint}. */ -@RunWith(Parameterized.class) -public class RestServerEndpointITCase extends TestLogger { +@ExtendWith(ParameterizedTestExtension.class) +public class RestServerEndpointITCase { private static final JobID PATH_JOB_ID = new JobID(); private static final JobID QUERY_JOB_ID = new JobID(); @@ -132,11 +121,9 @@ public class RestServerEndpointITCase extends TestLogger { private static final Time timeout = Time.seconds(10L); private static final int TEST_REST_MAX_CONTENT_LENGTH = 4096; - @ClassRule - public static final TestExecutorResource EXECUTOR_RESOURCE = - TestingUtils.defaultExecutorResource(); - - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @RegisterExtension + public static final TestExecutorExtension EXECUTOR_RESOURCE = + TestingUtils.defaultExecutorExtension(); private RestServerEndpoint serverEndpoint; private RestClient restClient; @@ -153,7 +140,7 @@ public RestServerEndpointITCase(final Configuration config) { this.config = requireNonNull(config); } - @Parameterized.Parameters + @Parameters public static Collection data() throws Exception { final Configuration config = getBaseConfig(); @@ -194,9 +181,9 @@ private static Configuration getBaseConfig() { return config; } - @Before - public void setup() throws Exception { - config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath()); + @BeforeEach + void setup(@TempDir File temporaryFolder) throws Exception { + config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.getCanonicalPath()); defaultSSLContext = SSLContext.getDefault(); defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); @@ -238,7 +225,7 @@ public void setup() throws Exception { final StaticFileServerHandler staticFileServerHandler = new StaticFileServerHandler<>( - mockGatewayRetriever, RpcUtils.INF_TIMEOUT, temporaryFolder.getRoot()); + mockGatewayRetriever, RpcUtils.INF_TIMEOUT, temporaryFolder); serverEndpoint = TestRestServerEndpoint.builder(config) @@ -257,8 +244,8 @@ public void setup() throws Exception { serverAddress = serverEndpoint.getServerAddress(); } - @After - public void teardown() throws Exception { + @AfterEach + void teardown() throws Exception { if (defaultSSLContext != null) { SSLContext.setDefault(defaultSSLContext); HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory); @@ -280,7 +267,7 @@ public void teardown() throws Exception { * This means that request responses can overtake each other. */ @Test - public void testRequestInterleaving() throws Exception { + void testRequestInterleaving() throws Exception { final BlockerSync sync = new BlockerSync(); testHandler.handlerBody = id -> { @@ -302,13 +289,13 @@ public void testRequestInterleaving() throws Exception { // send second request and verify response final CompletableFuture response2 = sendRequestToTestHandler(new TestRequest(2)); - assertEquals(2, response2.get().id); + assertThat(response2.get().id).isEqualTo(2); // wake up blocked handler sync.releaseBlocker(); // verify response to first request - assertEquals(1, response1.get().id); + assertThat(response1.get().id).isOne(); } /** @@ -318,7 +305,7 @@ public void testRequestInterleaving() throws Exception { *

See FLINK-7663 */ @Test - public void testBadHandlerRequest() throws Exception { + void testBadHandlerRequest() throws Exception { final FaultyTestParameters parameters = new FaultyTestParameters(); parameters.faultyJobIDPathParameter.resolve(PATH_JOB_ID); @@ -340,17 +327,17 @@ public void testBadHandlerRequest() throws Exception { } catch (ExecutionException ee) { Throwable t = ExceptionUtils.stripExecutionException(ee); - assertTrue(t instanceof RestClientException); + assertThat(t instanceof RestClientException).isTrue(); RestClientException rce = (RestClientException) t; - assertEquals(HttpResponseStatus.BAD_REQUEST, rce.getHttpResponseStatus()); + assertThat(rce.getHttpResponseStatus()).isEqualTo(HttpResponseStatus.BAD_REQUEST); } } /** Tests that requests larger than {@link #TEST_REST_MAX_CONTENT_LENGTH} are rejected. */ @Test - public void testShouldRespectMaxContentLengthLimitForRequests() throws Exception { + void testShouldRespectMaxContentLengthLimitForRequests() throws Exception { testHandler.handlerBody = id -> { throw new AssertionError("Request should not arrive at server."); @@ -363,14 +350,14 @@ public void testShouldRespectMaxContentLengthLimitForRequests() throws Exception fail("Expected exception not thrown"); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripExecutionException(e); - assertThat(throwable, instanceOf(RestClientException.class)); - assertThat(throwable.getMessage(), containsString("Try to raise")); + assertThat(throwable).isInstanceOf(RestClientException.class); + assertThat(throwable.getMessage()).contains("Try to raise"); } } /** Tests that responses larger than {@link #TEST_REST_MAX_CONTENT_LENGTH} are rejected. */ @Test - public void testShouldRespectMaxContentLengthLimitForResponses() throws Exception { + void testShouldRespectMaxContentLengthLimitForResponses() throws Exception { testHandler.handlerBody = id -> CompletableFuture.completedFuture( @@ -382,8 +369,8 @@ public void testShouldRespectMaxContentLengthLimitForResponses() throws Exceptio fail("Expected exception not thrown"); } catch (final ExecutionException e) { final Throwable throwable = ExceptionUtils.stripExecutionException(e); - assertThat(throwable, instanceOf(TooLongFrameException.class)); - assertThat(throwable.getMessage(), containsString("Try to raise")); + assertThat(throwable).isInstanceOf(TooLongFrameException.class); + assertThat(throwable.getMessage()).contains("Try to raise"); } } @@ -393,7 +380,7 @@ public void testShouldRespectMaxContentLengthLimitForResponses() throws Exceptio * @see FileUploadHandler */ @Test - public void testFileUpload() throws Exception { + void testFileUpload() throws Exception { final String boundary = generateMultiPartBoundary(); final String crlf = "\r\n"; final String uploadedContent = "hello"; @@ -415,9 +402,10 @@ public void testFileUpload() throws Exception { writer.append("--" + boundary + "--").append(crlf).flush(); } - assertEquals(200, connection.getResponseCode()); + assertThat(connection.getResponseCode()).isEqualTo(200); final byte[] lastUploadedFileContents = testUploadHandler.getLastUploadedFileContents(); - assertEquals(uploadedContent, new String(lastUploadedFileContents, StandardCharsets.UTF_8)); + assertThat(uploadedContent) + .isEqualTo(new String(lastUploadedFileContents, StandardCharsets.UTF_8)); } /** @@ -425,7 +413,7 @@ public void testFileUpload() throws Exception { * expects a file upload. */ @Test - public void testMultiPartFormDataWithoutFileUpload() throws Exception { + void testMultiPartFormDataWithoutFileUpload() throws Exception { final String boundary = generateMultiPartBoundary(); final String crlf = "\r\n"; final HttpURLConnection connection = openHttpConnectionForUpload(boundary); @@ -444,13 +432,12 @@ public void testMultiPartFormDataWithoutFileUpload() throws Exception { writer.append("--" + boundary + "--").append(crlf).flush(); } - assertEquals(400, connection.getResponseCode()); + assertThat(connection.getResponseCode()).isEqualTo(400); } /** Tests that files can be served with the {@link StaticFileServerHandler}. */ @Test - public void testStaticFileServerHandler() throws Exception { - final File file = temporaryFolder.newFile(); + void testStaticFileServerHandler(@TempDir File file) throws Exception { Files.write(file.toPath(), Collections.singletonList("foobar")); final URL url = new URL(serverEndpoint.getRestBaseUrl() + "/" + file.getName()); @@ -458,11 +445,11 @@ public void testStaticFileServerHandler() throws Exception { connection.setRequestMethod("GET"); final String fileContents = IOUtils.toString(connection.getInputStream()); - assertEquals("foobar", fileContents.trim()); + assertThat(fileContents.trim()).isEqualTo("foobar"); } @Test - public void testVersioning() throws Exception { + void testVersioning() throws Exception { CompletableFuture unspecifiedVersionResponse = restClient.sendRequest( serverAddress.getHostName(), @@ -488,7 +475,7 @@ public void testVersioning() throws Exception { } @Test - public void testVersionSelection() throws Exception { + void testVersionSelection() throws Exception { CompletableFuture version1Response = restClient.sendRequest( serverAddress.getHostName(), @@ -501,10 +488,10 @@ public void testVersionSelection() throws Exception { try { version1Response.get(5, TimeUnit.SECONDS); - fail(); + fail("Expected exception not thrown"); } catch (ExecutionException ee) { RestClientException rce = (RestClientException) ee.getCause(); - assertEquals(HttpResponseStatus.OK, rce.getHttpResponseStatus()); + assertThat(rce.getHttpResponseStatus()).isEqualTo(HttpResponseStatus.OK); } CompletableFuture version2Response = @@ -519,18 +506,18 @@ public void testVersionSelection() throws Exception { try { version2Response.get(5, TimeUnit.SECONDS); - fail(); + fail("Expected exception not thrown"); } catch (ExecutionException ee) { RestClientException rce = (RestClientException) ee.getCause(); - assertEquals(HttpResponseStatus.ACCEPTED, rce.getHttpResponseStatus()); + assertThat(rce.getHttpResponseStatus()).isEqualTo(HttpResponseStatus.ACCEPTED); } } @Test - public void testDefaultVersionRouting() throws Exception { - Assume.assumeFalse( - "Ignoring SSL-enabled test to keep OkHttp usage simple.", - config.getBoolean(SecurityOptions.SSL_REST_ENABLED)); + void testDefaultVersionRouting() throws Exception { + assertThat(config.getBoolean(SecurityOptions.SSL_REST_ENABLED)) + .as("Ignoring SSL-enabled test to keep OkHttp usage simple.") + .isFalse(); OkHttpClient client = new OkHttpClient(); @@ -543,21 +530,21 @@ public void testDefaultVersionRouting() throws Exception { .build(); try (final Response response = client.newCall(request).execute()) { - assertEquals(HttpResponseStatus.ACCEPTED.code(), response.code()); + assertThat(response.code()).isEqualTo(HttpResponseStatus.ACCEPTED.code()); } } @Test - public void testNonSslRedirectForEnabledSsl() throws Exception { - Assume.assumeTrue(config.getBoolean(SecurityOptions.SSL_REST_ENABLED)); + void testNonSslRedirectForEnabledSsl() throws Exception { + assertThat(config.getBoolean(SecurityOptions.SSL_REST_ENABLED)).isTrue(); OkHttpClient client = new OkHttpClient.Builder().followRedirects(false).build(); String httpsUrl = serverEndpoint.getRestBaseUrl() + "/path"; String httpUrl = httpsUrl.replace("https://", "http://"); Request request = new Request.Builder().url(httpUrl).build(); try (final Response response = client.newCall(request).execute()) { - assertEquals(HttpResponseStatus.MOVED_PERMANENTLY.code(), response.code()); - assertThat(response.headers().names(), hasItems("location")); - assertEquals(httpsUrl, response.header("location")); + assertThat(response.code()).isEqualTo(HttpResponseStatus.MOVED_PERMANENTLY.code()); + assertThat(response.headers().names()).contains("location"); + assertThat(response.header("location")).isEqualTo(httpsUrl); } } @@ -567,7 +554,7 @@ public void testNonSslRedirectForEnabledSsl() throws Exception { * HTTP requests should be served. */ @Test - public void testShouldWaitForHandlersWhenClosing() throws Exception { + void testShouldWaitForHandlersWhenClosing() throws Exception { testHandler.closeFuture = new CompletableFuture<>(); final BlockerSync sync = new BlockerSync(); testHandler.handlerBody = @@ -587,7 +574,7 @@ public void testShouldWaitForHandlersWhenClosing() throws Exception { // Initiate closing RestServerEndpoint but the test handler should block. final CompletableFuture closeRestServerEndpointFuture = serverEndpoint.closeAsync(); - assertThat(closeRestServerEndpointFuture.isDone(), is(false)); + assertThat(closeRestServerEndpointFuture).isNotDone(); // create an in-flight request final CompletableFuture request = @@ -597,7 +584,7 @@ public void testShouldWaitForHandlersWhenClosing() throws Exception { // Allow handler to close but there is still one in-flight request which should prevent // the RestServerEndpoint from closing. testHandler.closeFuture.complete(null); - assertThat(closeRestServerEndpointFuture.isDone(), is(false)); + assertThat(closeRestServerEndpointFuture).isNotDone(); // Finish the in-flight request. sync.releaseBlocker(); @@ -608,7 +595,7 @@ public void testShouldWaitForHandlersWhenClosing() throws Exception { /** Tests that new requests are ignored after a handler is shut down. */ @Test - public void testRequestsRejectedAfterShutdownOfHandlerIsCompleted() throws Exception { + void testRequestsRejectedAfterShutdownOfHandlerIsCompleted() throws Exception { testHandler.handlerBody = id -> CompletableFuture.completedFuture(new TestResponse(id, "foobar")); @@ -617,7 +604,7 @@ public void testRequestsRejectedAfterShutdownOfHandlerIsCompleted() throws Excep final CompletableFuture closeRestServerEndpointFuture = serverEndpoint.closeAsync(); - assertThat(closeRestServerEndpointFuture.isDone(), is(false)); + assertThat(closeRestServerEndpointFuture).isNotDone(); // wait until the TestHandler is closed testHandler.closeLatch.await(); @@ -640,7 +627,7 @@ public void testRequestsRejectedAfterShutdownOfHandlerIsCompleted() throws Excep } @Test - public void testRestServerBindPort() throws Exception { + void testRestServerBindPort() throws Exception { final int portRangeStart = 52300; final int portRangeEnd = 52400; final Configuration config = new Configuration(); @@ -654,28 +641,23 @@ public void testRestServerBindPort() throws Exception { serverEndpoint1.start(); serverEndpoint2.start(); - assertNotEquals( - serverEndpoint1.getServerAddress().getPort(), - serverEndpoint2.getServerAddress().getPort()); + assertThat(serverEndpoint1.getServerAddress().getPort()) + .isNotEqualTo(serverEndpoint2.getServerAddress().getPort()); - assertThat( - serverEndpoint1.getServerAddress().getPort(), - is(greaterThanOrEqualTo(portRangeStart))); - assertThat( - serverEndpoint1.getServerAddress().getPort(), - is(lessThanOrEqualTo(portRangeEnd))); + assertThat(serverEndpoint1.getServerAddress().getPort()) + .isGreaterThanOrEqualTo(portRangeStart); + assertThat(serverEndpoint1.getServerAddress().getPort()) + .isLessThanOrEqualTo(portRangeEnd); - assertThat( - serverEndpoint2.getServerAddress().getPort(), - is(greaterThanOrEqualTo(portRangeStart))); - assertThat( - serverEndpoint2.getServerAddress().getPort(), - is(lessThanOrEqualTo(portRangeEnd))); + assertThat(serverEndpoint2.getServerAddress().getPort()) + .isGreaterThanOrEqualTo(portRangeStart); + assertThat(serverEndpoint2.getServerAddress().getPort()) + .isLessThanOrEqualTo(portRangeEnd); } } @Test - public void testEndpointsMustBeUnique() throws Exception { + void testEndpointsMustBeUnique() throws Exception { assertThrows( "REST handler registration", FlinkRuntimeException.class, @@ -692,7 +674,7 @@ public void testEndpointsMustBeUnique() throws Exception { } @Test - public void testDuplicateHandlerRegistrationIsForbidden() throws Exception { + void testDuplicateHandlerRegistrationIsForbidden() throws Exception { assertThrows( "Duplicate REST handler", FlinkRuntimeException.class, @@ -709,7 +691,7 @@ public void testDuplicateHandlerRegistrationIsForbidden() throws Exception { } @Test - public void testOnUnavailableRpcEndpointReturns503() throws IOException { + void testOnUnavailableRpcEndpointReturns503() throws IOException { CompletableFuture response = restClient.sendRequest( serverAddress.getHostName(), @@ -771,8 +753,9 @@ private static class TestHandler @Override protected CompletableFuture handleRequest( @Nonnull HandlerRequest request, RestfulGateway gateway) { - assertEquals(request.getPathParameter(JobIDPathParameter.class), PATH_JOB_ID); - assertEquals(request.getQueryParameter(JobIDQueryParameter.class).get(0), QUERY_JOB_ID); + assertThat(PATH_JOB_ID).isEqualTo(request.getPathParameter(JobIDPathParameter.class)); + assertThat(QUERY_JOB_ID) + .isEqualTo(request.getQueryParameter(JobIDQueryParameter.class).get(0)); final int id = request.getRequestBody().id; return handlerBody.apply(id); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointTest.java index 8ff85020c2554d..23254eac9abc51 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerEndpointTest.java @@ -18,12 +18,8 @@ package org.apache.flink.runtime.rest; -import org.apache.flink.util.TestLogger; - -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.slf4j.helpers.NOPLogger; import java.io.File; @@ -34,19 +30,15 @@ import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** Test cases for the {@link RestServerEndpoint}. */ -public class RestServerEndpointTest extends TestLogger { - - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); +class RestServerEndpointTest { /** Tests that the REST handler URLs are properly sorted. */ @Test - public void testRestHandlerUrlSorting() { + void testRestHandlerUrlSorting() { final int numberHandlers = 5; final List handlerUrls = new ArrayList<>(numberHandlers); @@ -69,25 +61,23 @@ public void testRestHandlerUrlSorting() { handlerUrls, new RestServerEndpoint.RestHandlerUrlComparator.CaseInsensitiveOrderComparator()); - assertEquals(expected, handlerUrls); + assertThat(handlerUrls).isEqualTo(expected); } @Test - public void testCreateUploadDir() throws Exception { - final File file = temporaryFolder.newFolder(); + void testCreateUploadDir(@TempDir File file) throws Exception { final Path testUploadDir = file.toPath().resolve("testUploadDir"); - assertFalse(Files.exists(testUploadDir)); + assertThat(Files.exists(testUploadDir)).isFalse(); RestServerEndpoint.createUploadDir(testUploadDir, NOPLogger.NOP_LOGGER, true); - assertTrue(Files.exists(testUploadDir)); + assertThat(Files.exists(testUploadDir)).isTrue(); } @Test - public void testCreateUploadDirFails() throws Exception { - final File file = temporaryFolder.newFolder(); - Assume.assumeTrue(file.setWritable(false)); + void testCreateUploadDirFails(@TempDir File file) throws Exception { + assertThat(file.setWritable(false)); final Path testUploadDir = file.toPath().resolve("testUploadDir"); - assertFalse(Files.exists(testUploadDir)); + assertThat(Files.exists(testUploadDir)).isFalse(); try { RestServerEndpoint.createUploadDir(testUploadDir, NOPLogger.NOP_LOGGER, true); fail("Expected exception not thrown."); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerSSLAuthITCase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerSSLAuthITCase.java index eaad8caadb4e88..5753b1a8e3c16c 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerSSLAuthITCase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/RestServerSSLAuthITCase.java @@ -31,13 +31,13 @@ import org.apache.flink.runtime.rpc.RpcUtils; import org.apache.flink.runtime.webmonitor.RestfulGateway; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; import org.apache.flink.util.ExceptionUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import javax.net.ssl.SSLException; @@ -48,15 +48,15 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * This test validates that connections are failing when mutual auth is enabled but untrusted keys * or fingerprints are used. */ -@RunWith(Parameterized.class) -public class RestServerSSLAuthITCase extends TestLogger { +@ExtendWith(ParameterizedTestExtension.class) +class RestServerSSLAuthITCase { private static final String KEY_STORE_FILE = RestServerSSLAuthITCase.class.getResource("/local127.keystore").getFile(); @@ -75,7 +75,7 @@ public RestServerSSLAuthITCase(final Tuple2 client this.serverConfig = clientServerConfig.f1; } - @Parameterized.Parameters + @Parameters public static Collection data() throws Exception { // client and server trust store does not match Tuple2 untrusted = getClientServerConfiguration(); @@ -100,7 +100,7 @@ public static Collection data() throws Exception { } @Test - public void testConnectFailure() throws Exception { + void testConnectFailure() throws Exception { RestClient restClient = null; RestServerEndpoint serverEndpoint = null; @@ -130,7 +130,8 @@ public void testConnectFailure() throws Exception { fail("should never complete normally"); } catch (ExecutionException exception) { // that is what we want - assertTrue(ExceptionUtils.findThrowable(exception, SSLException.class).isPresent()); + assertThat(ExceptionUtils.findThrowable(exception, SSLException.class).isPresent()) + .isTrue(); } finally { if (restClient != null) { restClient.shutdown(timeout); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/AbstractHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/AbstractHandlerTest.java index 36bdc38f71cd59..0614a2943834aa 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/AbstractHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/AbstractHandlerTest.java @@ -38,7 +38,6 @@ import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; import org.apache.flink.util.ConfigurationException; -import org.apache.flink.util.TestLoggerExtension; import org.apache.flink.util.concurrent.Executors; import org.apache.flink.util.concurrent.FutureUtils; @@ -53,7 +52,6 @@ import org.apache.flink.shaded.netty4.io.netty.util.AttributeKey; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; import javax.annotation.Nonnull; @@ -75,7 +73,6 @@ import static org.mockito.Mockito.when; /** Tests for {@link AbstractHandler}. */ -@ExtendWith(TestLoggerExtension.class) class AbstractHandlerTest { private static final RestfulGateway mockRestfulGateway = diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/FileUploadsTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/FileUploadsTest.java index a80a9751d7ecf4..817c074015c5e0 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/FileUploadsTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/FileUploadsTest.java @@ -18,12 +18,8 @@ package org.apache.flink.runtime.rest.handler; -import org.apache.flink.util.TestLogger; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -33,30 +29,27 @@ import java.util.Collection; import java.util.stream.Collectors; -/** Tests for {@link FileUploads}. */ -public class FileUploadsTest extends TestLogger { +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; - @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); +/** Tests for {@link FileUploads}. */ +class FileUploadsTest { @Test - public void testRelativePathRejection() throws IOException { + void testRelativePathRejection() throws IOException { Path relative = Paths.get("root"); - try { - new FileUploads(relative); - Assert.fail(); - } catch (IllegalArgumentException iae) { - // expected - } + assertThatThrownBy(() -> new FileUploads(relative)) + .isInstanceOf(IllegalArgumentException.class); } @Test - public void testDirectoryScan() throws IOException { + void testDirectoryScan(@TempDir File temporaryFolder) throws IOException { Path rootDir = Paths.get("root"); Path rootFile = rootDir.resolve("rootFile"); Path subDir = rootDir.resolve("sub"); Path subFile = subDir.resolve("subFile"); - Path tmp = temporaryFolder.getRoot().toPath(); + Path tmp = temporaryFolder.toPath(); Files.createDirectory(tmp.resolve(rootDir)); Files.createDirectory(tmp.resolve(subDir)); Files.createFile(tmp.resolve(rootFile)); @@ -68,47 +61,47 @@ public void testDirectoryScan() throws IOException { .map(File::toPath) .collect(Collectors.toList()); - Assert.assertEquals(2, detectedFiles.size()); - Assert.assertTrue(detectedFiles.contains(tmp.resolve(rootFile))); - Assert.assertTrue(detectedFiles.contains(tmp.resolve(subFile))); + assertThat(detectedFiles).hasSize(2); + assertThat(detectedFiles.contains(tmp.resolve(rootFile))).isTrue(); + assertThat(detectedFiles.contains(tmp.resolve(subFile))).isTrue(); } } @Test - public void testEmptyDirectory() throws IOException { + void testEmptyDirectory(@TempDir File temporaryFolder) throws IOException { Path rootDir = Paths.get("root"); - Path tmp = temporaryFolder.getRoot().toPath(); + Path tmp = temporaryFolder.toPath(); Files.createDirectory(tmp.resolve(rootDir)); try (FileUploads fileUploads = new FileUploads(tmp.resolve(rootDir))) { Collection detectedFiles = fileUploads.getUploadedFiles(); - Assert.assertEquals(0, detectedFiles.size()); + assertThat(detectedFiles).isEmpty(); } } @Test - public void testCleanup() throws IOException { + void testCleanup(@TempDir File temporaryFolder) throws IOException { Path rootDir = Paths.get("root"); Path rootFile = rootDir.resolve("rootFile"); Path subDir = rootDir.resolve("sub"); Path subFile = subDir.resolve("subFile"); - Path tmp = temporaryFolder.getRoot().toPath(); + Path tmp = temporaryFolder.toPath(); Files.createDirectory(tmp.resolve(rootDir)); Files.createDirectory(tmp.resolve(subDir)); Files.createFile(tmp.resolve(rootFile)); Files.createFile(tmp.resolve(subFile)); try (FileUploads fileUploads = new FileUploads(tmp.resolve(rootDir))) { - Assert.assertTrue(Files.exists(tmp.resolve(rootDir))); - Assert.assertTrue(Files.exists(tmp.resolve(subDir))); - Assert.assertTrue(Files.exists(tmp.resolve(rootFile))); - Assert.assertTrue(Files.exists(tmp.resolve(subFile))); + assertThat(Files.exists(tmp.resolve(rootDir))).isTrue(); + assertThat(Files.exists(tmp.resolve(subDir))).isTrue(); + assertThat(Files.exists(tmp.resolve(rootFile))).isTrue(); + assertThat(Files.exists(tmp.resolve(subFile))).isTrue(); } - Assert.assertFalse(Files.exists(tmp.resolve(rootDir))); - Assert.assertFalse(Files.exists(tmp.resolve(subDir))); - Assert.assertFalse(Files.exists(tmp.resolve(rootFile))); - Assert.assertFalse(Files.exists(tmp.resolve(subFile))); + assertThat(Files.exists(tmp.resolve(rootDir))).isFalse(); + assertThat(Files.exists(tmp.resolve(subDir))).isFalse(); + assertThat(Files.exists(tmp.resolve(rootFile))).isFalse(); + assertThat(Files.exists(tmp.resolve(subFile))).isFalse(); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/InFlightRequestTrackerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/InFlightRequestTrackerTest.java index 7d7954dae56e06..1cff2d9134f933 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/InFlightRequestTrackerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/InFlightRequestTrackerTest.java @@ -18,70 +18,65 @@ package org.apache.flink.runtime.rest.handler; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.concurrent.CompletableFuture; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link InFlightRequestTracker}. */ -public class InFlightRequestTrackerTest { +class InFlightRequestTrackerTest { private InFlightRequestTracker inFlightRequestTracker; - @Before - public void setUp() { + @BeforeEach + void setUp() { inFlightRequestTracker = new InFlightRequestTracker(); } @Test - public void testShouldFinishAwaitAsyncImmediatelyIfNoRequests() { - assertTrue(inFlightRequestTracker.awaitAsync().isDone()); + void testShouldFinishAwaitAsyncImmediatelyIfNoRequests() { + assertThat(inFlightRequestTracker.awaitAsync()).isDone(); } @Test - public void testShouldFinishAwaitAsyncIffAllRequestsDeregistered() { + void testShouldFinishAwaitAsyncIffAllRequestsDeregistered() { inFlightRequestTracker.registerRequest(); final CompletableFuture awaitFuture = inFlightRequestTracker.awaitAsync(); - assertFalse(awaitFuture.isDone()); + assertThat(awaitFuture).isNotDone(); inFlightRequestTracker.deregisterRequest(); - assertTrue(awaitFuture.isDone()); + assertThat(awaitFuture).isDone(); } @Test - public void testAwaitAsyncIsIdempotent() { + void testAwaitAsyncIsIdempotent() { final CompletableFuture awaitFuture = inFlightRequestTracker.awaitAsync(); - assertTrue(awaitFuture.isDone()); - - assertSame( - "The reference to the future must not change", - awaitFuture, - inFlightRequestTracker.awaitAsync()); + assertThat(awaitFuture).isDone(); + assertThat(awaitFuture) + .as("The reference to the future must not change") + .isEqualTo(inFlightRequestTracker.awaitAsync()); } @Test - public void testShouldTolerateRegisterAfterAwaitAsync() { + void testShouldTolerateRegisterAfterAwaitAsync() { final CompletableFuture awaitFuture = inFlightRequestTracker.awaitAsync(); - assertTrue(awaitFuture.isDone()); + assertThat(awaitFuture).isDone(); inFlightRequestTracker.registerRequest(); - assertSame( - "The reference to the future must not change", - awaitFuture, - inFlightRequestTracker.awaitAsync()); + assertThat(awaitFuture) + .as("The reference to the future must not change") + .isEqualTo(inFlightRequestTracker.awaitAsync()); } @Test - public void testShouldNotRegisterNewRequestsAfterTermination() { + void testShouldNotRegisterNewRequestsAfterTermination() { final CompletableFuture terminationFuture = inFlightRequestTracker.awaitAsync(); - assertTrue(terminationFuture.isDone()); - assertFalse(inFlightRequestTracker.registerRequest()); + assertThat(terminationFuture).isDone(); + assertThat(inFlightRequestTracker.registerRequest()).isFalse(); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/RestHandlerConfigurationTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/RestHandlerConfigurationTest.java index 217130844b4af4..47efe5c92d8736 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/RestHandlerConfigurationTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/RestHandlerConfigurationTest.java @@ -23,10 +23,8 @@ import org.apache.flink.configuration.RestOptions; import org.apache.flink.configuration.SchedulerExecutionMode; import org.apache.flink.configuration.WebOptions; -import org.apache.flink.util.TestLoggerExtension; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -35,7 +33,6 @@ import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link RestHandlerConfiguration}. */ -@ExtendWith(TestLoggerExtension.class) class RestHandlerConfigurationTest { @Test @@ -108,7 +105,7 @@ private static void testWebCancelFeatureFlag(boolean webCancelEnabled) { } @Test - public void testCheckpointCacheExpireAfterWrite() { + void testCheckpointCacheExpireAfterWrite() { final Duration testDuration = Duration.ofMillis(100L); final Configuration config = new Configuration(); config.set(RestOptions.CACHE_CHECKPOINT_STATISTICS_TIMEOUT, testDuration); @@ -120,7 +117,7 @@ public void testCheckpointCacheExpireAfterWrite() { } @Test - public void testCheckpointCacheExpiryFallbackToRefreshInterval() { + void testCheckpointCacheExpiryFallbackToRefreshInterval() { final long refreshInterval = 1000L; final Configuration config = new Configuration(); config.set(WebOptions.REFRESH_INTERVAL, refreshInterval); @@ -132,7 +129,7 @@ public void testCheckpointCacheExpiryFallbackToRefreshInterval() { } @Test - public void testCheckpointCacheSize() { + void testCheckpointCacheSize() { final int testCacheSize = 50; final Configuration config = new Configuration(); config.set(RestOptions.CACHE_CHECKPOINT_STATISTICS_SIZE, testCacheSize); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AbstractAsynchronousOperationHandlersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AbstractAsynchronousOperationHandlersTest.java index f2f6da135ab3b1..ba46757bb7e06e 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AbstractAsynchronousOperationHandlersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AbstractAsynchronousOperationHandlersTest.java @@ -39,13 +39,12 @@ import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.util.FlinkException; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.annotation.Nullable; @@ -57,13 +56,11 @@ import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** Tests for the {@link AbstractAsynchronousOperationHandlers}. */ -public class AbstractAsynchronousOperationHandlersTest extends TestLogger { +class AbstractAsynchronousOperationHandlersTest { private static final Time TIMEOUT = Time.seconds(10L); @@ -74,8 +71,8 @@ public class AbstractAsynchronousOperationHandlersTest extends TestLogger { private TestingAsynchronousOperationHandlers.TestingStatusHandler testingStatusHandler; - @Before - public void setup() { + @BeforeEach + void setup() { TestingAsynchronousOperationHandlers testingAsynchronousOperationHandlers = new TestingAsynchronousOperationHandlers(); @@ -98,7 +95,7 @@ public void setup() { /** Tests the triggering and successful completion of an asynchronous operation. */ @Test - public void testOperationCompletion() throws Exception { + void testOperationCompletion() throws Exception { final CompletableFuture acknowledgeFuture = new CompletableFuture<>(); testingTriggerHandler.setGatewayCallback((request, gateway) -> acknowledgeFuture); @@ -114,7 +111,8 @@ public void testOperationCompletion() throws Exception { .handleRequest(statusOperationRequest(triggerId), DUMMY_GATEWAY) .get(); - assertThat(operationResult.queueStatus().getId(), is(QueueStatus.inProgress().getId())); + assertThat(operationResult.queueStatus().getId()) + .isEqualTo(QueueStatus.inProgress().getId()); // complete the operation acknowledgeFuture.complete(Acknowledge.get()); @@ -124,14 +122,15 @@ public void testOperationCompletion() throws Exception { .handleRequest(statusOperationRequest(triggerId), DUMMY_GATEWAY) .get(); - assertThat(operationResult.queueStatus().getId(), is(QueueStatus.completed().getId())); + assertThat(operationResult.queueStatus().getId()) + .isEqualTo(QueueStatus.completed().getId()); - assertThat(operationResult.resource().value, is(Acknowledge.get())); + assertThat(operationResult.resource().value).isEqualTo(Acknowledge.get()); } /** Tests the triggering and exceptional completion of an asynchronous operation. */ @Test - public void testOperationFailure() throws Exception { + void testOperationFailure() throws Exception { final FlinkException testException = new FlinkException("Test exception"); testingTriggerHandler.setGatewayCallback( (request, gateway) -> FutureUtils.completedExceptionally(testException)); @@ -148,17 +147,18 @@ public void testOperationFailure() throws Exception { .handleRequest(statusOperationRequest(triggerId), DUMMY_GATEWAY) .get(); - assertThat(operationResult.queueStatus().getId(), is(QueueStatus.completed().getId())); + assertThat(operationResult.queueStatus().getId()) + .isEqualTo(QueueStatus.completed().getId()); final OperationResult resource = operationResult.resource(); - assertThat(resource.throwable, is(testException)); + assertThat(resource.throwable).isEqualTo(testException); } /** * Tests that an querying an unknown trigger id will return an exceptionally completed future. */ @Test - public void testUnknownTriggerId() throws Exception { + void testUnknownTriggerId() throws Exception { try { testingStatusHandler .handleRequest(statusOperationRequest(new TriggerId()), DUMMY_GATEWAY) @@ -169,13 +169,13 @@ public void testUnknownTriggerId() throws Exception { final Optional optionalRestHandlerException = ExceptionUtils.findThrowable(ee, RestHandlerException.class); - assertThat(optionalRestHandlerException.isPresent(), is(true)); + assertThat(optionalRestHandlerException).isPresent(); final RestHandlerException restHandlerException = optionalRestHandlerException.get(); - assertThat(restHandlerException.getMessage(), containsString("Operation not found")); - assertThat( - restHandlerException.getHttpResponseStatus(), is(HttpResponseStatus.NOT_FOUND)); + assertThat(restHandlerException.getMessage()).contains("Operation not found"); + assertThat(restHandlerException.getHttpResponseStatus()) + .isEqualTo(HttpResponseStatus.NOT_FOUND); } } @@ -185,7 +185,7 @@ public void testUnknownTriggerId() throws Exception { * of the asynchronous operation is served. */ @Test - public void testCloseShouldFinishOnFirstServedResult() throws Exception { + void testCloseShouldFinishOnFirstServedResult() throws Exception { final CompletableFuture acknowledgeFuture = new CompletableFuture<>(); testingTriggerHandler.setGatewayCallback((request, gateway) -> acknowledgeFuture); @@ -198,12 +198,12 @@ public void testCloseShouldFinishOnFirstServedResult() throws Exception { testingStatusHandler.handleRequest(statusOperationRequest(triggerId), DUMMY_GATEWAY).get(); - assertThat(closeFuture.isDone(), is(false)); + assertThat(closeFuture).isNotDone(); acknowledgeFuture.complete(Acknowledge.get()); testingStatusHandler.handleRequest(statusOperationRequest(triggerId), DUMMY_GATEWAY).get(); - assertThat(closeFuture.isDone(), is(true)); + assertThat(closeFuture).isDone(); } private static HandlerRequest triggerOperationRequest() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AsynchronousOperationResultTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AsynchronousOperationResultTest.java index 496ce5a18051f7..ab59814258e381 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AsynchronousOperationResultTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/AsynchronousOperationResultTest.java @@ -20,23 +20,23 @@ import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; import org.apache.flink.runtime.rest.messages.TriggerId; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for the marshalling of {@link AsynchronousOperationResult}. */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class AsynchronousOperationResultTest extends RestResponseMarshallingTestBase> { - @Parameterized.Parameters + @Parameters public static Collection data() { return Arrays.asList( new Object[][] { @@ -72,7 +72,7 @@ protected AsynchronousOperationResult getTestResponseInstance() throw protected void assertOriginalEqualsToUnmarshalled( AsynchronousOperationResult expected, AsynchronousOperationResult actual) { - assertThat(actual.queueStatus().getId(), is(expected.queueStatus().getId())); - assertThat(actual.resource(), is(expected.resource())); + assertThat(actual.queueStatus().getId()).isEqualTo(expected.queueStatus().getId()); + assertThat(actual.resource()).isEqualTo(expected.resource()); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/CompletedOperationCacheTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/CompletedOperationCacheTest.java index 6f09fc914cc63c..ce3eca490a5c99 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/CompletedOperationCacheTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/CompletedOperationCacheTest.java @@ -22,26 +22,21 @@ import org.apache.flink.core.testutils.FlinkMatchers; import org.apache.flink.runtime.rest.messages.TriggerId; import org.apache.flink.runtime.util.ManualTicker; -import org.apache.flink.util.TestLogger; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.HamcrestCondition.matching; /** Tests for {@link CompletedOperationCache}. */ -public class CompletedOperationCacheTest extends TestLogger { +class CompletedOperationCacheTest { private static final OperationKey TEST_OPERATION_KEY = new OperationKey(new TriggerId()); @@ -52,47 +47,47 @@ public class CompletedOperationCacheTest extends TestLogger { private CompletedOperationCache completedOperationCache; - @Before - public void setUp() { + @BeforeEach + void setUp() { manualTicker = new ManualTicker(); completedOperationCache = new CompletedOperationCache<>(manualTicker); } @Test - public void testShouldFinishClosingCacheIfAllResultsAreEvicted() { + void testShouldFinishClosingCacheIfAllResultsAreEvicted() { completedOperationCache.registerOngoingOperation(TEST_OPERATION_KEY, TEST_OPERATION_RESULT); final CompletableFuture closeCacheFuture = completedOperationCache.closeAsync(); - assertThat(closeCacheFuture.isDone(), is(false)); + assertThat(closeCacheFuture).isNotDone(); manualTicker.advanceTime(300, TimeUnit.SECONDS); completedOperationCache.cleanUp(); - assertThat(closeCacheFuture.isDone(), is(true)); + assertThat(closeCacheFuture).isDone(); } @Test - public void testShouldFinishClosingCacheIfAllResultsAccessed() throws Exception { + void testShouldFinishClosingCacheIfAllResultsAccessed() throws Exception { completedOperationCache.registerOngoingOperation(TEST_OPERATION_KEY, TEST_OPERATION_RESULT); final CompletableFuture closeCacheFuture = completedOperationCache.closeAsync(); - assertThat(closeCacheFuture.isDone(), is(false)); + assertThat(closeCacheFuture).isNotDone(); final Optional> operationResultOptional = completedOperationCache.get(TEST_OPERATION_KEY); - assertTrue(operationResultOptional.isPresent()); + assertThat(operationResultOptional).isPresent(); OperationResult operationResult = operationResultOptional.get(); - assertEquals(operationResult.getStatus(), OperationResultStatus.SUCCESS); - assertThat(operationResult.getResult(), is(equalTo(TEST_OPERATION_RESULT.get()))); - assertThat(closeCacheFuture.isDone(), is(true)); + assertThat(OperationResultStatus.SUCCESS).isEqualTo(operationResult.getStatus()); + assertThat(operationResult.getResult()).isEqualTo(TEST_OPERATION_RESULT.get()); + assertThat(closeCacheFuture).isDone(); } @Test - public void testCannotAddOperationAfterClosing() { + void testCannotAddOperationAfterClosing() { completedOperationCache.registerOngoingOperation( TEST_OPERATION_KEY, new CompletableFuture<>()); final CompletableFuture terminationFuture = completedOperationCache.closeAsync(); - assertFalse(terminationFuture.isDone()); + assertThat(terminationFuture).isNotDone(); try { completedOperationCache.registerOngoingOperation( @@ -105,47 +100,47 @@ public void testCannotAddOperationAfterClosing() { } @Test - public void testCanGetOperationResultAfterClosing() throws Exception { + void testCanGetOperationResultAfterClosing() throws Exception { completedOperationCache.registerOngoingOperation(TEST_OPERATION_KEY, TEST_OPERATION_RESULT); completedOperationCache.closeAsync(); final Optional> operationResultOptional = completedOperationCache.get(TEST_OPERATION_KEY); - assertTrue(operationResultOptional.isPresent()); + assertThat(operationResultOptional).isPresent(); final OperationResult operationResult = operationResultOptional.get(); - assertEquals(operationResult.getStatus(), OperationResultStatus.SUCCESS); - assertThat(operationResult.getResult(), is(equalTo(TEST_OPERATION_RESULT.get()))); + assertThat(OperationResultStatus.SUCCESS).isEqualTo(operationResult.getStatus()); + assertThat(operationResult.getResult()).isEqualTo(TEST_OPERATION_RESULT.get()); } @Test - public void testCacheTimeout() throws Exception { + void testCacheTimeout() throws Exception { final Duration timeout = RestOptions.ASYNC_OPERATION_STORE_DURATION.defaultValue(); completedOperationCache = new CompletedOperationCache<>(timeout, manualTicker); completedOperationCache.registerOngoingOperation(TEST_OPERATION_KEY, TEST_OPERATION_RESULT); // sanity check that the operation can be retrieved before the timeout - assertTrue(completedOperationCache.get(TEST_OPERATION_KEY).isPresent()); + assertThat(completedOperationCache.get(TEST_OPERATION_KEY)).isPresent(); manualTicker.advanceTime(timeout.multipliedBy(2).getSeconds(), TimeUnit.SECONDS); - assertFalse(completedOperationCache.get(TEST_OPERATION_KEY).isPresent()); + assertThat(completedOperationCache.get(TEST_OPERATION_KEY)).isNotPresent(); } @Test - public void testCacheTimeoutCanBeDisabled() throws Exception { + void testCacheTimeoutCanBeDisabled() throws Exception { completedOperationCache = new CompletedOperationCache<>(Duration.ofSeconds(0), manualTicker); completedOperationCache.registerOngoingOperation(TEST_OPERATION_KEY, TEST_OPERATION_RESULT); manualTicker.advanceTime(365, TimeUnit.DAYS); - assertTrue(completedOperationCache.get(TEST_OPERATION_KEY).isPresent()); + assertThat(completedOperationCache.get(TEST_OPERATION_KEY)).isPresent(); } @Test - public void testCacheTimeoutCanBeConfigured() throws Exception { + void testCacheTimeoutCanBeConfigured() throws Exception { final Duration baseTimeout = RestOptions.ASYNC_OPERATION_STORE_DURATION.defaultValue(); completedOperationCache = @@ -154,35 +149,35 @@ public void testCacheTimeoutCanBeConfigured() throws Exception { manualTicker.advanceTime(baseTimeout.multipliedBy(2).getSeconds(), TimeUnit.SECONDS); - assertTrue(completedOperationCache.get(TEST_OPERATION_KEY).isPresent()); + assertThat(completedOperationCache.get(TEST_OPERATION_KEY)).isPresent(); } @Test - public void containsReturnsFalseForUnknownOperation() { - assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY), is(false)); + void containsReturnsFalseForUnknownOperation() { + assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY)).isFalse(); } @Test - public void containsChecksOnoingOperations() { + void containsChecksOnoingOperations() { completedOperationCache.registerOngoingOperation( TEST_OPERATION_KEY, new CompletableFuture<>()); - assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY), is(true)); + assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY)).isTrue(); } @Test - public void containsChecksCompletedOperations() { + void containsChecksCompletedOperations() { completedOperationCache.registerOngoingOperation( TEST_OPERATION_KEY, CompletableFuture.completedFuture(null)); - assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY), is(true)); + assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY)).isTrue(); } @Test - public void containsDoesNotMarkResultAsAccessed() { + void containsDoesNotMarkResultAsAccessed() { completedOperationCache.registerOngoingOperation( TEST_OPERATION_KEY, CompletableFuture.completedFuture(null)); - assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY), is(true)); - assertThat( - completedOperationCache.closeAsync(), - FlinkMatchers.willNotComplete(Duration.ofMillis(10))); + assertThat(completedOperationCache.containsOperation(TEST_OPERATION_KEY)).isTrue(); + + assertThat(completedOperationCache.closeAsync()) + .satisfies(matching(FlinkMatchers.willNotComplete(Duration.ofMillis(10)))); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/TriggerResponseTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/TriggerResponseTest.java index f546fb2aa2fee5..bf6bae60ffc112 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/TriggerResponseTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/async/TriggerResponseTest.java @@ -18,15 +18,13 @@ package org.apache.flink.runtime.rest.handler.async; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import org.apache.flink.runtime.rest.messages.TriggerId; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Marshalling test for {@link TriggerResponse}. */ -public class TriggerResponseTest extends RestResponseMarshallingTestBase { +class TriggerResponseTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { @@ -41,6 +39,6 @@ protected TriggerResponse getTestResponseInstance() throws Exception { @Override protected void assertOriginalEqualsToUnmarshalled( TriggerResponse expected, TriggerResponse actual) { - assertThat(actual.getTriggerId(), is(equalTo(expected.getTriggerId()))); + assertThat(actual.getTriggerId()).isEqualTo(expected.getTriggerId()); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerCustomLogHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerCustomLogHandlerTest.java index 0c43ee3e4b3c22..7f980ba7e77dd9 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerCustomLogHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerCustomLogHandlerTest.java @@ -25,13 +25,11 @@ import org.apache.flink.runtime.rest.messages.cluster.JobManagerCustomLogHeaders; import org.apache.flink.runtime.webmonitor.TestingDispatcherGateway; import org.apache.flink.testutils.TestingUtils; -import org.apache.flink.util.TestLogger; import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -42,29 +40,23 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** Unit tests for {@link JobManagerCustomLogHandler}. */ -public class JobManagerCustomLogHandlerTest extends TestLogger { +class JobManagerCustomLogHandlerTest { private static final String FORBIDDEN_FILENAME = "forbidden"; private static final String VALID_LOG_FILENAME = "valid.log"; private static final String VALID_LOG_CONTENT = "logged content"; - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private File logRoot; private JobManagerCustomLogHandler testInstance; - @Before - public void setUp() throws IOException { - initializeFolderStructure(); + @BeforeEach + void setUp(@TempDir File root) throws IOException { + initializeFolderStructure(root); final TestingDispatcherGateway dispatcherGateway = TestingDispatcherGateway.newBuilder().build(); @@ -77,10 +69,9 @@ public void setUp() throws IOException { logRoot); } - private void initializeFolderStructure() throws IOException { - File root = temporaryFolder.getRoot(); + private void initializeFolderStructure(File root) throws IOException { logRoot = new File(root, "logs"); - assertTrue(logRoot.mkdir()); + assertThat(logRoot.mkdir()).isTrue(); createFile(new File(root, FORBIDDEN_FILENAME), "forbidden content"); createFile(new File(logRoot, VALID_LOG_FILENAME), VALID_LOG_CONTENT); @@ -105,60 +96,60 @@ private static HandlerRequest createHandlerRequest(String path } @Test - public void testGetJobManagerCustomLogsValidFilename() throws Exception { + void testGetJobManagerCustomLogsValidFilename() throws Exception { File actualFile = testInstance.getFile(createHandlerRequest(VALID_LOG_FILENAME)); - assertThat(actualFile, is(notNullValue())); + assertThat(actualFile).isNotNull(); String actualContent = String.join("", Files.readAllLines(actualFile.toPath())); - assertThat(actualContent, is(VALID_LOG_CONTENT)); + assertThat(actualContent).isEqualTo(VALID_LOG_CONTENT); } @Test - public void testGetJobManagerCustomLogsValidFilenameWithPath() throws Exception { + void testGetJobManagerCustomLogsValidFilenameWithPath() throws Exception { File actualFile = testInstance.getFile( createHandlerRequest(String.format("foobar/%s", VALID_LOG_FILENAME))); - assertThat(actualFile, is(notNullValue())); + assertThat(actualFile).isNotNull(); String actualContent = String.join("", Files.readAllLines(actualFile.toPath())); - assertThat(actualContent, is(VALID_LOG_CONTENT)); + assertThat(actualContent).isEqualTo(VALID_LOG_CONTENT); } @Test - public void testGetJobManagerCustomLogsValidFilenameWithInvalidPath() throws Exception { + void testGetJobManagerCustomLogsValidFilenameWithInvalidPath() throws Exception { File actualFile = testInstance.getFile( createHandlerRequest(String.format("../%s", VALID_LOG_FILENAME))); - assertThat(actualFile, is(notNullValue())); + assertThat(actualFile).isNotNull(); String actualContent = String.join("", Files.readAllLines(actualFile.toPath())); - assertThat(actualContent, is(VALID_LOG_CONTENT)); + assertThat(actualContent).isEqualTo(VALID_LOG_CONTENT); } @Test - public void testGetJobManagerCustomLogsNotExistingFile() throws Exception { + void testGetJobManagerCustomLogsNotExistingFile() throws Exception { File actualFile = testInstance.getFile(createHandlerRequest("not-existing")); - assertThat(actualFile, is(notNullValue())); - assertFalse(actualFile.exists()); + assertThat(actualFile).isNotNull(); + assertThat(actualFile.exists()).isFalse(); } @Test - public void testGetJobManagerCustomLogsExistingButForbiddenFile() throws Exception { + void testGetJobManagerCustomLogsExistingButForbiddenFile() throws Exception { File actualFile = testInstance.getFile( createHandlerRequest(String.format("../%s", FORBIDDEN_FILENAME))); - assertThat(actualFile, is(notNullValue())); - assertFalse(actualFile.exists()); + assertThat(actualFile).isNotNull(); + assertThat(actualFile.exists()).isFalse(); } @Test - public void testGetJobManagerCustomLogsValidFilenameWithLongInvalidPath() throws Exception { + void testGetJobManagerCustomLogsValidFilenameWithLongInvalidPath() throws Exception { File actualFile = testInstance.getFile( createHandlerRequest(String.format("foobar/../../%s", VALID_LOG_FILENAME))); - assertThat(actualFile, is(notNullValue())); + assertThat(actualFile).isNotNull(); String actualContent = String.join("", Files.readAllLines(actualFile.toPath())); - assertThat(actualContent, is(VALID_LOG_CONTENT)); + assertThat(actualContent).isEqualTo(VALID_LOG_CONTENT); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerLogListHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerLogListHandlerTest.java index 258b96ab67b13e..c74ea63a35c894 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerLogListHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/cluster/JobManagerLogListHandlerTest.java @@ -29,14 +29,12 @@ import org.apache.flink.runtime.webmonitor.TestingDispatcherGateway; import org.apache.flink.testutils.TestingUtils; import org.apache.flink.util.StringUtils; -import org.apache.flink.util.TestLogger; import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import javax.annotation.Nullable; @@ -49,22 +47,17 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadLocalRandom; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Unit tests for {@link JobManagerLogListHandler}. */ -public class JobManagerLogListHandlerTest extends TestLogger { +class JobManagerLogListHandlerTest { private static HandlerRequest testRequest; - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private DispatcherGateway dispatcherGateway; - @BeforeClass - public static void setupClass() throws HandlerRequestException { + @BeforeAll + static void setupClass() throws HandlerRequestException { testRequest = HandlerRequest.create( EmptyRequestBody.getInstance(), @@ -72,14 +65,13 @@ public static void setupClass() throws HandlerRequestException { Collections.emptyList()); } - @Before - public void setUp() { + @BeforeEach + void setUp() { dispatcherGateway = TestingDispatcherGateway.newBuilder().build(); } @Test - public void testGetJobManagerLogsList() throws Exception { - File logRoot = temporaryFolder.getRoot(); + void testGetJobManagerLogsList(@TempDir File logRoot) throws Exception { List expectedLogInfo = Arrays.asList( new LogInfo("jobmanager.log", 5, 1632844800000L), @@ -91,18 +83,17 @@ public void testGetJobManagerLogsList() throws Exception { LogListInfo logListInfo = jobManagerLogListHandler.handleRequest(testRequest, dispatcherGateway).get(); - assertThat( - logListInfo.getLogInfos(), - containsInAnyOrder(expectedLogInfo.toArray(new LogInfo[0]))); + assertThat(logListInfo.getLogInfos()) + .containsExactlyInAnyOrder(expectedLogInfo.toArray(new LogInfo[0])); } @Test - public void testGetJobManagerLogsListWhenLogDirIsNull() throws Exception { + void testGetJobManagerLogsListWhenLogDirIsNull() throws Exception { JobManagerLogListHandler jobManagerLogListHandler = createHandler(null); LogListInfo logListInfo = jobManagerLogListHandler.handleRequest(testRequest, dispatcherGateway).get(); - assertThat(logListInfo.getLogInfos(), is(empty())); + assertThat(logListInfo.getLogInfos()).isEmpty(); } private JobManagerLogListHandler createHandler(@Nullable final File jobManagerLogRoot) { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/GeneratedLogUrlHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/GeneratedLogUrlHandlerTest.java index 528c7115e93bc4..f8004bb9660c73 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/GeneratedLogUrlHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/GeneratedLogUrlHandlerTest.java @@ -18,27 +18,25 @@ package org.apache.flink.runtime.rest.handler.job; -import org.apache.flink.util.TestLogger; - import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Test for the {@link GeneratedLogUrlHandler}. */ -public class GeneratedLogUrlHandlerTest extends TestLogger { +class GeneratedLogUrlHandlerTest { @Test - public void testGenerateJobManagerLogUrl() { + void testGenerateJobManagerLogUrl() { final String pattern = "http://localhost//log"; final String jobId = "jobid"; final String generatedUrl = GeneratedLogUrlHandler.generateLogUrl(pattern, jobId, null); - assertEquals(pattern.replace("", jobId), generatedUrl); + assertThat(generatedUrl).isEqualTo(pattern.replace("", jobId)); } @Test - public void testGenerateTaskManagerLogUrl() { + void testGenerateTaskManagerLogUrl() { final String pattern = "http://localhost//tm//log"; final String jobId = "jobid"; final String taskManagerId = "tmid"; @@ -46,7 +44,7 @@ public void testGenerateTaskManagerLogUrl() { final String generatedUrl = GeneratedLogUrlHandler.generateLogUrl(pattern, jobId, taskManagerId); - assertEquals( - pattern.replace("", jobId).replace("", taskManagerId), generatedUrl); + assertThat(pattern.replace("", jobId).replace("", taskManagerId)) + .isEqualTo(generatedUrl); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobCancellationHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobCancellationHandlerTest.java index 93efa4fbf3f115..0ffb748b335f25 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobCancellationHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobCancellationHandlerTest.java @@ -32,7 +32,6 @@ import org.apache.flink.runtime.rest.messages.TerminationModeQueryParameter; import org.apache.flink.runtime.webmonitor.RestfulGateway; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.util.function.ThrowingConsumer; @@ -45,19 +44,20 @@ import java.util.concurrent.TimeoutException; import java.util.function.Function; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.HamcrestCondition.matching; /** Tests for the {@link JobCancellationHandler}. */ -public class JobCancellationHandlerTest extends TestLogger { +class JobCancellationHandlerTest { @Test - public void testSuccessfulCancellation() throws Exception { + void testSuccessfulCancellation() throws Exception { testResponse( jobId -> CompletableFuture.completedFuture(Acknowledge.get()), CompletableFuture::get); } @Test - public void testErrorCodeForNonCanceledTerminalJob() throws Exception { + void testErrorCodeForNonCanceledTerminalJob() throws Exception { testResponseCodeOnFailedDispatcherCancellationResponse( jobId -> FutureUtils.completedExceptionally( @@ -67,21 +67,21 @@ public void testErrorCodeForNonCanceledTerminalJob() throws Exception { } @Test - public void testErrorCodeForTimeout() throws Exception { + void testErrorCodeForTimeout() throws Exception { testResponseCodeOnFailedDispatcherCancellationResponse( jobId -> FutureUtils.completedExceptionally(new TimeoutException()), HttpResponseStatus.REQUEST_TIMEOUT); } @Test - public void testErrorCodeForUnknownJob() throws Exception { + void testErrorCodeForUnknownJob() throws Exception { testResponseCodeOnFailedDispatcherCancellationResponse( jobId -> FutureUtils.completedExceptionally(new FlinkJobNotFoundException(jobId)), HttpResponseStatus.NOT_FOUND); } @Test - public void testErrorCodeForUnknownError() throws Exception { + void testErrorCodeForUnknownError() throws Exception { testResponseCodeOnFailedDispatcherCancellationResponse( jobId -> FutureUtils.completedExceptionally(new RuntimeException()), HttpResponseStatus.INTERNAL_SERVER_ERROR); @@ -95,9 +95,11 @@ private static void testResponseCodeOnFailedDispatcherCancellationResponse( testResponse( cancelJobFunction, cancellationFuture -> - assertThat( - cancellationFuture, - RestMatchers.respondsWithError(expectedErrorCode))); + assertThat(cancellationFuture) + .satisfies( + matching( + RestMatchers.respondsWithError( + expectedErrorCode)))); } private static void testResponse( diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobConfigHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobConfigHandlerTest.java index ce23fe11d571ac..c2d2968e5ed7dc 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobConfigHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobConfigHandlerTest.java @@ -33,24 +33,21 @@ import org.apache.flink.runtime.rest.messages.JobIDPathParameter; import org.apache.flink.runtime.rest.messages.JobMessageParameters; import org.apache.flink.testutils.TestingUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Test for the {@link JobConfigHandler}. */ -public class JobConfigHandlerTest extends TestLogger { +class JobConfigHandlerTest { @Test - public void handleRequest_executionConfigWithSecretValues_excludesSecretValuesFromResponse() + void handleRequest_executionConfigWithSecretValues_excludesSecretValuesFromResponse() throws HandlerRequestException { final JobConfigHandler jobConfigHandler = new JobConfigHandler( @@ -83,9 +80,8 @@ public void handleRequest_executionConfigWithSecretValues_excludesSecretValuesFr final Map filteredGlobalJobParameters = filterSecretValues(globalJobParameters); - assertThat( - jobConfigInfoResponse.getExecutionConfigInfo().getGlobalJobParameters(), - is(equalTo(filteredGlobalJobParameters))); + assertThat(jobConfigInfoResponse.getExecutionConfigInfo().getGlobalJobParameters()) + .isEqualTo(filteredGlobalJobParameters); } private Map filterSecretValues(Map globalJobParameters) { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExceptionsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExceptionsHandlerTest.java index efce7903686333..b294f4f161f77f 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExceptionsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExceptionsHandlerTest.java @@ -52,7 +52,6 @@ import org.apache.flink.testutils.TestingUtils; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.util.SerializedThrowable; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; import org.hamcrest.Description; @@ -60,7 +59,7 @@ import org.hamcrest.TypeSafeDiagnosingMatcher; import org.hamcrest.collection.IsEmptyIterable; import org.hamcrest.collection.IsIterableContainingInOrder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -73,18 +72,13 @@ import java.util.function.Function; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.collection.IsEmptyCollection.empty; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.hamcrest.collection.IsIterableWithSize.iterableWithSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.HamcrestCondition.matching; +XXX.contains; +XXX.iterableWithSize; /** Test for the {@link JobExceptionsHandler}. */ -public class JobExceptionsHandlerTest extends TestLogger { +class JobExceptionsHandlerTest { private final JobExceptionsHandler testInstance = new JobExceptionsHandler( @@ -96,7 +90,7 @@ public class JobExceptionsHandlerTest extends TestLogger { Executors.directExecutor()); @Test - public void testNoExceptions() throws HandlerRequestException { + void testNoExceptions() throws HandlerRequestException { final ExecutionGraphInfo executionGraphInfo = new ExecutionGraphInfo(new ArchivedExecutionGraphBuilder().build()); @@ -105,15 +99,15 @@ public void testNoExceptions() throws HandlerRequestException { final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat(response.getRootException(), is(nullValue())); - assertThat(response.getRootTimestamp(), is(nullValue())); - assertFalse(response.isTruncated()); - assertThat(response.getAllExceptions(), empty()); - assertThat(response.getExceptionHistory().getEntries(), empty()); + assertThat(response.getRootException()).isNull(); + assertThat(response.getRootTimestamp()).isNull(); + assertThat(response.isTruncated()).isFalse(); + assertThat(response.getAllExceptions()).isEmpty(); + assertThat(response.getExceptionHistory().getEntries()).isEmpty(); } @Test - public void testOnlyRootCause() + void testOnlyRootCause() throws HandlerRequestException, ExecutionException, InterruptedException { final Throwable rootCause = new RuntimeException("root cause"); final long rootCauseTimestamp = System.currentTimeMillis(); @@ -125,18 +119,22 @@ public void testOnlyRootCause() final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat(response.getRootException(), is(ExceptionUtils.stringifyException(rootCause))); - assertThat(response.getRootTimestamp(), is(rootCauseTimestamp)); - assertFalse(response.isTruncated()); - assertThat(response.getAllExceptions(), empty()); - - assertThat( - response.getExceptionHistory().getEntries(), - contains(historyContainsGlobalFailure(rootCause, rootCauseTimestamp))); + assertThat(response.getRootException()) + .isEqualTo(ExceptionUtils.stringifyException(rootCause)); + assertThat(response.getRootTimestamp()).isEqualTo(rootCauseTimestamp); + assertThat(response.isTruncated()).isFalse(); + assertThat(response.getAllExceptions()).isEmpty(); + + assertThat(response.getExceptionHistory().getEntries()) + .satisfies( + matching( + contains( + historyContainsGlobalFailure( + rootCause, rootCauseTimestamp)))); } @Test - public void testOnlyExceptionHistory() + void testOnlyExceptionHistory() throws HandlerRequestException, ExecutionException, InterruptedException { final RuntimeException rootThrowable = new RuntimeException("exception #0"); final long rootTimestamp = System.currentTimeMillis(); @@ -148,17 +146,19 @@ public void testOnlyExceptionHistory() final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat(response.getRootException(), is(nullValue())); - assertThat(response.getRootTimestamp(), is(nullValue())); + assertThat(response.getRootException()).isNull(); + assertThat(response.getRootTimestamp()).isNull(); - assertThat( - response.getExceptionHistory().getEntries(), - contains(historyContainsGlobalFailure(rootThrowable, rootTimestamp))); + assertThat(response.getExceptionHistory().getEntries()) + .satisfies( + matching( + contains( + historyContainsGlobalFailure( + rootThrowable, rootTimestamp)))); } @Test - public void testOnlyExceptionHistoryWithNoMatchingFailureLabel() - throws HandlerRequestException { + void testOnlyExceptionHistoryWithNoMatchingFailureLabel() throws HandlerRequestException { final RuntimeException rootThrowable = new RuntimeException("exception #0"); final long rootTimestamp = System.currentTimeMillis(); final RootExceptionHistoryEntry rootEntry = fromGlobalFailure(rootThrowable, rootTimestamp); @@ -170,14 +170,14 @@ public void testOnlyExceptionHistoryWithNoMatchingFailureLabel() final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat(response.getRootException(), is(nullValue())); - assertThat(response.getRootTimestamp(), is(nullValue())); + assertThat(response.getRootException()).isNull(); + assertThat(response.getRootTimestamp()).isNull(); - assertThat(response.getExceptionHistory().getEntries(), is(empty())); + assertThat(response.getExceptionHistory().getEntries()).isEmpty(); } @Test - public void testWithExceptionHistory() + void testWithExceptionHistory() throws HandlerRequestException, ExecutionException, InterruptedException { final RootExceptionHistoryEntry rootCause = fromGlobalFailure(new RuntimeException("exception #0"), System.currentTimeMillis()); @@ -197,25 +197,26 @@ public void testWithExceptionHistory() final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat( - response.getExceptionHistory().getEntries(), - contains( - historyContainsGlobalFailure( - rootCause.getException(), rootCause.getTimestamp()), - historyContainsJobExceptionInfo( - otherFailure.getException(), - otherFailure.getTimestamp(), - otherFailure.getFailureLabelsFuture(), - otherFailure.getFailingTaskName(), - JobExceptionsHandler.toString( - otherFailure.getTaskManagerLocation()), - JobExceptionsHandler.toTaskManagerId( - otherFailure.getTaskManagerLocation())))); - assertFalse(response.getExceptionHistory().isTruncated()); + assertThat(response.getExceptionHistory().getEntries()) + .satisfies( + matching( + contains( + historyContainsGlobalFailure( + rootCause.getException(), rootCause.getTimestamp()), + historyContainsJobExceptionInfo( + otherFailure.getException(), + otherFailure.getTimestamp(), + otherFailure.getFailureLabelsFuture(), + otherFailure.getFailingTaskName(), + JobExceptionsHandler.toString( + otherFailure.getTaskManagerLocation()), + JobExceptionsHandler.toTaskManagerId( + otherFailure.getTaskManagerLocation()))))); + assertThat(response.getExceptionHistory().isTruncated()).isFalse(); } @Test - public void testWithExceptionHistoryWithMatchingFailureLabel() + void testWithExceptionHistoryWithMatchingFailureLabel() throws HandlerRequestException, ExecutionException, InterruptedException { final RootExceptionHistoryEntry rootCause = fromGlobalFailure(new RuntimeException("exception #0"), System.currentTimeMillis()); @@ -269,24 +270,26 @@ public void testWithExceptionHistoryWithMatchingFailureLabel() final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat(response.getExceptionHistory().getEntries().size(), is(1)); - assertThat( - response.getExceptionHistory().getEntries(), - contains( - historyContainsJobExceptionInfo( - matchingFailure.getException(), - matchingFailure.getTimestamp(), - matchingFailure.getFailureLabelsFuture(), - matchingFailure.getFailingTaskName(), - JobExceptionsHandler.toString( - matchingFailure.getTaskManagerLocation()), - JobExceptionsHandler.toTaskManagerId( - matchingFailure.getTaskManagerLocation())))); - assertFalse(response.getExceptionHistory().isTruncated()); + assertThat(response.getExceptionHistory().getEntries()).hasSize(1); + assertThat(response.getExceptionHistory().getEntries()) + .satisfies( + matching( + contains( + historyContainsJobExceptionInfo( + matchingFailure.getException(), + matchingFailure.getTimestamp(), + matchingFailure.getFailureLabelsFuture(), + matchingFailure.getFailingTaskName(), + JobExceptionsHandler.toString( + matchingFailure.getTaskManagerLocation()), + JobExceptionsHandler.toTaskManagerId( + matchingFailure + .getTaskManagerLocation()))))); + assertThat(response.getExceptionHistory().isTruncated()).isFalse(); } @Test - public void testWithLocalExceptionHistoryEntryNotHavingATaskManagerInformationAvailable() + void testWithLocalExceptionHistoryEntryNotHavingATaskManagerInformationAvailable() throws HandlerRequestException, ExecutionException, InterruptedException { final RootExceptionHistoryEntry failure = new RootExceptionHistoryEntry( @@ -303,21 +306,23 @@ public void testWithLocalExceptionHistoryEntryNotHavingATaskManagerInformationAv final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat( - response.getExceptionHistory().getEntries(), - contains( - historyContainsJobExceptionInfo( - failure.getException(), - failure.getTimestamp(), - failure.getFailureLabelsFuture(), - failure.getFailingTaskName(), - JobExceptionsHandler.toString(failure.getTaskManagerLocation()), - JobExceptionsHandler.toTaskManagerId( - failure.getTaskManagerLocation())))); + assertThat(response.getExceptionHistory().getEntries()) + .satisfies( + matching( + contains( + historyContainsJobExceptionInfo( + failure.getException(), + failure.getTimestamp(), + failure.getFailureLabelsFuture(), + failure.getFailingTaskName(), + JobExceptionsHandler.toString( + failure.getTaskManagerLocation()), + JobExceptionsHandler.toTaskManagerId( + failure.getTaskManagerLocation()))))); } @Test - public void testWithExceptionHistoryWithTruncationThroughParameter() + void testWithExceptionHistoryWithTruncationThroughParameter() throws HandlerRequestException, ExecutionException, InterruptedException { final RootExceptionHistoryEntry rootCause = fromGlobalFailure(new RuntimeException("exception #0"), System.currentTimeMillis()); @@ -337,54 +342,57 @@ public void testWithExceptionHistoryWithTruncationThroughParameter() final JobExceptionsInfoWithHistory response = testInstance.handleRequest(request, executionGraphInfo); - assertThat( - response.getExceptionHistory().getEntries(), - contains( - historyContainsGlobalFailure( - rootCause.getException(), rootCause.getTimestamp()))); - assertThat(response.getExceptionHistory().getEntries(), iterableWithSize(1)); - assertTrue(response.getExceptionHistory().isTruncated()); + assertThat(response.getExceptionHistory().getEntries()) + .satisfies( + matching( + contains( + historyContainsGlobalFailure( + rootCause.getException(), + rootCause.getTimestamp())))); + + assertThat(response.getExceptionHistory().getEntries()) + .satisfies(matching(iterableWithSize(1))); + assertThat(response.getExceptionHistory().isTruncated()).isTrue(); } @Test - public void testTaskManagerLocationFallbackHandling() { - assertThat(JobExceptionsHandler.toString((TaskManagerLocation) null), is("(unassigned)")); + void testTaskManagerLocationFallbackHandling() { + assertThat(JobExceptionsHandler.toString((TaskManagerLocation) null)) + .isEqualTo("(unassigned)"); } @Test - public void testTaskManagerLocationHandling() { + void testTaskManagerLocationHandling() { final TaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation(); - assertThat( - JobExceptionsHandler.toString(taskManagerLocation), - is( + assertThat(JobExceptionsHandler.toString(taskManagerLocation)) + .isEqualTo( String.format( "%s:%s", taskManagerLocation.getFQDNHostname(), - taskManagerLocation.dataPort()))); + taskManagerLocation.dataPort())); } @Test - public void testArchivedTaskManagerLocationFallbackHandling() { + void testArchivedTaskManagerLocationFallbackHandling() { assertThat( - JobExceptionsHandler.toString( - (ExceptionHistoryEntry.ArchivedTaskManagerLocation) null), - is(nullValue())); + JobExceptionsHandler.toString( + (ExceptionHistoryEntry.ArchivedTaskManagerLocation) null)) + .isNull(); } @Test - public void testArchivedTaskManagerLocationHandling() { + void testArchivedTaskManagerLocationHandling() { final TaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation(); - assertThat( - JobExceptionsHandler.toString(taskManagerLocation), - is( + assertThat(JobExceptionsHandler.toString(taskManagerLocation)) + .isEqualTo( String.format( "%s:%s", taskManagerLocation.getFQDNHostname(), - taskManagerLocation.dataPort()))); + taskManagerLocation.dataPort())); } @Test - public void testGetJobExceptionsInfo() throws HandlerRequestException { + void testGetJobExceptionsInfo() throws HandlerRequestException { final int numExceptions = 20; final ExecutionGraphInfo archivedExecutionGraph = createAccessExecutionGraph(numExceptions); checkExceptionLimit(testInstance, archivedExecutionGraph, numExceptions, 10); @@ -403,7 +411,7 @@ private static void checkExceptionLimit( final JobExceptionsInfo jobExceptionsInfo = jobExceptionsHandler.handleRequest(handlerRequest, graph); final int numReportedException = Math.min(maxNumExceptions, numExpectedException); - assertEquals(jobExceptionsInfo.getAllExceptions().size(), numReportedException); + assertThat(numReportedException).isEqualTo(jobExceptionsInfo.getAllExceptions().size()); } private static ExecutionGraphInfo createAccessExecutionGraph(int numTasks) { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExecutionResultHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExecutionResultHandlerTest.java index 36e450ca133543..f22449600b3f4c 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExecutionResultHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobExecutionResultHandlerTest.java @@ -33,27 +33,22 @@ import org.apache.flink.runtime.rest.messages.queue.QueueStatus; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.util.ExceptionUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** Tests for {@link JobExecutionResultHandler}. */ -public class JobExecutionResultHandlerTest extends TestLogger { +class JobExecutionResultHandlerTest { private static final JobID TEST_JOB_ID = new JobID(); @@ -61,8 +56,8 @@ public class JobExecutionResultHandlerTest extends TestLogger { private HandlerRequest testRequest; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder().build(); @@ -82,7 +77,7 @@ public void setUp() throws Exception { } @Test - public void testResultInProgress() throws Exception { + void testResultInProgress() throws Exception { final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() .setRequestJobStatusFunction( @@ -92,11 +87,11 @@ public void testResultInProgress() throws Exception { final JobExecutionResultResponseBody responseBody = jobExecutionResultHandler.handleRequest(testRequest, testingRestfulGateway).get(); - assertThat(responseBody.getStatus().getId(), equalTo(QueueStatus.Id.IN_PROGRESS)); + assertThat(responseBody.getStatus().getId()).isEqualTo(QueueStatus.Id.IN_PROGRESS); } @Test - public void testCompletedResult() throws Exception { + void testCompletedResult() throws Exception { final JobStatus jobStatus = JobStatus.FINISHED; final ArchivedExecutionGraph executionGraph = new ArchivedExecutionGraphBuilder() @@ -108,12 +103,12 @@ public void testCompletedResult() throws Exception { new TestingRestfulGateway.Builder() .setRequestJobStatusFunction( jobId -> { - assertThat(jobId, equalTo(TEST_JOB_ID)); + assertThat(jobId).isEqualTo(TEST_JOB_ID); return CompletableFuture.completedFuture(jobStatus); }) .setRequestJobResultFunction( jobId -> { - assertThat(jobId, equalTo(TEST_JOB_ID)); + assertThat(jobId).isEqualTo(TEST_JOB_ID); return CompletableFuture.completedFuture( JobResult.createFrom(executionGraph)); }) @@ -122,12 +117,12 @@ public void testCompletedResult() throws Exception { final JobExecutionResultResponseBody responseBody = jobExecutionResultHandler.handleRequest(testRequest, testingRestfulGateway).get(); - assertThat(responseBody.getStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); - assertThat(responseBody.getJobExecutionResult(), not(nullValue())); + assertThat(responseBody.getStatus().getId()).isEqualTo(QueueStatus.Id.COMPLETED); + assertThat(responseBody.getJobExecutionResult()).isNotNull(); } @Test - public void testPropagateFlinkJobNotFoundExceptionAsRestHandlerException() throws Exception { + void testPropagateFlinkJobNotFoundExceptionAsRestHandlerException() throws Exception { final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() .setRequestJobStatusFunction( @@ -141,10 +136,9 @@ public void testPropagateFlinkJobNotFoundExceptionAsRestHandlerException() throw fail("Expected exception not thrown"); } catch (final ExecutionException e) { final Throwable cause = ExceptionUtils.stripCompletionException(e.getCause()); - assertThat(cause, instanceOf(RestHandlerException.class)); - assertThat( - ((RestHandlerException) cause).getHttpResponseStatus(), - equalTo(HttpResponseStatus.NOT_FOUND)); + assertThat(cause).isInstanceOf(RestHandlerException.class); + assertThat(((RestHandlerException) cause).getHttpResponseStatus()) + .isEqualTo(HttpResponseStatus.NOT_FOUND); } } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobManagerJobConfigurationHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobManagerJobConfigurationHandlerTest.java index 855bf4724a643e..92ceb482d603d6 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobManagerJobConfigurationHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobManagerJobConfigurationHandlerTest.java @@ -27,19 +27,18 @@ import org.apache.flink.runtime.rest.messages.job.JobManagerJobConfigurationHeaders; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.testutils.TestingUtils; -import org.apache.flink.util.TestLogger; import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Test for the {@link JobManagerJobConfigurationHandler}. */ -public class JobManagerJobConfigurationHandlerTest extends TestLogger { +class JobManagerJobConfigurationHandlerTest { @Test - public void testRequestConfiguration() throws Exception { + void testRequestConfiguration() throws Exception { final Configuration configuration = new Configuration(); configuration.set(JobManagerOptions.ADDRESS, "address"); @@ -62,7 +61,7 @@ public void testRequestConfiguration() throws Exception { new TestingRestfulGateway.Builder().build()) .get(); - assertEquals(JobManagerOptions.ADDRESS.key(), configurationInfo.get(0).getKey()); - assertEquals("address", configurationInfo.get(0).getValue()); + assertThat(configurationInfo.get(0).getKey()).isEqualTo(JobManagerOptions.ADDRESS.key()); + assertThat(configurationInfo.get(0).getValue()).isEqualTo("address"); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobStatusHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobStatusHandlerTest.java index a110cce3b2f7fe..d96deaa812d2d9 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobStatusHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobStatusHandlerTest.java @@ -29,21 +29,20 @@ import org.apache.flink.runtime.rest.messages.job.JobStatusInfoHeaders; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.testutils.TestingUtils; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Test for the {@link JobStatusHandler}. */ -public class JobStatusHandlerTest extends TestLogger { +class JobStatusHandlerTest { @Test - public void testRequestJobStatus() throws Exception { + void testRequestJobStatus() throws Exception { final JobStatusHandler jobStatusHandler = new JobStatusHandler( CompletableFuture::new, @@ -62,7 +61,7 @@ public void testRequestJobStatus() throws Exception { JobStatus.INITIALIZING)) .build()); - assertEquals(response.get().getJobStatus(), JobStatus.INITIALIZING); + assertThat(JobStatus.INITIALIZING).isEqualTo(response.get().getJobStatus()); } private static HandlerRequest createRequest(JobID jobId) diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobSubmitHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobSubmitHandlerTest.java index 3c9ca8ab6d88e6..516697c347662b 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobSubmitHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobSubmitHandlerTest.java @@ -34,21 +34,20 @@ import org.apache.flink.runtime.rest.messages.job.JobSubmitRequestBody; import org.apache.flink.runtime.rpc.RpcUtils; import org.apache.flink.runtime.webmonitor.TestingDispatcherGateway; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; +import org.apache.flink.testutils.junit.utils.TempDirUtils; import org.apache.flink.util.ExceptionUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -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.BeforeEach; +import org.junit.jupiter.api.TestTemplate; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.io.ObjectOutputStream; @@ -59,11 +58,14 @@ import java.util.Collections; import java.util.concurrent.CompletableFuture; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + /** Tests for the {@link JobSubmitHandler}. */ -@RunWith(Parameterized.class) -public class JobSubmitHandlerTest extends TestLogger { +@ExtendWith(ParameterizedTestExtension.class) +public class JobSubmitHandlerTest { - @Parameterized.Parameters(name = "SSL enabled: {0}") + @Parameters(name = "SSL enabled: {0}") public static Iterable> data() { ArrayList> parameters = new ArrayList<>(3); parameters.add(Tuple2.of(false, "no SSL")); @@ -73,7 +75,7 @@ public static Iterable> data() { return parameters; } - @ClassRule public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder(); + @TempDir public static java.nio.file.Path temporaryFolder; private final Configuration configuration; @@ -86,24 +88,26 @@ public JobSubmitHandlerTest(Tuple2 withSsl) { : new Configuration(); } - @Before - public void setup() throws IOException { + @BeforeEach + void setup() throws IOException { Configuration config = new Configuration(configuration); - blobServer = new BlobServer(config, TEMPORARY_FOLDER.newFolder(), new VoidBlobStore()); + blobServer = + new BlobServer( + config, TempDirUtils.newFolder(temporaryFolder), new VoidBlobStore()); blobServer.start(); } - @After - public void teardown() throws IOException { + @AfterEach + void teardown() throws IOException { if (blobServer != null) { blobServer.close(); } } - @Test - public void testSerializationFailureHandling() throws Exception { - final Path jobGraphFile = TEMPORARY_FOLDER.newFile().toPath(); + @TestTemplate + void testSerializationFailureHandling() throws Exception { + final Path jobGraphFile = TempDirUtils.newFolder(temporaryFolder).toPath(); DispatcherGateway mockGateway = TestingDispatcherGateway.newBuilder() .setSubmitFunction( @@ -126,15 +130,15 @@ public void testSerializationFailureHandling() throws Exception { handler.handleRequest( HandlerRequest.create(request, EmptyMessageParameters.getInstance()), mockGateway); - Assert.fail(); + fail("Expected exception not thrown"); } catch (RestHandlerException rhe) { - Assert.assertEquals(HttpResponseStatus.BAD_REQUEST, rhe.getHttpResponseStatus()); + assertThat(rhe.getHttpResponseStatus()).isEqualTo(HttpResponseStatus.BAD_REQUEST); } } - @Test - public void testSuccessfulJobSubmission() throws Exception { - final Path jobGraphFile = TEMPORARY_FOLDER.newFile().toPath(); + @TestTemplate + void testSuccessfulJobSubmission() throws Exception { + final Path jobGraphFile = TempDirUtils.newFile(temporaryFolder).toPath(); try (ObjectOutputStream objectOut = new ObjectOutputStream(Files.newOutputStream(jobGraphFile))) { objectOut.writeObject(JobGraphTestUtils.emptyJobGraph()); @@ -169,14 +173,14 @@ public void testSuccessfulJobSubmission() throws Exception { .get(); } - @Test - public void testRejectionOnCountMismatch() throws Exception { - final Path jobGraphFile = TEMPORARY_FOLDER.newFile().toPath(); + @TestTemplate + void testRejectionOnCountMismatch() throws Exception { + final Path jobGraphFile = TempDirUtils.newFile(temporaryFolder).toPath(); try (ObjectOutputStream objectOut = new ObjectOutputStream(Files.newOutputStream(jobGraphFile))) { objectOut.writeObject(JobGraphTestUtils.emptyJobGraph()); } - final Path countExceedingFile = TEMPORARY_FOLDER.newFile().toPath(); + final Path countExceedingFile = TempDirUtils.newFolder(temporaryFolder).toPath(); TestingDispatcherGateway.Builder builder = TestingDispatcherGateway.newBuilder(); builder.setBlobServerPort(blobServer.getPort()) @@ -216,8 +220,8 @@ public void testRejectionOnCountMismatch() throws Exception { } } - @Test - public void testFileHandling() throws Exception { + @TestTemplate + void testFileHandling() throws Exception { final String dcEntryName = "entry"; CompletableFuture submittedJobGraphFuture = new CompletableFuture<>(); @@ -239,9 +243,9 @@ public void testFileHandling() throws Exception { Executors.directExecutor(), configuration); - final Path jobGraphFile = TEMPORARY_FOLDER.newFile().toPath(); - final Path jarFile = TEMPORARY_FOLDER.newFile().toPath(); - final Path artifactFile = TEMPORARY_FOLDER.newFile().toPath(); + final Path jobGraphFile = TempDirUtils.newFile(temporaryFolder).toPath(); + final Path jarFile = TempDirUtils.newFile(temporaryFolder).toPath(); + final Path artifactFile = TempDirUtils.newFile(temporaryFolder).toPath(); final JobGraph jobGraph = JobGraphTestUtils.emptyJobGraph(); // the entry that should be updated @@ -271,15 +275,16 @@ public void testFileHandling() throws Exception { dispatcherGateway) .get(); - Assert.assertTrue("No JobGraph was submitted.", submittedJobGraphFuture.isDone()); + assertThat(submittedJobGraphFuture).as("No JobGraph was submitted.") + .isCompleted(); final JobGraph submittedJobGraph = submittedJobGraphFuture.get(); - Assert.assertEquals(1, submittedJobGraph.getUserJarBlobKeys().size()); - Assert.assertEquals(1, submittedJobGraph.getUserArtifacts().size()); - Assert.assertNotNull(submittedJobGraph.getUserArtifacts().get(dcEntryName).blobKey); + assertThat(submittedJobGraph.getUserJarBlobKeys()).hasSize(1); + assertThat(submittedJobGraph.getUserArtifacts()).hasSize(1); + assertThat(submittedJobGraph.getUserArtifacts().get(dcEntryName).blobKey).isNotNull(); } - @Test - public void testFailedJobSubmission() throws Exception { + @TestTemplate + void testFailedJobSubmission() throws Exception { final String errorMessage = "test"; DispatcherGateway mockGateway = TestingDispatcherGateway.newBuilder() @@ -297,7 +302,7 @@ public void testFailedJobSubmission() throws Exception { Executors.directExecutor(), configuration); - final Path jobGraphFile = TEMPORARY_FOLDER.newFile().toPath(); + final Path jobGraphFile = TempDirUtils.newFile(temporaryFolder).toPath(); JobGraph jobGraph = JobGraphTestUtils.emptyJobGraph(); try (ObjectOutputStream objectOut = @@ -320,7 +325,7 @@ public void testFailedJobSubmission() throws Exception { .get(); } catch (Exception e) { Throwable t = ExceptionUtils.stripExecutionException(e); - Assert.assertEquals(errorMessage, t.getMessage()); + assertThat(t.getMessage()).isEqualTo(errorMessage); } } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobVertexFlameGraphHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobVertexFlameGraphHandlerTest.java index dd8434114c69ab..8f73f9c7ac56b0 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobVertexFlameGraphHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/JobVertexFlameGraphHandlerTest.java @@ -44,7 +44,6 @@ import org.apache.flink.runtime.webmonitor.threadinfo.VertexFlameGraph; import org.apache.flink.runtime.webmonitor.threadinfo.VertexThreadInfoStats; import org.apache.flink.util.FlinkException; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; import org.junit.jupiter.api.BeforeAll; @@ -60,7 +59,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** Tests of {@link JobVertexFlameGraphHandler}. */ -public class JobVertexFlameGraphHandlerTest extends TestLogger { +class JobVertexFlameGraphHandlerTest { private static final JobID JOB_ID = new JobID(); private static final JobVertexID JOB_VERTEX_ID = new JobVertexID(); @@ -69,7 +68,7 @@ public class JobVertexFlameGraphHandlerTest extends TestLogger { private static JobVertexFlameGraphHandler handler; @BeforeAll - public static void setUp() { + static void setUp() { taskThreadInfoStatsDefaultSample = new VertexThreadInfoStats( 8, diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskCurrentAttemptDetailsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskCurrentAttemptDetailsHandlerTest.java index 70f46c1d302119..be4938ab96faa0 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskCurrentAttemptDetailsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskCurrentAttemptDetailsHandlerTest.java @@ -43,23 +43,22 @@ import org.apache.flink.runtime.rest.messages.job.SubtaskMessageParameters; import org.apache.flink.runtime.rest.messages.job.metrics.IOMetricsInfo; import org.apache.flink.runtime.taskmanager.LocalTaskManagerLocation; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests of {@link SubtaskCurrentAttemptDetailsHandler}. */ -public class SubtaskCurrentAttemptDetailsHandlerTest extends TestLogger { +class SubtaskCurrentAttemptDetailsHandlerTest { @Test - public void testHandleRequest() throws Exception { + void testHandleRequest() throws Exception { // Prepare the execution graph. final JobID jobID = new JobID(); @@ -195,6 +194,6 @@ public void testHandleRequest() throws Exception { statusDuration, null); - assertEquals(expectedDetailsInfo, detailsInfo); + assertThat(detailsInfo).isEqualTo(expectedDetailsInfo); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptAccumulatorsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptAccumulatorsHandlerTest.java index bf1b9561e43986..ecb44860b1f0a0 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptAccumulatorsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptAccumulatorsHandlerTest.java @@ -37,10 +37,9 @@ import org.apache.flink.runtime.rest.messages.job.UserAccumulator; import org.apache.flink.util.FlinkRuntimeException; import org.apache.flink.util.OptionalFailure; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; @@ -48,13 +47,13 @@ import java.util.Map; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests of {@link SubtaskExecutionAttemptAccumulatorsHandler}. */ -public class SubtaskExecutionAttemptAccumulatorsHandlerTest extends TestLogger { +class SubtaskExecutionAttemptAccumulatorsHandlerTest { @Test - public void testHandleRequest() throws Exception { + void testHandleRequest() throws Exception { // Instance the handler. final RestHandlerConfiguration restHandlerConfiguration = @@ -124,6 +123,6 @@ public void testHandleRequest() throws Exception { userAccumulatorList); // Verify. - assertEquals(expected, accumulatorsInfo); + assertThat(accumulatorsInfo).isEqualTo(expected); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptDetailsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptDetailsHandlerTest.java index 40f2286d7228ac..ba828377f4409b 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptDetailsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/SubtaskExecutionAttemptDetailsHandlerTest.java @@ -45,23 +45,22 @@ import org.apache.flink.runtime.rest.messages.job.SubtaskExecutionAttemptDetailsHeaders; import org.apache.flink.runtime.rest.messages.job.SubtaskExecutionAttemptDetailsInfo; import org.apache.flink.runtime.rest.messages.job.metrics.IOMetricsInfo; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests of {@link SubtaskExecutionAttemptDetailsHandler}. */ -public class SubtaskExecutionAttemptDetailsHandlerTest extends TestLogger { +class SubtaskExecutionAttemptDetailsHandlerTest { @Test - public void testHandleRequest() throws Exception { + void testHandleRequest() throws Exception { final JobID jobID = new JobID(); final JobVertexID jobVertexId = new JobVertexID(); @@ -198,6 +197,6 @@ public void testHandleRequest() throws Exception { statusDuration, null); - assertEquals(expectedDetailsInfo, detailsInfo); + assertThat(detailsInfo).isEqualTo(expectedDetailsInfo); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/AbstractCheckpointStatsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/AbstractCheckpointStatsHandlerTest.java index f18cf985c5cae9..9f629a84916e0a 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/AbstractCheckpointStatsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/AbstractCheckpointStatsHandlerTest.java @@ -36,7 +36,6 @@ import org.apache.flink.runtime.webmonitor.RestfulGateway; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; import org.apache.flink.shaded.guava31.com.google.common.cache.Cache; @@ -56,7 +55,7 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; /** Test class for {@link AbstractCheckpointStatsHandler}. */ -public class AbstractCheckpointStatsHandlerTest extends TestLogger { +class AbstractCheckpointStatsHandlerTest { private static final Time TIMEOUT = Time.seconds(10); @@ -67,7 +66,7 @@ public class AbstractCheckpointStatsHandlerTest extends TestLogger { 10, UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup()); @Test - public void testRetrieveSnapshotFromCache() throws Exception { + void testRetrieveSnapshotFromCache() throws Exception { GatewayRetriever leaderRetriever = () -> CompletableFuture.completedFuture(null); CheckpointingStatistics checkpointingStatistics = getTestCheckpointingStatistics(); @@ -128,7 +127,7 @@ public void testRetrieveSnapshotFromCache() throws Exception { } @Test - public void testRestExceptionPassedThrough() throws Exception { + void testRestExceptionPassedThrough() throws Exception { GatewayRetriever leaderRetriever = () -> CompletableFuture.completedFuture(null); CheckpointStatsSnapshot checkpointStatsSnapshot1 = getTestCheckpointStatsSnapshot(); @@ -171,7 +170,7 @@ public void testRestExceptionPassedThrough() throws Exception { } @Test - public void testFlinkJobNotFoundException() throws Exception { + void testFlinkJobNotFoundException() throws Exception { GatewayRetriever leaderRetriever = () -> CompletableFuture.completedFuture(null); CheckpointStatsSnapshot checkpointStatsSnapshot1 = getTestCheckpointStatsSnapshot(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/CheckpointHandlersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/CheckpointHandlersTest.java index 8152a1ba08bdbb..1d8ff99696314c 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/CheckpointHandlersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/checkpoints/CheckpointHandlersTest.java @@ -42,7 +42,6 @@ import org.apache.flink.runtime.webmonitor.RestfulGateway; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; @@ -61,7 +60,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** Test for {@link CheckpointHandlers}. */ -class CheckpointHandlersTest extends TestLogger { +class CheckpointHandlersTest { private static final Time TIMEOUT = Time.seconds(10); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AbstractMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AbstractMetricsHandlerTest.java index 4ca852e21078c5..823498181d75db 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AbstractMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AbstractMetricsHandlerTest.java @@ -35,10 +35,9 @@ import org.apache.flink.runtime.rest.messages.job.metrics.MetricCollectionResponseBody; import org.apache.flink.runtime.rest.messages.job.metrics.MetricsFilterParameter; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; -import org.apache.flink.util.TestLogger; -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.MockitoAnnotations; @@ -49,15 +48,11 @@ import java.util.Map; import java.util.concurrent.CompletableFuture; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; /** Tests for {@link AbstractMetricsHandler}. */ -public class AbstractMetricsHandlerTest extends TestLogger { +class AbstractMetricsHandlerTest { private static final String TEST_METRIC_NAME = "test_counter"; @@ -71,8 +66,8 @@ public class AbstractMetricsHandlerTest extends TestLogger { private TestMetricsHandler testMetricsHandler; - @Before - public void setUp() { + @BeforeEach + void setUp() { MockitoAnnotations.initMocks(this); final MetricStore metricStore = new MetricStore(); @@ -99,7 +94,7 @@ public CompletableFuture getFuture() { } @Test - public void testListMetrics() throws Exception { + void testListMetrics() throws Exception { final CompletableFuture completableFuture = testMetricsHandler.handleRequest( HandlerRequest.create( @@ -108,18 +103,18 @@ public void testListMetrics() throws Exception { Collections.emptyList()), mockDispatcherGateway); - assertTrue(completableFuture.isDone()); + assertThat(completableFuture).isDone(); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); - assertThat(metricCollectionResponseBody.getMetrics(), hasSize(1)); + assertThat(metricCollectionResponseBody.getMetrics()).hasSize(1); final Metric metric = metricCollectionResponseBody.getMetrics().iterator().next(); - assertThat(metric.getId(), equalTo(TEST_METRIC_NAME)); - assertThat(metric.getValue(), equalTo(null)); + assertThat(metric.getId()).isEqualTo(TEST_METRIC_NAME); + assertThat(metric.getValue()).isNull(); } @Test - public void testReturnEmptyListIfNoComponentMetricStore() throws Exception { + void testReturnEmptyListIfNoComponentMetricStore() throws Exception { testMetricsHandler.returnComponentMetricStore = false; final CompletableFuture completableFuture = @@ -130,14 +125,14 @@ public void testReturnEmptyListIfNoComponentMetricStore() throws Exception { Collections.emptyList()), mockDispatcherGateway); - assertTrue(completableFuture.isDone()); + assertThat(completableFuture).isDone(); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); - assertThat(metricCollectionResponseBody.getMetrics(), empty()); + assertThat(metricCollectionResponseBody.getMetrics()).isEmpty(); } @Test - public void testGetMetrics() throws Exception { + void testGetMetrics() throws Exception { final CompletableFuture completableFuture = testMetricsHandler.handleRequest( HandlerRequest.resolveParametersAndCreate( @@ -150,18 +145,18 @@ public void testGetMetrics() throws Exception { Collections.emptyList()), mockDispatcherGateway); - assertTrue(completableFuture.isDone()); + assertThat(completableFuture).isDone(); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); - assertThat(metricCollectionResponseBody.getMetrics(), hasSize(1)); + assertThat(metricCollectionResponseBody.getMetrics()).hasSize(1); final Metric metric = metricCollectionResponseBody.getMetrics().iterator().next(); - assertThat(metric.getId(), equalTo(TEST_METRIC_NAME)); - assertThat(metric.getValue(), equalTo(Integer.toString(TEST_METRIC_VALUE))); + assertThat(metric.getId()).isEqualTo(TEST_METRIC_NAME); + assertThat(metric.getValue()).isEqualTo(Integer.toString(TEST_METRIC_VALUE)); } @Test - public void testReturnEmptyListIfRequestedMetricIsUnknown() throws Exception { + void testReturnEmptyListIfRequestedMetricIsUnknown() throws Exception { final CompletableFuture completableFuture = testMetricsHandler.handleRequest( HandlerRequest.resolveParametersAndCreate( @@ -174,10 +169,10 @@ public void testReturnEmptyListIfRequestedMetricIsUnknown() throws Exception { Collections.emptyList()), mockDispatcherGateway); - assertTrue(completableFuture.isDone()); + assertThat(completableFuture).isDone(); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); - assertThat(metricCollectionResponseBody.getMetrics(), empty()); + assertThat(metricCollectionResponseBody.getMetrics()).isEmpty(); } private static class TestMetricsHandler extends AbstractMetricsHandler { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingJobsMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingJobsMetricsHandlerTest.java index 7c7c8ff3ff839c..fe832aa5d8a57f 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingJobsMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingJobsMetricsHandlerTest.java @@ -36,7 +36,7 @@ import java.util.concurrent.Executor; /** Tests for the {@link AggregatingJobsMetricsHandler}. */ -public class AggregatingJobsMetricsHandlerTest +class AggregatingJobsMetricsHandlerTest extends AggregatingMetricsHandlerTestBase< AggregatingJobsMetricsHandler, AggregatedJobMetricsParameters> { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingMetricsHandlerTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingMetricsHandlerTestBase.java index 5e0b5fdbeebfe7..698e5652d550e2 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingMetricsHandlerTestBase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingMetricsHandlerTestBase.java @@ -35,11 +35,10 @@ import org.apache.flink.runtime.webmonitor.TestingDispatcherGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; import org.apache.flink.testutils.TestingUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.Executors; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collection; @@ -52,14 +51,13 @@ import java.util.concurrent.Executor; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.within; /** Test base for handlers that extend {@link AbstractAggregatingMetricsHandler}. */ -public abstract class AggregatingMetricsHandlerTestBase< - H extends AbstractAggregatingMetricsHandler

, - P extends AbstractAggregatedMetricsParameters> - extends TestLogger { +abstract class AggregatingMetricsHandlerTestBase< + H extends AbstractAggregatingMetricsHandler

, + P extends AbstractAggregatedMetricsParameters> { private static final DispatcherGateway MOCK_DISPATCHER_GATEWAY; private static final GatewayRetriever LEADER_RETRIEVER; @@ -82,8 +80,8 @@ public CompletableFuture getFuture() { private MetricStore store; private Map pathParameters; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { MetricFetcher fetcher = new MetricFetcherImpl<>( () -> null, @@ -124,7 +122,7 @@ protected abstract H getHandler( MetricFetcher fetcher); @Test - public void getStores() throws Exception { + void getStores() throws Exception { { // test without filter HandlerRequest request = HandlerRequest.resolveParametersAndCreate( @@ -136,7 +134,7 @@ public void getStores() throws Exception { Collection subStores = handler.getStores(store, request); - assertEquals(3, subStores.size()); + assertThat(subStores).hasSize(3); List sortedMetrics1 = subStores.stream() @@ -145,10 +143,10 @@ public void getStores() throws Exception { .sorted() .collect(Collectors.toList()); - assertEquals(2, sortedMetrics1.size()); + assertThat(sortedMetrics1).hasSize(2); - assertEquals("1", sortedMetrics1.get(0)); - assertEquals("3", sortedMetrics1.get(1)); + assertThat(sortedMetrics1.get(0)).isEqualTo("1"); + assertThat(sortedMetrics1.get(1)).isEqualTo("3"); List sortedMetrics2 = subStores.stream() @@ -157,9 +155,9 @@ public void getStores() throws Exception { .sorted() .collect(Collectors.toList()); - assertEquals(1, sortedMetrics2.size()); + assertThat(sortedMetrics2).hasSize(1); - assertEquals("5", sortedMetrics2.get(0)); + assertThat(sortedMetrics2.get(0)).isEqualTo("5"); } { // test with filter @@ -176,7 +174,7 @@ public void getStores() throws Exception { Collection subStores = handler.getStores(store, request); - assertEquals(2, subStores.size()); + assertThat(subStores).hasSize(2); List sortedMetrics1 = subStores.stream() @@ -185,9 +183,9 @@ public void getStores() throws Exception { .sorted() .collect(Collectors.toList()); - assertEquals(1, sortedMetrics1.size()); + assertThat(sortedMetrics1).hasSize(1); - assertEquals("1", sortedMetrics1.get(0)); + assertThat(sortedMetrics1.get(0)).isEqualTo("1"); List sortedMetrics2 = subStores.stream() @@ -196,14 +194,14 @@ public void getStores() throws Exception { .sorted() .collect(Collectors.toList()); - assertEquals(1, sortedMetrics2.size()); + assertThat(sortedMetrics2).hasSize(1); - assertEquals("5", sortedMetrics2.get(0)); + assertThat(sortedMetrics2.get(0)).isEqualTo("5"); } } @Test - public void testListMetrics() throws Exception { + void testListMetrics() throws Exception { HandlerRequest request = HandlerRequest.resolveParametersAndCreate( EmptyRequestBody.getInstance(), @@ -221,13 +219,13 @@ public void testListMetrics() throws Exception { .sorted() .collect(Collectors.toList()); - assertEquals(2, availableMetrics.size()); - assertEquals("abc.metric1", availableMetrics.get(0)); - assertEquals("abc.metric2", availableMetrics.get(1)); + assertThat(availableMetrics).hasSize(2); + assertThat(availableMetrics.get(0)).isEqualTo("abc.metric1"); + assertThat(availableMetrics.get(1)).isEqualTo("abc.metric2"); } @Test - public void testMinAggregation() throws Exception { + void testMinAggregation() throws Exception { Map> queryParams = new HashMap<>(4); queryParams.put("get", Collections.singletonList("abc.metric1")); queryParams.put("agg", Collections.singletonList("min")); @@ -245,18 +243,18 @@ public void testMinAggregation() throws Exception { Collection aggregatedMetrics = response.getMetrics(); - assertEquals(1, aggregatedMetrics.size()); + assertThat(aggregatedMetrics).hasSize(1); AggregatedMetric aggregatedMetric = aggregatedMetrics.iterator().next(); - assertEquals("abc.metric1", aggregatedMetric.getId()); - assertEquals(1.0, aggregatedMetric.getMin(), 0.1); - assertNull(aggregatedMetric.getMax()); - assertNull(aggregatedMetric.getSum()); - assertNull(aggregatedMetric.getAvg()); + assertThat(aggregatedMetric.getId()).isEqualTo("abc.metric1"); + assertThat(aggregatedMetric.getMin()).isCloseTo(1.0, within(0.1)); + assertThat(aggregatedMetric.getMax()).isNull(); + assertThat(aggregatedMetric.getSum()).isNull(); + assertThat(aggregatedMetric.getAvg()).isNull(); } @Test - public void testMaxAggregation() throws Exception { + void testMaxAggregation() throws Exception { Map> queryParams = new HashMap<>(4); queryParams.put("get", Collections.singletonList("abc.metric1")); queryParams.put("agg", Collections.singletonList("max")); @@ -274,18 +272,18 @@ public void testMaxAggregation() throws Exception { Collection aggregatedMetrics = response.getMetrics(); - assertEquals(1, aggregatedMetrics.size()); + assertThat(aggregatedMetrics).hasSize(1); AggregatedMetric aggregatedMetric = aggregatedMetrics.iterator().next(); - assertEquals("abc.metric1", aggregatedMetric.getId()); - assertEquals(3.0, aggregatedMetric.getMax(), 0.1); - assertNull(aggregatedMetric.getMin()); - assertNull(aggregatedMetric.getSum()); - assertNull(aggregatedMetric.getAvg()); + assertThat(aggregatedMetric.getId()).isEqualTo("abc.metric1"); + assertThat(aggregatedMetric.getMax()).isCloseTo(3.0, within(0.1)); + assertThat(aggregatedMetric.getMin()).isNull(); + assertThat(aggregatedMetric.getSum()).isNull(); + assertThat(aggregatedMetric.getAvg()).isNull(); } @Test - public void testSumAggregation() throws Exception { + void testSumAggregation() throws Exception { Map> queryParams = new HashMap<>(4); queryParams.put("get", Collections.singletonList("abc.metric1")); queryParams.put("agg", Collections.singletonList("sum")); @@ -303,18 +301,18 @@ public void testSumAggregation() throws Exception { Collection aggregatedMetrics = response.getMetrics(); - assertEquals(1, aggregatedMetrics.size()); + assertThat(aggregatedMetrics).hasSize(1); AggregatedMetric aggregatedMetric = aggregatedMetrics.iterator().next(); - assertEquals("abc.metric1", aggregatedMetric.getId()); - assertEquals(4.0, aggregatedMetric.getSum(), 0.1); - assertNull(aggregatedMetric.getMin()); - assertNull(aggregatedMetric.getMax()); - assertNull(aggregatedMetric.getAvg()); + assertThat(aggregatedMetric.getId()).isEqualTo("abc.metric1"); + assertThat(aggregatedMetric.getSum()).isCloseTo(4.0, within(0.1)); + assertThat(aggregatedMetric.getMin()).isNull(); + assertThat(aggregatedMetric.getMax()).isNull(); + assertThat(aggregatedMetric.getAvg()).isNull(); } @Test - public void testAvgAggregation() throws Exception { + void testAvgAggregation() throws Exception { Map> queryParams = new HashMap<>(4); queryParams.put("get", Collections.singletonList("abc.metric1")); queryParams.put("agg", Collections.singletonList("avg")); @@ -332,18 +330,18 @@ public void testAvgAggregation() throws Exception { Collection aggregatedMetrics = response.getMetrics(); - assertEquals(1, aggregatedMetrics.size()); + assertThat(aggregatedMetrics).hasSize(1); AggregatedMetric aggregatedMetric = aggregatedMetrics.iterator().next(); - assertEquals("abc.metric1", aggregatedMetric.getId()); - assertEquals(2.0, aggregatedMetric.getAvg(), 0.1); - assertNull(aggregatedMetric.getMin()); - assertNull(aggregatedMetric.getMax()); - assertNull(aggregatedMetric.getSum()); + assertThat(aggregatedMetric.getId()).isEqualTo("abc.metric1"); + assertThat(aggregatedMetric.getAvg()).isCloseTo(2.0, within(0.1)); + assertThat(aggregatedMetric.getMin()).isNull(); + assertThat(aggregatedMetric.getMax()).isNull(); + assertThat(aggregatedMetric.getSum()).isNull(); } @Test - public void testMultipleAggregation() throws Exception { + void testMultipleAggregation() throws Exception { Map> queryParams = new HashMap<>(4); queryParams.put("get", Collections.singletonList("abc.metric1")); queryParams.put("agg", Arrays.asList("min", "max", "avg")); @@ -361,18 +359,18 @@ public void testMultipleAggregation() throws Exception { Collection aggregatedMetrics = response.getMetrics(); - assertEquals(1, aggregatedMetrics.size()); + assertThat(aggregatedMetrics).hasSize(1); AggregatedMetric aggregatedMetric = aggregatedMetrics.iterator().next(); - assertEquals("abc.metric1", aggregatedMetric.getId()); - assertEquals(1.0, aggregatedMetric.getMin(), 0.1); - assertEquals(3.0, aggregatedMetric.getMax(), 0.1); - assertEquals(2.0, aggregatedMetric.getAvg(), 0.1); - assertNull(aggregatedMetric.getSum()); + assertThat(aggregatedMetric.getId()).isEqualTo("abc.metric1"); + assertThat(aggregatedMetric.getMin()).isCloseTo(1.0, within(0.1)); + assertThat(aggregatedMetric.getMax()).isCloseTo(3.0, within(0.1)); + assertThat(aggregatedMetric.getAvg()).isCloseTo(2.0, within(0.1)); + assertThat(aggregatedMetric.getSum()).isNull(); } @Test - public void testDefaultAggregation() throws Exception { + void testDefaultAggregation() throws Exception { Map> queryParams = new HashMap<>(4); queryParams.put("get", Collections.singletonList("abc.metric1")); @@ -389,13 +387,13 @@ public void testDefaultAggregation() throws Exception { Collection aggregatedMetrics = response.getMetrics(); - assertEquals(1, aggregatedMetrics.size()); + assertThat(aggregatedMetrics).hasSize(1); AggregatedMetric aggregatedMetric = aggregatedMetrics.iterator().next(); - assertEquals("abc.metric1", aggregatedMetric.getId()); - assertEquals(1.0, aggregatedMetric.getMin(), 0.1); - assertEquals(3.0, aggregatedMetric.getMax(), 0.1); - assertEquals(2.0, aggregatedMetric.getAvg(), 0.1); - assertEquals(4.0, aggregatedMetric.getSum(), 0.1); + assertThat(aggregatedMetric.getId()).isEqualTo("abc.metric1"); + assertThat(aggregatedMetric.getMin()).isCloseTo(1.0, within(0.1)); + assertThat(aggregatedMetric.getMax()).isCloseTo(3.0, within(0.1)); + assertThat(aggregatedMetric.getAvg()).isCloseTo(2.0, within(0.1)); + assertThat(aggregatedMetric.getSum()).isCloseTo(4.0, within(0.1)); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingSubtasksMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingSubtasksMetricsHandlerTest.java index ed13c7da040cd9..d368e58be19083 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingSubtasksMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingSubtasksMetricsHandlerTest.java @@ -40,7 +40,7 @@ import java.util.concurrent.Executor; /** Tests for the {@link AggregatingSubtasksMetricsHandler}. */ -public class AggregatingSubtasksMetricsHandlerTest +class AggregatingSubtasksMetricsHandlerTest extends AggregatingMetricsHandlerTestBase< AggregatingSubtasksMetricsHandler, AggregatedSubtaskMetricsParameters> { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingTaskManagersMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingTaskManagersMetricsHandlerTest.java index ef043fff9c5faf..ed5db69d8fab22 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingTaskManagersMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/AggregatingTaskManagersMetricsHandlerTest.java @@ -36,7 +36,7 @@ import java.util.concurrent.Executor; /** Tests for the {@link AggregatingTaskManagersMetricsHandler}. */ -public class AggregatingTaskManagersMetricsHandlerTest +class AggregatingTaskManagersMetricsHandlerTest extends AggregatingMetricsHandlerTestBase< AggregatingTaskManagersMetricsHandler, AggregateTaskManagerMetricsParameters> { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobManagerMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobManagerMetricsHandlerTestBase.java similarity index 93% rename from flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobManagerMetricsHandlerTest.java rename to flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobManagerMetricsHandlerTestBase.java index d71c452831ebe9..97109ecef75444 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobManagerMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobManagerMetricsHandlerTestBase.java @@ -24,7 +24,7 @@ import java.util.Map; /** Tests for {@link JobManagerMetricsHandler}. */ -public class JobManagerMetricsHandlerTest extends MetricsHandlerTestBase { +class JobManagerMetricsHandlerTestBase extends MetricsHandlerTestBase { @Override JobManagerMetricsHandler getMetricsHandler() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobMetricsHandlerTestBase.java similarity index 95% rename from flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobMetricsHandlerTest.java rename to flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobMetricsHandlerTestBase.java index 577d5c4c8e4e6a..405446ea8f5f46 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobMetricsHandlerTestBase.java @@ -26,7 +26,7 @@ import java.util.Map; /** Tests for {@link JobMetricsHandler}. */ -public class JobMetricsHandlerTest extends MetricsHandlerTestBase { +class JobMetricsHandlerTestBase extends MetricsHandlerTestBase { private static final String TEST_JOB_ID = new JobID().toString(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexMetricsHandlerTestBase.java similarity index 95% rename from flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexMetricsHandlerTest.java rename to flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexMetricsHandlerTestBase.java index b48dbbac38f295..23db6d6183c453 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexMetricsHandlerTestBase.java @@ -26,7 +26,7 @@ import java.util.Map; /** Tests for {@link JobVertexMetricsHandler}. */ -public class JobVertexMetricsHandlerTest extends MetricsHandlerTestBase { +class JobVertexMetricsHandlerTestBase extends MetricsHandlerTestBase { private static final String TEST_JOB_ID = new JobID().toString(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexWatermarksHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexWatermarksHandlerTest.java index e295564bd035f5..2dfa99fc743a69 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexWatermarksHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/JobVertexWatermarksHandlerTest.java @@ -37,9 +37,9 @@ import org.hamcrest.BaseMatcher; import org.hamcrest.Description; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.annotation.Nullable; @@ -50,14 +50,13 @@ import java.util.Objects; import java.util.concurrent.Executor; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.HamcrestCondition.matching; +XXX.contains; +XXX.containsInAnyOrder; /** Tests for {@link JobVertexWatermarksHandler}. */ -public class JobVertexWatermarksHandlerTest { +class JobVertexWatermarksHandlerTest { private static final JobID TEST_JOB_ID = new JobID(); @@ -69,8 +68,8 @@ public class JobVertexWatermarksHandlerTest { private HandlerRequest request; private AccessExecutionJobVertex vertex; - @Before - public void before() throws Exception { + @BeforeEach + void before() throws Exception { taskMetricStore = Mockito.mock(MetricStore.TaskMetricStore.class); MetricStore metricStore = Mockito.mock(MetricStore.class); @@ -115,45 +114,45 @@ public void before() throws Exception { Mockito.when(vertex.getTaskVertices()).thenReturn(accessExecutionVertices); } - @After - public void after() { + @AfterEach + void after() { Mockito.verify(metricFetcher).update(); } @Test - public void testWatermarksRetrieval() throws Exception { + void testWatermarksRetrieval() throws Exception { Mockito.when(taskMetricStore.getMetric("0.currentInputWatermark")).thenReturn("23"); Mockito.when(taskMetricStore.getMetric("1.currentInputWatermark")).thenReturn("42"); MetricCollectionResponseBody response = watermarkHandler.handleRequest(request, vertex); - assertThat( - response.getMetrics(), - containsInAnyOrder( - new MetricMatcher("0.currentInputWatermark", "23"), - new MetricMatcher("1.currentInputWatermark", "42"))); + assertThat(response.getMetrics()) + .satisfies( + matching( + containsInAnyOrder( + new MetricMatcher("0.currentInputWatermark", "23"), + new MetricMatcher("1.currentInputWatermark", "42")))); } @Test - public void testPartialWatermarksAvailable() throws Exception { + void testPartialWatermarksAvailable() throws Exception { Mockito.when(taskMetricStore.getMetric("0.currentInputWatermark")).thenReturn("23"); Mockito.when(taskMetricStore.getMetric("1.currentInputWatermark")).thenReturn(null); MetricCollectionResponseBody response = watermarkHandler.handleRequest(request, vertex); - assertThat( - response.getMetrics(), - contains(new MetricMatcher("0.currentInputWatermark", "23"))); + assertThat(response.getMetrics()) + .satisfies(matching(contains(new MetricMatcher("0.currentInputWatermark", "23")))); } @Test - public void testNoWatermarksAvailable() throws Exception { + void testNoWatermarksAvailable() throws Exception { Mockito.when(taskMetricStore.getMetric("0.currentInputWatermark")).thenReturn(null); Mockito.when(taskMetricStore.getMetric("1.currentInputWatermark")).thenReturn(null); MetricCollectionResponseBody response = watermarkHandler.handleRequest(request, vertex); - assertThat(response.getMetrics(), is(empty())); + assertThat(response.getMetrics()).isEmpty(); } private static class MetricMatcher extends BaseMatcher { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/MetricsHandlerTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/MetricsHandlerTestBase.java index ed1d3959403850..db28eb65c6ab9d 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/MetricsHandlerTestBase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/MetricsHandlerTestBase.java @@ -30,22 +30,18 @@ import org.apache.flink.runtime.rest.messages.job.metrics.MetricCollectionResponseBody; import org.apache.flink.runtime.webmonitor.TestingDispatcherGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; -import org.apache.flink.util.TestLogger; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.Map; import java.util.concurrent.CompletableFuture; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** Unit test base class for subclasses of {@link AbstractMetricsHandler}. */ -public abstract class MetricsHandlerTestBase extends TestLogger { +abstract class MetricsHandlerTestBase { private static final String TEST_METRIC_NAME = "test_counter"; @@ -65,8 +61,8 @@ public abstract class MetricsHandlerTestBase e private Map pathParameters; - @Before - public void setUp() { + @BeforeEach + void setUp() { final MetricStore metricStore = new MetricStore(); metricStore.add( new MetricDump.CounterDump( @@ -97,7 +93,7 @@ public long getLastUpdateTime() { * AbstractMetricsHandler#getComponentMetricStore(HandlerRequest, MetricStore)}. */ @Test - public void testGetMetric() throws Exception { + void testGetMetric() throws Exception { @SuppressWarnings("unchecked") final CompletableFuture completableFuture = metricsHandler.handleRequest( @@ -109,13 +105,13 @@ public void testGetMetric() throws Exception { Collections.emptyList()), mockDispatcherGateway); - assertTrue(completableFuture.isDone()); + assertThat(completableFuture).isDone(); final MetricCollectionResponseBody metricCollectionResponseBody = completableFuture.get(); - assertThat(metricCollectionResponseBody.getMetrics(), hasSize(1)); + assertThat(metricCollectionResponseBody.getMetrics()).hasSize(1); final Metric metric = metricCollectionResponseBody.getMetrics().iterator().next(); - assertThat(metric.getId(), equalTo(getExpectedIdForMetricName(TEST_METRIC_NAME))); + assertThat(metric.getId()).isEqualTo(getExpectedIdForMetricName(TEST_METRIC_NAME)); } /** Returns instance under test. */ diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/SubtaskMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/SubtaskMetricsHandlerTestBase.java similarity index 96% rename from flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/SubtaskMetricsHandlerTest.java rename to flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/SubtaskMetricsHandlerTestBase.java index 30559e56aee49a..f9aed0d3faf63a 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/SubtaskMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/SubtaskMetricsHandlerTestBase.java @@ -29,7 +29,7 @@ import java.util.Map; /** Tests for {@link SubtaskMetricsHandler}. */ -public class SubtaskMetricsHandlerTest extends MetricsHandlerTestBase { +class SubtaskMetricsHandlerTestBase extends MetricsHandlerTestBase { private static final String TEST_JOB_ID = new JobID().toString(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/TaskManagerMetricsHandlerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/TaskManagerMetricsHandlerTestBase.java similarity index 94% rename from flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/TaskManagerMetricsHandlerTest.java rename to flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/TaskManagerMetricsHandlerTestBase.java index 07562b27b75b52..b036361312544b 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/TaskManagerMetricsHandlerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/metrics/TaskManagerMetricsHandlerTestBase.java @@ -26,8 +26,7 @@ import java.util.Map; /** Tests for {@link TaskManagerMetricsHandler}. */ -public class TaskManagerMetricsHandlerTest - extends MetricsHandlerTestBase { +class TaskManagerMetricsHandlerTestBase extends MetricsHandlerTestBase { private static final String TEST_TASK_MANAGER_ID = new InstanceID().toString(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointHandlersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointHandlersTest.java index 2f864bed909f18..0aa7917765715f 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointHandlersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointHandlersTest.java @@ -42,13 +42,12 @@ import org.apache.flink.runtime.webmonitor.RestfulGateway; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.FutureUtils; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.annotation.Nullable; @@ -60,15 +59,12 @@ import static org.apache.flink.runtime.rest.handler.job.savepoints.SavepointTestUtilities.getResultIfKeyMatches; import static org.apache.flink.runtime.rest.handler.job.savepoints.SavepointTestUtilities.setReferenceToOperationKey; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.HamcrestCondition.matching; /** Test for {@link SavepointHandlers}. */ -public class SavepointHandlersTest extends TestLogger { +class SavepointHandlersTest { private static final Time TIMEOUT = Time.seconds(10); @@ -85,8 +81,8 @@ public class SavepointHandlersTest extends TestLogger { private GatewayRetriever leaderRetriever; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { leaderRetriever = () -> CompletableFuture.completedFuture(null); final SavepointHandlers savepointHandlers = new SavepointHandlers(null); @@ -100,7 +96,7 @@ public void setUp() throws Exception { } @Test - public void testSavepointCompletedSuccessfully() throws Exception { + void testSavepointCompletedSuccessfully() throws Exception { final OperationResult successfulResult = OperationResult.success(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); final AtomicReference keyReference = new AtomicReference<>(); @@ -123,15 +119,14 @@ public void testSavepointCompletedSuccessfully() throws Exception { .handleRequest(savepointStatusRequest(triggerId), testingRestfulGateway) .get(); - assertThat(savepointResponseBody.queueStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); - assertThat(savepointResponseBody.resource(), notNullValue()); - assertThat( - savepointResponseBody.resource().getLocation(), - equalTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER)); + assertThat(savepointResponseBody.queueStatus().getId()).isEqualTo(QueueStatus.Id.COMPLETED); + assertThat(savepointResponseBody.resource()).isNotNull(); + assertThat(savepointResponseBody.resource().getLocation()) + .isEqualTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); } @Test - public void testTriggerSavepointWithDefaultDirectory() throws Exception { + void testTriggerSavepointWithDefaultDirectory() throws Exception { final CompletableFuture targetDirectoryFuture = new CompletableFuture<>(); final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() @@ -153,11 +148,11 @@ public void testTriggerSavepointWithDefaultDirectory() throws Exception { .handleRequest(triggerSavepointRequestWithDefaultDirectory(), testingRestfulGateway) .get(); - assertThat(targetDirectoryFuture.get(), equalTo(defaultSavepointDir)); + assertThat(targetDirectoryFuture.get()).isEqualTo(defaultSavepointDir); } @Test - public void testTriggerSavepointNoDirectory() throws Exception { + void testTriggerSavepointNoDirectory() throws Exception { TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() .setTriggerSavepointFunction( @@ -174,17 +169,16 @@ public void testTriggerSavepointNoDirectory() throws Exception { .get(); fail("Expected exception not thrown."); } catch (RestHandlerException rhe) { - assertThat( - rhe.getMessage(), - equalTo( + assertThat(rhe.getMessage()) + .isEqualTo( "Config key [state.savepoints.dir] is not set. " - + "Property [target-directory] must be provided.")); - assertThat(rhe.getHttpResponseStatus(), equalTo(HttpResponseStatus.BAD_REQUEST)); + + "Property [target-directory] must be provided."); + assertThat(rhe.getHttpResponseStatus()).isEqualTo(HttpResponseStatus.BAD_REQUEST); } } @Test - public void testSavepointCompletedWithException() throws Exception { + void testSavepointCompletedWithException() throws Exception { final OperationResult failedResult = OperationResult.failure(new RuntimeException("expected")); final AtomicReference keyReference = new AtomicReference<>(); @@ -206,20 +200,20 @@ public void testSavepointCompletedWithException() throws Exception { .handleRequest(savepointStatusRequest(triggerId), testingRestfulGateway) .get(); - assertThat(savepointResponseBody.queueStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); - assertThat(savepointResponseBody.resource(), notNullValue()); - assertThat(savepointResponseBody.resource().getFailureCause(), notNullValue()); + assertThat(savepointResponseBody.queueStatus().getId()).isEqualTo(QueueStatus.Id.COMPLETED); + assertThat(savepointResponseBody.resource()).isNotNull(); + assertThat(savepointResponseBody.resource().getFailureCause()).isNotNull(); final Throwable savepointError = savepointResponseBody .resource() .getFailureCause() .deserializeError(ClassLoader.getSystemClassLoader()); - assertThat(savepointError.getMessage(), equalTo("expected")); - assertThat(savepointError, instanceOf(RuntimeException.class)); + assertThat(savepointError.getMessage()).isEqualTo("expected"); + assertThat(savepointError).isInstanceOf(RuntimeException.class); } @Test - public void testProvidedTriggerId() throws Exception { + void testProvidedTriggerId() throws Exception { final OperationResult successfulResult = OperationResult.success(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); AtomicReference keyReference = new AtomicReference<>(); @@ -243,7 +237,7 @@ public void testProvidedTriggerId() throws Exception { .get() .getTriggerId(); - assertEquals(providedTriggerId, returnedTriggerId); + assertThat(returnedTriggerId).isEqualTo(providedTriggerId); AsynchronousOperationResult savepointResponseBody; savepointResponseBody = @@ -252,15 +246,14 @@ public void testProvidedTriggerId() throws Exception { savepointStatusRequest(providedTriggerId), testingRestfulGateway) .get(); - assertThat(savepointResponseBody.queueStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); - assertThat(savepointResponseBody.resource(), notNullValue()); - assertThat( - savepointResponseBody.resource().getLocation(), - equalTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER)); + assertThat(savepointResponseBody.queueStatus().getId()).isEqualTo(QueueStatus.Id.COMPLETED); + assertThat(savepointResponseBody.resource()).isNotNull(); + assertThat(savepointResponseBody.resource().getLocation()) + .isEqualTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); } @Test - public void testQueryStatusOfUnknownOperationReturnsError() + void testQueryStatusOfUnknownOperationReturnsError() throws HandlerRequestException, RestHandlerException { final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() @@ -274,7 +267,8 @@ public void testQueryStatusOfUnknownOperationReturnsError() savepointStatusHandler.handleRequest( savepointStatusRequest(new TriggerId()), testingRestfulGateway); - assertThat(statusFuture, RestMatchers.respondsWithError(HttpResponseStatus.NOT_FOUND)); + assertThat(statusFuture) + .satisfies(matching(RestMatchers.respondsWithError(HttpResponseStatus.NOT_FOUND))); } private static HandlerRequest triggerSavepointRequest() diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointTestUtilities.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointTestUtilities.java index c36ace2ebed455..694a6893984b8d 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointTestUtilities.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/SavepointTestUtilities.java @@ -29,7 +29,7 @@ import java.util.function.Function; /** Utility functions used in tests. */ -public final class SavepointTestUtilities { +final class SavepointTestUtilities { /** * Returns a function which, when called, sets the provided reference to the {@link diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/StopWithSavepointHandlersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/StopWithSavepointHandlersTest.java index fa0196fc5ebebb..d4649d68ed92ef 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/StopWithSavepointHandlersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/job/savepoints/StopWithSavepointHandlersTest.java @@ -40,12 +40,11 @@ import org.apache.flink.runtime.webmonitor.RestfulGateway; import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; -import org.apache.flink.util.TestLogger; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import javax.annotation.Nullable; @@ -57,12 +56,8 @@ import static org.apache.flink.runtime.rest.handler.job.savepoints.SavepointTestUtilities.getResultIfKeyMatches; import static org.apache.flink.runtime.rest.handler.job.savepoints.SavepointTestUtilities.setReferenceToOperationKey; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** * Test for the {@link @@ -70,7 +65,7 @@ * *

Shamelessly copied from {@link SavepointHandlersTest}. */ -public class StopWithSavepointHandlersTest extends TestLogger { +class StopWithSavepointHandlersTest { private static final Time TIMEOUT = Time.seconds(10); @@ -87,8 +82,8 @@ public class StopWithSavepointHandlersTest extends TestLogger { private GatewayRetriever leaderRetriever; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { leaderRetriever = () -> CompletableFuture.completedFuture(null); final SavepointHandlers savepointHandlers = new SavepointHandlers(null); @@ -102,7 +97,7 @@ public void setUp() throws Exception { } @Test - public void testSavepointCompletedSuccessfully() throws Exception { + void testSavepointCompletedSuccessfully() throws Exception { final OperationResult successfulResult = OperationResult.success(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); AtomicReference keyReference = new AtomicReference<>(); @@ -125,15 +120,14 @@ public void testSavepointCompletedSuccessfully() throws Exception { .handleRequest(savepointStatusRequest(triggerId), testingRestfulGateway) .get(); - assertThat(savepointResponseBody.queueStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); - assertThat(savepointResponseBody.resource(), notNullValue()); - assertThat( - savepointResponseBody.resource().getLocation(), - equalTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER)); + assertThat(savepointResponseBody.queueStatus().getId()).isEqualTo(QueueStatus.Id.COMPLETED); + assertThat(savepointResponseBody.resource()).isNotNull(); + assertThat(savepointResponseBody.resource().getLocation()) + .isEqualTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); } @Test - public void testTriggerSavepointWithDefaultDirectory() throws Exception { + void testTriggerSavepointWithDefaultDirectory() throws Exception { final CompletableFuture targetDirectoryFuture = new CompletableFuture<>(); final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() @@ -155,11 +149,11 @@ public void testTriggerSavepointWithDefaultDirectory() throws Exception { .handleRequest(triggerSavepointRequestWithDefaultDirectory(), testingRestfulGateway) .get(); - assertThat(targetDirectoryFuture.get(), equalTo(defaultSavepointDir)); + assertThat(targetDirectoryFuture.get()).isEqualTo(defaultSavepointDir); } @Test - public void testTriggerSavepointNoDirectory() throws Exception { + void testTriggerSavepointNoDirectory() throws Exception { TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder() .setStopWithSavepointFunction( @@ -176,17 +170,16 @@ public void testTriggerSavepointNoDirectory() throws Exception { .get(); fail("Expected exception not thrown."); } catch (RestHandlerException rhe) { - assertThat( - rhe.getMessage(), - equalTo( + assertThat(rhe.getMessage()) + .isEqualTo( "Config key [state.savepoints.dir] is not set. " - + "Property [targetDirectory] must be provided.")); - assertThat(rhe.getHttpResponseStatus(), equalTo(HttpResponseStatus.BAD_REQUEST)); + + "Property [targetDirectory] must be provided."); + assertThat(rhe.getHttpResponseStatus()).isEqualTo(HttpResponseStatus.BAD_REQUEST); } } @Test - public void testSavepointCompletedWithException() throws Exception { + void testSavepointCompletedWithException() throws Exception { AtomicReference keyReference = new AtomicReference<>(); final OperationResult failedResult = OperationResult.failure(new RuntimeException("expected")); @@ -208,20 +201,20 @@ public void testSavepointCompletedWithException() throws Exception { .handleRequest(savepointStatusRequest(triggerId), testingRestfulGateway) .get(); - assertThat(savepointResponseBody.queueStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); - assertThat(savepointResponseBody.resource(), notNullValue()); - assertThat(savepointResponseBody.resource().getFailureCause(), notNullValue()); + assertThat(savepointResponseBody.queueStatus().getId()).isEqualTo(QueueStatus.Id.COMPLETED); + assertThat(savepointResponseBody.resource()).isNotNull(); + assertThat(savepointResponseBody.resource().getFailureCause()).isNotNull(); final Throwable savepointError = savepointResponseBody .resource() .getFailureCause() .deserializeError(ClassLoader.getSystemClassLoader()); - assertThat(savepointError.getMessage(), equalTo("expected")); - assertThat(savepointError, instanceOf(RuntimeException.class)); + assertThat(savepointError.getMessage()).isEqualTo("expected"); + assertThat(savepointError).isInstanceOf(RuntimeException.class); } @Test - public void testProvidedTriggerId() throws Exception { + void testProvidedTriggerId() throws Exception { final OperationResult successfulResult = OperationResult.success(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); AtomicReference keyReference = new AtomicReference<>(); @@ -245,7 +238,7 @@ public void testProvidedTriggerId() throws Exception { .get() .getTriggerId(); - assertEquals(providedTriggerId, returnedTriggerId); + assertThat(returnedTriggerId).isEqualTo(providedTriggerId); AsynchronousOperationResult savepointResponseBody; savepointResponseBody = @@ -254,11 +247,10 @@ public void testProvidedTriggerId() throws Exception { savepointStatusRequest(providedTriggerId), testingRestfulGateway) .get(); - assertThat(savepointResponseBody.queueStatus().getId(), equalTo(QueueStatus.Id.COMPLETED)); - assertThat(savepointResponseBody.resource(), notNullValue()); - assertThat( - savepointResponseBody.resource().getLocation(), - equalTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER)); + assertThat(savepointResponseBody.queueStatus().getId()).isEqualTo(QueueStatus.Id.COMPLETED); + assertThat(savepointResponseBody.resource()).isNotNull(); + assertThat(savepointResponseBody.resource().getLocation()) + .isEqualTo(COMPLETED_SAVEPOINT_EXTERNAL_POINTER); } private static HandlerRequest triggerSavepointRequest() diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/DefaultExecutionGraphCacheTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/DefaultExecutionGraphCacheTest.java index 12415d7b23dbe4..bcbe5cac265b3e 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/DefaultExecutionGraphCacheTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/DefaultExecutionGraphCacheTest.java @@ -28,12 +28,10 @@ import org.apache.flink.util.ExecutorUtils; import org.apache.flink.util.FlinkException; import org.apache.flink.util.Preconditions; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.concurrent.FutureUtils; -import org.hamcrest.Matchers; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -46,18 +44,16 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** Tests for the {@link DefaultExecutionGraphCache}. */ -public class DefaultExecutionGraphCacheTest extends TestLogger { +class DefaultExecutionGraphCacheTest { private static ExecutionGraphInfo expectedExecutionGraphInfo; private static final JobID expectedJobId = new JobID(); - @BeforeClass + @BeforeAll public static void setup() { expectedExecutionGraphInfo = new ExecutionGraphInfo(new ArchivedExecutionGraphBuilder().build()); @@ -65,7 +61,7 @@ public static void setup() { /** Tests that we can cache AccessExecutionGraphs over multiple accesses. */ @Test - public void testExecutionGraphCaching() throws Exception { + void testExecutionGraphCaching() throws Exception { final Time timeout = Time.milliseconds(100L); final Time timeToLive = Time.hours(1L); @@ -79,20 +75,20 @@ public void testExecutionGraphCaching() throws Exception { CompletableFuture executionGraphInfoFuture = executionGraphCache.getExecutionGraphInfo(expectedJobId, restfulGateway); - assertEquals(expectedExecutionGraphInfo, executionGraphInfoFuture.get()); + assertThat(executionGraphInfoFuture.get()).isEqualTo(expectedExecutionGraphInfo); executionGraphInfoFuture = executionGraphCache.getExecutionGraphInfo(expectedJobId, restfulGateway); - assertEquals(expectedExecutionGraphInfo, executionGraphInfoFuture.get()); + assertThat(executionGraphInfoFuture.get()).isEqualTo(expectedExecutionGraphInfo); - assertThat(restfulGateway.getNumRequestJobCalls(), Matchers.equalTo(1)); + assertThat(restfulGateway.getNumRequestJobCalls()).isOne(); } } /** Tests that an AccessExecutionGraph is invalidated after its TTL expired. */ @Test - public void testExecutionGraphEntryInvalidation() throws Exception { + void testExecutionGraphEntryInvalidation() throws Exception { final Time timeout = Time.milliseconds(100L); final Time timeToLive = Time.milliseconds(1L); @@ -107,7 +103,7 @@ public void testExecutionGraphEntryInvalidation() throws Exception { CompletableFuture executionGraphInfoFuture = executionGraphCache.getExecutionGraphInfo(expectedJobId, restfulGateway); - assertEquals(expectedExecutionGraphInfo, executionGraphInfoFuture.get()); + assertThat(executionGraphInfoFuture.get()).isEqualTo(expectedExecutionGraphInfo); // sleep for the TTL Thread.sleep(timeToLive.toMilliseconds() * 5L); @@ -115,9 +111,9 @@ public void testExecutionGraphEntryInvalidation() throws Exception { CompletableFuture executionGraphInfoFuture2 = executionGraphCache.getExecutionGraphInfo(expectedJobId, restfulGateway); - assertEquals(expectedExecutionGraphInfo, executionGraphInfoFuture2.get()); + assertThat(executionGraphInfoFuture2.get()).isEqualTo(expectedExecutionGraphInfo); - assertThat(restfulGateway.getNumRequestJobCalls(), Matchers.equalTo(2)); + assertThat(restfulGateway.getNumRequestJobCalls()).isEqualTo(2); } } @@ -126,7 +122,7 @@ public void testExecutionGraphEntryInvalidation() throws Exception { * a cache entry --> another cache request will trigger a new gateway request. */ @Test - public void testImmediateCacheInvalidationAfterFailure() throws Exception { + void testImmediateCacheInvalidationAfterFailure() throws Exception { final Time timeout = Time.milliseconds(100L); final Time timeToLive = Time.hours(1L); @@ -148,13 +144,13 @@ public void testImmediateCacheInvalidationAfterFailure() throws Exception { fail("The execution graph future should have been completed exceptionally."); } catch (ExecutionException ee) { - assertTrue(ee.getCause() instanceof FlinkException); + assertThat(ee.getCause() instanceof FlinkException).isTrue(); } CompletableFuture executionGraphFuture2 = executionGraphCache.getExecutionGraphInfo(expectedJobId, restfulGateway); - assertEquals(expectedExecutionGraphInfo, executionGraphFuture2.get()); + assertThat(executionGraphFuture2.get()).isEqualTo(expectedExecutionGraphInfo); } } @@ -163,7 +159,7 @@ public void testImmediateCacheInvalidationAfterFailure() throws Exception { * DefaultExecutionGraphCache#cleanup()}. */ @Test - public void testCacheEntryCleanup() throws Exception { + void testCacheEntryCleanup() throws Exception { final Time timeout = Time.milliseconds(100L); final Time timeToLive = Time.milliseconds(1L); final JobID expectedJobId2 = new JobID(); @@ -197,23 +193,23 @@ public void testCacheEntryCleanup() throws Exception { CompletableFuture executionGraph2Future = executionGraphCache.getExecutionGraphInfo(expectedJobId2, restfulGateway); - assertEquals(expectedExecutionGraphInfo, executionGraph1Future.get()); + assertThat(executionGraph1Future.get()).isEqualTo(expectedExecutionGraphInfo); - assertEquals(expectedExecutionGraphInfo2, executionGraph2Future.get()); + assertThat(executionGraph2Future.get()).isEqualTo(expectedExecutionGraphInfo2); - assertThat(requestJobCalls.get(), Matchers.equalTo(2)); + assertThat(requestJobCalls.get()).isEqualTo(2); Thread.sleep(timeToLive.toMilliseconds()); executionGraphCache.cleanup(); - assertTrue(executionGraphCache.size() == 0); + assertThat(executionGraphCache.size()).isZero(); } } /** Tests that concurrent accesses only trigger a single AccessExecutionGraph request. */ @Test - public void testConcurrentAccess() throws Exception { + void testConcurrentAccess() throws Exception { final Time timeout = Time.milliseconds(100L); final Time timeToLive = Time.hours(1L); @@ -250,10 +246,10 @@ public void testConcurrentAccess() throws Exception { Collection allExecutionGraphs = allExecutionGraphFutures.get(); for (ExecutionGraphInfo executionGraph : allExecutionGraphs) { - assertEquals(expectedExecutionGraphInfo, executionGraph); + assertThat(executionGraph).isEqualTo(expectedExecutionGraphInfo); } - assertThat(restfulGateway.getNumRequestJobCalls(), Matchers.equalTo(1)); + assertThat(restfulGateway.getNumRequestJobCalls()).isOne(); } finally { ExecutorUtils.gracefulShutdown(5000L, TimeUnit.MILLISECONDS, executor); } @@ -286,7 +282,7 @@ private CountingRestfulGateway( @Override public CompletableFuture requestExecutionGraphInfo( JobID jobId, Time timeout) { - assertThat(jobId, Matchers.equalTo(expectedJobId)); + assertThat(jobId).isEqualTo(expectedJobId); numRequestJobCalls.incrementAndGet(); return super.requestExecutionGraphInfo(jobId, timeout); } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/checkpoints/CheckpointStatsCacheTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/checkpoints/CheckpointStatsCacheTest.java index 595804578c355f..53a066ae5099f1 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/checkpoints/CheckpointStatsCacheTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/checkpoints/CheckpointStatsCacheTest.java @@ -22,43 +22,42 @@ import org.apache.flink.runtime.checkpoint.CheckpointStatsStatus; import org.apache.flink.runtime.rest.handler.job.checkpoints.CheckpointStatsCache; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** Tests for the CheckpointStatsCache. */ -public class CheckpointStatsCacheTest { +class CheckpointStatsCacheTest { @Test - public void testZeroSizeCache() throws Exception { + void testZeroSizeCache() throws Exception { AbstractCheckpointStats checkpoint = createCheckpoint(0, CheckpointStatsStatus.COMPLETED); CheckpointStatsCache cache = new CheckpointStatsCache(0); cache.tryAdd(checkpoint); - assertNull(cache.tryGet(0L)); + assertThat(cache.tryGet(0L)).isNull(); } @Test - public void testCacheAddAndGet() throws Exception { + void testCacheAddAndGet() throws Exception { AbstractCheckpointStats chk0 = createCheckpoint(0, CheckpointStatsStatus.COMPLETED); AbstractCheckpointStats chk1 = createCheckpoint(1, CheckpointStatsStatus.COMPLETED); AbstractCheckpointStats chk2 = createCheckpoint(2, CheckpointStatsStatus.IN_PROGRESS); CheckpointStatsCache cache = new CheckpointStatsCache(1); cache.tryAdd(chk0); - assertEquals(chk0, cache.tryGet(0)); + assertThat(cache.tryGet(0)).isEqualTo(chk0); cache.tryAdd(chk1); - assertNull(cache.tryGet(0)); - assertEquals(chk1, cache.tryGet(1)); + assertThat(cache.tryGet(0)).isNull(); + assertThat(cache.tryGet(1)).isEqualTo(chk1); cache.tryAdd(chk2); - assertNull(cache.tryGet(2)); - assertNull(cache.tryGet(0)); - assertEquals(chk1, cache.tryGet(1)); + assertThat(cache.tryGet(2)).isNull(); + assertThat(cache.tryGet(0)).isNull(); + assertThat(cache.tryGet(1)).isEqualTo(chk1); } private AbstractCheckpointStats createCheckpoint(long id, CheckpointStatsStatus status) { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/files/MimeTypesTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/files/MimeTypesTest.java index c04d83fe984b6f..e6054f04449f91 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/files/MimeTypesTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/files/MimeTypesTest.java @@ -20,33 +20,32 @@ import org.apache.flink.runtime.rest.handler.util.MimeTypes; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** Tests for the MIME types map. */ public class MimeTypesTest { @Test - public void testCompleteness() { + void testCompleteness() { try { - assertNotNull(MimeTypes.getMimeTypeForExtension("txt")); - assertNotNull(MimeTypes.getMimeTypeForExtension("htm")); - assertNotNull(MimeTypes.getMimeTypeForExtension("html")); - assertNotNull(MimeTypes.getMimeTypeForExtension("css")); - assertNotNull(MimeTypes.getMimeTypeForExtension("js")); - assertNotNull(MimeTypes.getMimeTypeForExtension("json")); - assertNotNull(MimeTypes.getMimeTypeForExtension("png")); - assertNotNull(MimeTypes.getMimeTypeForExtension("jpg")); - assertNotNull(MimeTypes.getMimeTypeForExtension("jpeg")); - assertNotNull(MimeTypes.getMimeTypeForExtension("gif")); - assertNotNull(MimeTypes.getMimeTypeForExtension("woff")); - assertNotNull(MimeTypes.getMimeTypeForExtension("woff2")); - assertNotNull(MimeTypes.getMimeTypeForExtension("otf")); - assertNotNull(MimeTypes.getMimeTypeForExtension("ttf")); - assertNotNull(MimeTypes.getMimeTypeForExtension("eot")); + assertThat(MimeTypes.getMimeTypeForExtension("txt")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("htm")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("html")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("css")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("js")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("json")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("png")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("jpg")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("jpeg")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("gif")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("woff")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("woff2")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("otf")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("ttf")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForExtension("eot")).isNotNull(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); @@ -54,15 +53,15 @@ public void testCompleteness() { } @Test - public void testFileNameExtraction() { + void testFileNameExtraction() { try { - assertNotNull(MimeTypes.getMimeTypeForFileName("test.txt")); - assertNotNull(MimeTypes.getMimeTypeForFileName("t.txt")); - assertNotNull(MimeTypes.getMimeTypeForFileName("first.second.third.txt")); + assertThat(MimeTypes.getMimeTypeForFileName("test.txt")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForFileName("t.txt")).isNotNull(); + assertThat(MimeTypes.getMimeTypeForFileName("first.second.third.txt")).isNotNull(); - assertNull(MimeTypes.getMimeTypeForFileName(".txt")); - assertNull(MimeTypes.getMimeTypeForFileName("txt")); - assertNull(MimeTypes.getMimeTypeForFileName("test.")); + assertThat(MimeTypes.getMimeTypeForFileName(".txt")).isNull(); + assertThat(MimeTypes.getMimeTypeForFileName("txt")).isNull(); + assertThat(MimeTypes.getMimeTypeForFileName("test.")).isNull(); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/messages/ClusterOverviewWithVersionTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/messages/ClusterOverviewWithVersionTest.java index 71a2977ecbbb5a..b3a52b93912129 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/messages/ClusterOverviewWithVersionTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/messages/ClusterOverviewWithVersionTest.java @@ -18,11 +18,11 @@ package org.apache.flink.runtime.rest.handler.legacy.messages; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; /** Tests for the {@link ClusterOverviewWithVersion}. */ -public class ClusterOverviewWithVersionTest - extends RestResponseMarshallingTestBase { +class ClusterOverviewWithVersionTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/metrics/MetricFetcherTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/metrics/MetricFetcherTest.java index f1823f6da75c8d..4722f809d274ef 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/metrics/MetricFetcherTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/metrics/MetricFetcherTest.java @@ -37,12 +37,10 @@ import org.apache.flink.runtime.webmonitor.TestingRestfulGateway; import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever; import org.apache.flink.runtime.webmonitor.retriever.MetricQueryServiceGateway; -import org.apache.flink.util.TestLoggerExtension; import org.apache.flink.util.concurrent.Executors; import org.apache.flink.util.concurrent.FutureUtils; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import javax.annotation.Nullable; @@ -56,7 +54,6 @@ import static org.assertj.core.api.Assertions.assertThat; /** Tests for the MetricFetcher. */ -@ExtendWith(TestLoggerExtension.class) class MetricFetcherTest { @Test void testUpdate() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/router/RouterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/router/RouterTest.java index 199f5bc957e117..118dd8e755333a 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/router/RouterTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/router/RouterTest.java @@ -20,120 +20,118 @@ import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.Set; import static org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod.GET; import static org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod.POST; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link Router}. */ -public class RouterTest { +class RouterTest { private Router router; - @Before + @BeforeEach public void setUp() { router = StringRouter.create(); } @Test - public void testIgnoreSlashesAtBothEnds() { - assertEquals("index", router.route(GET, "articles").target()); - assertEquals("index", router.route(GET, "/articles").target()); - assertEquals("index", router.route(GET, "//articles").target()); - assertEquals("index", router.route(GET, "articles/").target()); - assertEquals("index", router.route(GET, "articles//").target()); - assertEquals("index", router.route(GET, "/articles/").target()); - assertEquals("index", router.route(GET, "//articles//").target()); + void testIgnoreSlashesAtBothEnds() { + assertThat("index").isEqualTo(router.route(GET, "articles").target()); + assertThat("index").isEqualTo(router.route(GET, "/articles").target()); + assertThat("index").isEqualTo(router.route(GET, "//articles").target()); + assertThat("index").isEqualTo(router.route(GET, "articles/").target()); + assertThat("index").isEqualTo(router.route(GET, "articles//").target()); + assertThat("index").isEqualTo(router.route(GET, "/articles/").target()); + assertThat("index").isEqualTo(router.route(GET, "//articles//").target()); } @Test - public void testEmptyParams() { + void testEmptyParams() { RouteResult routed = router.route(GET, "/articles"); - assertEquals("index", routed.target()); - assertEquals(0, routed.pathParams().size()); + assertThat(routed.target()).isEqualTo("index"); + assertThat(routed.pathParams()).isEmpty(); } @Test - public void testParams() { + void testParams() { RouteResult routed = router.route(GET, "/articles/123"); - assertEquals("show", routed.target()); - assertEquals(1, routed.pathParams().size()); - assertEquals("123", routed.pathParams().get("id")); + assertThat(routed.target()).isEqualTo("show"); + assertThat(routed.pathParams()).hasSize(1); + assertThat(routed.pathParams().get("id")).isEqualTo("123"); } @Test - public void testNone() { + void testNone() { RouteResult routed = router.route(GET, "/noexist"); - assertEquals("404", routed.target()); + assertThat(routed.target()).isEqualTo("404"); } @Test - public void testSplatWildcard() { + void testSplatWildcard() { RouteResult routed = router.route(GET, "/download/foo/bar.png"); - assertEquals("download", routed.target()); - assertEquals(1, routed.pathParams().size()); - assertEquals("foo/bar.png", routed.pathParams().get("*")); + assertThat(routed.target()).isEqualTo("download"); + assertThat(routed.pathParams()).hasSize(1); + assertThat(routed.pathParams().get("*")).isEqualTo("foo/bar.png"); } @Test - public void testOrder() { + void testOrder() { RouteResult routed1 = router.route(GET, "/articles/new"); - assertEquals("new", routed1.target()); - assertEquals(0, routed1.pathParams().size()); + assertThat(routed1.target()).isEqualTo("new"); + assertThat(routed1.pathParams()).isEmpty(); RouteResult routed2 = router.route(GET, "/articles/123"); - assertEquals("show", routed2.target()); - assertEquals(1, routed2.pathParams().size()); - assertEquals("123", routed2.pathParams().get("id")); + assertThat(routed2.target()).isEqualTo("show"); + assertThat(routed2.pathParams()).hasSize(1); + assertThat(routed2.pathParams().get("id")).isEqualTo("123"); RouteResult routed3 = router.route(GET, "/notfound"); - assertEquals("404", routed3.target()); - assertEquals(0, routed3.pathParams().size()); + assertThat(routed3.target()).isEqualTo("404"); + assertThat(routed3.pathParams()).isEmpty(); RouteResult routed4 = router.route(GET, "/articles/overview"); - assertEquals("overview", routed4.target()); - assertEquals(0, routed4.pathParams().size()); + assertThat(routed4.target()).isEqualTo("overview"); + assertThat(routed4.pathParams()).isEmpty(); RouteResult routed5 = router.route(GET, "/articles/overview/detailed"); - assertEquals("detailed", routed5.target()); - assertEquals(0, routed5.pathParams().size()); + assertThat(routed5.target()).isEqualTo("detailed"); + assertThat(routed5.pathParams()).isEmpty(); } @Test - public void testAnyMethod() { + void testAnyMethod() { RouteResult routed1 = router.route(GET, "/anyMethod"); - assertEquals("anyMethod", routed1.target()); - assertEquals(0, routed1.pathParams().size()); + assertThat(routed1.target()).isEqualTo("anyMethod"); + assertThat(routed1.pathParams()).isEmpty(); RouteResult routed2 = router.route(POST, "/anyMethod"); - assertEquals("anyMethod", routed2.target()); - assertEquals(0, routed2.pathParams().size()); + assertThat(routed2.target()).isEqualTo("anyMethod"); + assertThat(routed2.pathParams()).isEmpty(); } @Test - public void testRemoveByPathPattern() { + void testRemoveByPathPattern() { router.removePathPattern("/articles"); RouteResult routed = router.route(GET, "/articles"); - assertEquals("404", routed.target()); + assertThat(routed.target()).isEqualTo("404"); } @Test - public void testAllowedMethods() { - assertEquals(9, router.allAllowedMethods().size()); + void testAllowedMethods() { + assertThat(router.allAllowedMethods()).hasSize(9); Set methods = router.allowedMethods("/articles"); - assertEquals(2, methods.size()); - assertTrue(methods.contains(GET)); - assertTrue(methods.contains(POST)); + assertThat(methods).hasSize(2); + assertThat(methods.contains(GET)).isTrue(); + assertThat(methods.contains(POST)).isTrue(); } @Test - public void testSubclasses() { + void testSubclasses() { Router> router = new Router>() .addRoute(GET, "/articles", Index.class) @@ -141,10 +139,10 @@ public void testSubclasses() { RouteResult> routed1 = router.route(GET, "/articles"); RouteResult> routed2 = router.route(GET, "/articles/123"); - assertNotNull(routed1); - assertNotNull(routed2); - assertEquals(Index.class, routed1.target()); - assertEquals(Show.class, routed2.target()); + assertThat(routed1).isNotNull(); + assertThat(routed2).isNotNull(); + assertThat(routed1.target()).isEqualTo(Index.class); + assertThat(routed2.target()).isEqualTo(Show.class); } private static final class StringRouter { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/util/HandlerRequestUtilsTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/util/HandlerRequestUtilsTest.java index 88c0b3908355e4..52970f9c7fbae9 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/util/HandlerRequestUtilsTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/util/HandlerRequestUtilsTest.java @@ -24,23 +24,20 @@ import org.apache.flink.runtime.rest.messages.MessageParameters; import org.apache.flink.runtime.rest.messages.MessagePathParameter; import org.apache.flink.runtime.rest.messages.MessageQueryParameter; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link HandlerRequestUtils}. */ -public class HandlerRequestUtilsTest extends TestLogger { +class HandlerRequestUtilsTest { @Test - public void testGetQueryParameter() throws Exception { + void testGetQueryParameter() throws Exception { final Boolean queryParameter = HandlerRequestUtils.getQueryParameter( HandlerRequest.resolveParametersAndCreate( @@ -50,11 +47,11 @@ public void testGetQueryParameter() throws Exception { Collections.singletonMap("key", Collections.singletonList("true")), Collections.emptyList()), TestBooleanQueryParameter.class); - assertThat(queryParameter, equalTo(true)); + assertThat(queryParameter).isTrue(); } @Test - public void testGetQueryParameterRepeated() throws Exception { + void testGetQueryParameterRepeated() throws Exception { try { HandlerRequestUtils.getQueryParameter( HandlerRequest.resolveParametersAndCreate( @@ -65,12 +62,12 @@ public void testGetQueryParameterRepeated() throws Exception { Collections.emptyList()), TestBooleanQueryParameter.class); } catch (final RestHandlerException e) { - assertThat(e.getMessage(), containsString("Expected only one value")); + assertThat(e.getMessage()).contains("Expected only one value"); } } @Test - public void testGetQueryParameterDefaultValue() throws Exception { + void testGetQueryParameterDefaultValue() throws Exception { final Boolean allowNonRestoredState = HandlerRequestUtils.getQueryParameter( HandlerRequest.resolveParametersAndCreate( @@ -81,7 +78,7 @@ public void testGetQueryParameterDefaultValue() throws Exception { Collections.emptyList()), TestBooleanQueryParameter.class, true); - assertThat(allowNonRestoredState, equalTo(true)); + assertThat(allowNonRestoredState).isTrue(); } private static class TestMessageParameters extends MessageParameters { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/AggregatedTaskDetailsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/AggregatedTaskDetailsInfoTest.java index df3e3fef22028d..74b81b9d614a2f 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/AggregatedTaskDetailsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/AggregatedTaskDetailsInfoTest.java @@ -29,11 +29,11 @@ import java.util.Map; import java.util.Random; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for the {@link AggregatedTaskDetailsInfo}. */ -public class AggregatedTaskDetailsInfoTest - extends RestResponseMarshallingTestBase { +class AggregatedTaskDetailsInfoTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return AggregatedTaskDetailsInfo.class; @@ -82,19 +82,19 @@ protected AggregatedTaskDetailsInfo getTestResponseInstance() throws Exception { } @Test - public void testMetricsStatistics() { + void testMetricsStatistics() { final AggregatedTaskDetailsInfo.MetricsStatistics metricsStatistics = new AggregatedTaskDetailsInfo.MetricsStatistics("test"); for (int i = 0; i < 100; ++i) { metricsStatistics.addValue(i); } - assertEquals(0L, metricsStatistics.getMin()); - assertEquals(99L, metricsStatistics.getMax()); - assertEquals(49L, metricsStatistics.getPercentile(50)); - assertEquals(24L, metricsStatistics.getPercentile(25)); - assertEquals(74L, metricsStatistics.getPercentile(75)); - assertEquals(94L, metricsStatistics.getPercentile(95)); - assertEquals(4950L, metricsStatistics.getSum()); - assertEquals(49L, metricsStatistics.getAvg()); + assertThat(metricsStatistics.getMin()).isZero(); + assertThat(metricsStatistics.getMax()).isEqualTo(99L); + assertThat(metricsStatistics.getPercentile(50)).isEqualTo(49L); + assertThat(metricsStatistics.getPercentile(25)).isEqualTo(24L); + assertThat(metricsStatistics.getPercentile(75)).isEqualTo(74L); + assertThat(metricsStatistics.getPercentile(95)).isEqualTo(94L); + assertThat(metricsStatistics.getSum()).isEqualTo(4950L); + assertThat(metricsStatistics.getAvg()).isEqualTo(49L); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ConfigurationInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ConfigurationInfoTest.java index f10de95a61b093..ec3ff8bba9708d 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ConfigurationInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ConfigurationInfoTest.java @@ -19,7 +19,7 @@ package org.apache.flink.runtime.rest.messages; /** Tests for the {@link ConfigurationInfo}. */ -public class ConfigurationInfoTest extends RestResponseMarshallingTestBase { +class ConfigurationInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/DashboardConfigurationTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/DashboardConfigurationTest.java index eeedeb5b74917d..b9ce2917b3dfdb 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/DashboardConfigurationTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/DashboardConfigurationTest.java @@ -19,8 +19,7 @@ package org.apache.flink.runtime.rest.messages; /** Tests for the {@link DashboardConfiguration}. */ -public class DashboardConfigurationTest - extends RestResponseMarshallingTestBase { +class DashboardConfigurationTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/EnvironmentInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/EnvironmentInfoTest.java index 6b8696c06ac7c8..de0b8d4f0ec719 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/EnvironmentInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/EnvironmentInfoTest.java @@ -19,7 +19,7 @@ package org.apache.flink.runtime.rest.messages; /** Tests for the {@link EnvironmentInfo}. */ -public class EnvironmentInfoTest extends RestResponseMarshallingTestBase { +class EnvironmentInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return EnvironmentInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobAccumulatorsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobAccumulatorsInfoTest.java index 7828dee79404f3..33aa6b09a85477 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobAccumulatorsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobAccumulatorsInfoTest.java @@ -23,7 +23,7 @@ import java.util.List; /** Tests that the {@link JobAccumulatorsInfo} can be marshalled and unmarshalled. */ -public class JobAccumulatorsInfoTest extends RestResponseMarshallingTestBase { +class JobAccumulatorsInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobAccumulatorsInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobConfigInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobConfigInfoTest.java index 773b37087a00cf..abee2d110e1f0a 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobConfigInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobConfigInfoTest.java @@ -24,7 +24,7 @@ import java.util.Map; /** Tests that the {@link JobConfigInfo} can be marshalled and unmarshalled. */ -public class JobConfigInfoTest extends RestResponseMarshallingTestBase { +class JobConfigInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryNoRootTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryNoRootTest.java index e68ab8ce8a88c2..3d0746b680d59e 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryNoRootTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryNoRootTest.java @@ -27,8 +27,8 @@ * Tests that the {@link JobExceptionsInfoWithHistory} with no root exception can be marshalled and * unmarshalled. */ -public class JobExceptionsInfoWithHistoryNoRootTest - extends RestResponseMarshallingTestBase { +class JobExceptionsInfoWithHistoryNoRootTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobExceptionsInfoWithHistory.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryTest.java index b985ce6bb9f253..b04e30dca2ad32 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryTest.java @@ -23,19 +23,17 @@ import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; -import org.hamcrest.CoreMatchers; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests that the {@link JobExceptionsInfoWithHistory} can be marshalled and unmarshalled. */ -public class JobExceptionsInfoWithHistoryTest - extends RestResponseMarshallingTestBase { +class JobExceptionsInfoWithHistoryTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobExceptionsInfoWithHistory.class; @@ -74,14 +72,14 @@ protected JobExceptionsInfoWithHistory getTestResponseInstance() throws Exceptio * @throws JsonProcessingException is not expected to be thrown */ @Test - public void testNullFieldsNotSet() throws JsonProcessingException { + void testNullFieldsNotSet() throws JsonProcessingException { ObjectMapper objMapper = RestMapperUtils.getStrictObjectMapper(); String json = objMapper.writeValueAsString( new JobExceptionsInfoWithHistory.ExceptionInfo( "exception name", "stacktrace", 0L)); - assertThat(json, not(CoreMatchers.containsString("taskName"))); - assertThat(json, not(CoreMatchers.containsString("location"))); + assertThat(json).doesNotContain("taskName"); + assertThat(json).doesNotContain("location"); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobPlanInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobPlanInfoTest.java index b5e955768fa585..f62725c7688dbd 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobPlanInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobPlanInfoTest.java @@ -23,7 +23,7 @@ import org.apache.flink.runtime.jobgraph.jsonplan.JsonPlanGenerator; /** Tests that the {@link JobPlanInfo} can be marshalled and unmarshalled. */ -public class JobPlanInfoTest extends RestResponseMarshallingTestBase { +class JobPlanInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitRequestBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitRequestBodyTest.java index 778066e9030e19..5d288e25c6bbc8 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitRequestBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitRequestBodyTest.java @@ -24,7 +24,8 @@ import java.util.Arrays; /** Tests for the {@link JobSubmitRequestBody}. */ -public class JobSubmitRequestBodyTest extends RestRequestMarshallingTestBase { +public class JobSubmitRequestBodyTest + extends RestRequestUnmarshallingTestBase { @Override protected Class getTestRequestClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitResponseBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitResponseBodyTest.java index 331ed39533bfa3..73917e521fc6ab 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitResponseBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobSubmitResponseBodyTest.java @@ -21,8 +21,7 @@ import org.apache.flink.runtime.rest.messages.job.JobSubmitResponseBody; /** Tests for {@link JobSubmitResponseBody}. */ -public class JobSubmitResponseBodyTest - extends RestResponseMarshallingTestBase { +class JobSubmitResponseBodyTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexAccumulatorsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexAccumulatorsInfoTest.java index c8bbe49d54d67a..bde1c904d3b27b 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexAccumulatorsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexAccumulatorsInfoTest.java @@ -24,8 +24,8 @@ import java.util.List; /** Tests that the {@link JobVertexAccumulatorsInfo} can be marshalled and unmarshalled. */ -public class JobVertexAccumulatorsInfoTest - extends RestResponseMarshallingTestBase { +class JobVertexAccumulatorsInfoTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobVertexAccumulatorsInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexBackPressureInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexBackPressureInfoTest.java index 566f668837ae5a..02f6aa805e7418 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexBackPressureInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexBackPressureInfoTest.java @@ -22,8 +22,8 @@ import java.util.List; /** Tests that the {@link JobVertexBackPressureInfo} can be marshalled and unmarshalled. */ -public class JobVertexBackPressureInfoTest - extends RestResponseMarshallingTestBase { +class JobVertexBackPressureInfoTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobVertexBackPressureInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexDetailsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexDetailsInfoTest.java index 00b12f7c68d193..d47363fa80e0f2 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexDetailsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexDetailsInfoTest.java @@ -31,8 +31,7 @@ import java.util.Random; /** Tests that the {@link JobVertexDetailsInfo} can be marshalled and unmarshalled. */ -public class JobVertexDetailsInfoTest - extends RestResponseMarshallingTestBase { +class JobVertexDetailsInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobVertexDetailsInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexTaskManagersInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexTaskManagersInfoTest.java index a5e2213d0a2d6c..cb8d5b84bb50e7 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexTaskManagersInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobVertexTaskManagersInfoTest.java @@ -32,8 +32,8 @@ import static org.apache.flink.runtime.rest.messages.JobVertexTaskManagersInfo.TaskManagersInfo; /** Tests that the {@link JobVertexTaskManagersInfo} can be marshalled and unmarshalled. */ -public class JobVertexTaskManagersInfoTest - extends RestResponseMarshallingTestBase { +class JobVertexTaskManagersInfoTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return JobVertexTaskManagersInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/LogUrlResponseTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/LogUrlResponseTest.java index e658bd9fe7b6c3..d141cd479f2d15 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/LogUrlResponseTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/LogUrlResponseTest.java @@ -19,7 +19,7 @@ package org.apache.flink.runtime.rest.messages; /** Tests that the {@link LogUrlResponse} can be marshalled and unmarshalled. */ -public class LogUrlResponseTest extends RestResponseMarshallingTestBase { +class LogUrlResponseTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return LogUrlResponse.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/MessageParametersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/MessageParametersTest.java index 2ff31a5175b8d8..9c7523f9fb88c7 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/MessageParametersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/MessageParametersTest.java @@ -19,18 +19,19 @@ package org.apache.flink.runtime.rest.messages; import org.apache.flink.api.common.JobID; -import org.apache.flink.util.TestLogger; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Collections; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + /** Tests for {@link MessageParameters}. */ -public class MessageParametersTest extends TestLogger { +class MessageParametersTest { @Test - public void testResolveUrl() { + void testResolveUrl() { String genericUrl = "/jobs/:jobid/state"; TestMessageParameters parameters = new TestMessageParameters(); JobID pathJobID = new JobID(); @@ -40,24 +41,21 @@ public void testResolveUrl() { String resolvedUrl = MessageParameters.resolveUrl(genericUrl, parameters); - Assert.assertEquals("/jobs/" + pathJobID + "/state?jobid=" + queryJobID, resolvedUrl); + assertThat("/jobs/" + pathJobID + "/state?jobid=" + queryJobID).isEqualTo(resolvedUrl); } @Test - public void testUnresolvedParameters() { + void testUnresolvedParameters() { String genericUrl = "/jobs/:jobid/state"; TestMessageParameters parameters = new TestMessageParameters(); - try { - MessageParameters.resolveUrl(genericUrl, parameters); - Assert.fail(); - } catch (IllegalStateException expected) { - // the mandatory jobid path parameter was not resolved - } + assertThatThrownBy(() -> MessageParameters.resolveUrl(genericUrl, parameters)) + .isInstanceOf(IllegalStateException.class); + JobID jobID = new JobID(); parameters.pathParameter.resolve(jobID); String resolvedUrl = MessageParameters.resolveUrl(genericUrl, parameters); - Assert.assertEquals("/jobs/" + jobID + "/state", resolvedUrl); + assertThat(resolvedUrl).isEqualTo("/jobs/" + jobID + "/state"); } private static class TestMessageParameters extends MessageParameters { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ResourceProfileInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ResourceProfileInfoTest.java index 144cce1e3359b3..94ceeb91c73774 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ResourceProfileInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ResourceProfileInfoTest.java @@ -23,7 +23,7 @@ import java.util.Random; /** Test for (un)marshalling of the {@link ResourceProfileInfo}. */ -public class ResourceProfileInfoTest extends RestResponseMarshallingTestBase { +class ResourceProfileInfoTest extends RestResponseUnmarshallingTestBase { private static final Random random = new Random(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestMarshallingTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestMarshallingTestBase.java index e2d9a24e27ac76..65cc6e5925f024 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestMarshallingTestBase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestMarshallingTestBase.java @@ -19,35 +19,20 @@ package org.apache.flink.runtime.rest.messages; import org.apache.flink.runtime.rest.util.RestMapperUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.TestTemplate; /** * Test base for verifying that marshalling / unmarshalling REST {@link RequestBody}s work properly. */ -public abstract class RestRequestMarshallingTestBase extends TestLogger { +public abstract class RestRequestMarshallingTestBase + extends RestRequestTestBase { - /** - * Returns the class of the test response. - * - * @return class of the test response type - */ - protected abstract Class getTestRequestClass(); - - /** - * Returns an instance of a response to be tested. - * - * @return instance of the expected test response - */ - protected abstract R getTestRequestInstance() throws Exception; - - /** Tests that we can marshal and unmarshal the response. */ - @Test - public void testJsonMarshalling() throws Exception { + /** Tests that we can marshal the response. */ + @TestTemplate + void testJsonMarshalling() throws Exception { final R expected = getTestRequestInstance(); ObjectMapper objectMapper = RestMapperUtils.getStrictObjectMapper(); @@ -56,14 +41,4 @@ public void testJsonMarshalling() throws Exception { final R unmarshalled = objectMapper.readValue(marshalled, getTestRequestClass()); assertOriginalEqualsToUnmarshalled(expected, unmarshalled); } - - /** - * Asserts that two objects are equal. If they are not, an {@link AssertionError} is thrown. - * - * @param expected expected value - * @param actual the value to check against expected - */ - protected void assertOriginalEqualsToUnmarshalled(R expected, R actual) { - Assert.assertEquals(expected, actual); - } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestTestBase.java new file mode 100644 index 00000000000000..e51923bc9fb501 --- /dev/null +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestTestBase.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.runtime.rest.messages; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test base for verifying that marshalling / unmarshalling REST {@link RequestBody}s work properly. + */ +public abstract class RestRequestTestBase { + + /** + * Returns the class of the test response. + * + * @return class of the test response type + */ + protected abstract Class getTestRequestClass(); + + /** + * Returns an instance of a response to be tested. + * + * @return instance of the expected test response + */ + protected abstract R getTestRequestInstance() throws Exception; + + /** + * Asserts that two objects are equal. If they are not, an {@link AssertionError} is thrown. + * + * @param expected expected value + * @param actual the value to check against expected + */ + protected void assertOriginalEqualsToUnmarshalled(R expected, R actual) { + assertThat(actual).isEqualTo(expected); + } +} diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestUnmarshallingTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestUnmarshallingTestBase.java new file mode 100644 index 00000000000000..4286009710f453 --- /dev/null +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestRequestUnmarshallingTestBase.java @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.runtime.rest.messages; + +import org.apache.flink.runtime.rest.util.RestMapperUtils; + +import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.jupiter.api.Test; + +/** Test base for verifying that unmarshalling REST {@link RequestBody}s work properly. */ +public abstract class RestRequestUnmarshallingTestBase + extends RestRequestTestBase { + + /** Tests that we can unmarshal the response. */ + @Test + void testJsonUnMarshalling() throws Exception { + final R expected = getTestRequestInstance(); + + ObjectMapper objectMapper = RestMapperUtils.getStrictObjectMapper(); + final String marshalled = objectMapper.writeValueAsString(expected); + + final R unmarshalled = objectMapper.readValue(marshalled, getTestRequestClass()); + assertOriginalEqualsToUnmarshalled(expected, unmarshalled); + } +} diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseMarshallingTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseMarshallingTestBase.java index 3648df0f2ea5f9..927cf4711cf510 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseMarshallingTestBase.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseMarshallingTestBase.java @@ -19,44 +19,21 @@ package org.apache.flink.runtime.rest.messages; import org.apache.flink.runtime.rest.util.RestMapperUtils; -import org.apache.flink.util.TestLogger; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.TestTemplate; import java.util.Collection; -import java.util.Collections; -/** - * Test base for verifying that marshalling / unmarshalling REST {@link ResponseBody}s work - * properly. - */ -public abstract class RestResponseMarshallingTestBase extends TestLogger { - - /** - * Returns the class of the test response. - * - * @return class of the test response type - */ - protected abstract Class getTestResponseClass(); - - protected Collection> getTypeParameters() { - return Collections.emptyList(); - } - - /** - * Returns an instance of a response to be tested. - * - * @return instance of the expected test response - */ - protected abstract R getTestResponseInstance() throws Exception; +/** Test base for verifying that marshalling REST {@link ResponseBody}s work properly. */ +public abstract class RestResponseMarshallingTestBase + extends RestResponseTestBase { /** Tests that we can marshal and unmarshal the response. */ - @Test - public void testJsonMarshalling() throws Exception { + @TestTemplate + void testJsonMarshalling() throws Exception { final R expected = getTestResponseInstance(); ObjectMapper objectMapper = RestMapperUtils.getStrictObjectMapper(); @@ -79,14 +56,4 @@ public void testJsonMarshalling() throws Exception { final R unmarshalled = objectMapper.readValue(marshalled, type); assertOriginalEqualsToUnmarshalled(expected, unmarshalled); } - - /** - * Asserts that two objects are equal. If they are not, an {@link AssertionError} is thrown. - * - * @param expected expected value - * @param actual the value to check against expected - */ - protected void assertOriginalEqualsToUnmarshalled(R expected, R actual) { - Assert.assertEquals(expected, actual); - } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseTestBase.java new file mode 100644 index 00000000000000..51f2bc6ecf4381 --- /dev/null +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseTestBase.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.runtime.rest.messages; + +import java.util.Collection; +import java.util.Collections; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test base for verifying that marshalling / unmarshalling REST {@link ResponseBody}s work + * properly. + */ +public abstract class RestResponseTestBase { + + /** + * Returns the class of the test response. + * + * @return class of the test response type + */ + protected abstract Class getTestResponseClass(); + + protected Collection> getTypeParameters() { + return Collections.emptyList(); + } + + /** + * Returns an instance of a response to be tested. + * + * @return instance of the expected test response + */ + protected abstract R getTestResponseInstance() throws Exception; + + /** + * Asserts that two objects are equal. If they are not, an {@link AssertionError} is thrown. + * + * @param expected expected value + * @param actual the value to check against expected + */ + protected void assertOriginalEqualsToUnmarshalled(R expected, R actual) { + assertThat(actual).isEqualTo(expected); + } +} diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseUnmarshallingTestBase.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseUnmarshallingTestBase.java new file mode 100644 index 00000000000000..196d3edae1ed74 --- /dev/null +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/RestResponseUnmarshallingTestBase.java @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.runtime.rest.messages; + +import org.apache.flink.runtime.rest.util.RestMapperUtils; + +import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType; +import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; + +import org.junit.jupiter.api.Test; + +import java.util.Collection; + +/** Test base for verifying that unmarshalling REST {@link ResponseBody}s work properly. */ +public abstract class RestResponseUnmarshallingTestBase + extends RestResponseTestBase { + + /** Tests that we can unmarshal the response. */ + @Test + void testJsonMarshalling() throws Exception { + final R expected = getTestResponseInstance(); + + ObjectMapper objectMapper = RestMapperUtils.getStrictObjectMapper(); + final String marshalled = objectMapper.writeValueAsString(expected); + + final Collection> typeParameters = getTypeParameters(); + final JavaType type; + + if (typeParameters.isEmpty()) { + type = objectMapper.getTypeFactory().constructType(getTestResponseClass()); + } else { + type = + objectMapper + .getTypeFactory() + .constructParametricType( + getTestResponseClass(), + typeParameters.toArray(new Class[typeParameters.size()])); + } + + final R unmarshalled = objectMapper.readValue(marshalled, type); + assertOriginalEqualsToUnmarshalled(expected, unmarshalled); + } +} diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SavepointHandlerRequestBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SavepointHandlerRequestBodyTest.java index 40b6eefa78c607..0f0bb146dad13e 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SavepointHandlerRequestBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SavepointHandlerRequestBodyTest.java @@ -24,33 +24,31 @@ import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for the savepoint request bodies. */ public class SavepointHandlerRequestBodyTest { @Test - public void testSavepointRequestCanBeParsedFromEmptyObject() throws JsonProcessingException { + void testSavepointRequestCanBeParsedFromEmptyObject() throws JsonProcessingException { final SavepointTriggerRequestBody defaultParseResult = getDefaultParseResult(SavepointTriggerRequestBody.class); - assertThat(defaultParseResult.isCancelJob(), is(false)); + assertThat(defaultParseResult.isCancelJob()).isFalse(); - assertThat(defaultParseResult.getTargetDirectory().isPresent(), is(false)); + assertThat(defaultParseResult.getTargetDirectory()).isNotPresent(); } @Test - public void testStopWithSavepointRequestCanBeParsedFromEmptyObject() - throws JsonProcessingException { + void testStopWithSavepointRequestCanBeParsedFromEmptyObject() throws JsonProcessingException { final StopWithSavepointRequestBody defaultParseResult = getDefaultParseResult(StopWithSavepointRequestBody.class); - assertThat(defaultParseResult.shouldDrain(), is(false)); + assertThat(defaultParseResult.shouldDrain()).isFalse(); - assertThat(defaultParseResult.getTargetDirectory().isPresent(), is(false)); + assertThat(defaultParseResult.getTargetDirectory()).isNotPresent(); } private static T getDefaultParseResult(Class clazz) throws JsonProcessingException { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtaskIndexPathParameterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtaskIndexPathParameterTest.java index cafef64e86311c..94700e1f489230 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtaskIndexPathParameterTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtaskIndexPathParameterTest.java @@ -18,52 +18,47 @@ package org.apache.flink.runtime.rest.messages; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; /** Tests for {@link SubtaskIndexPathParameter}. */ -public class SubtaskIndexPathParameterTest { +class SubtaskIndexPathParameterTest { private SubtaskIndexPathParameter subtaskIndexPathParameter; - @Before - public void setUp() { + @BeforeEach + void setUp() { subtaskIndexPathParameter = new SubtaskIndexPathParameter(); } @Test - public void testConversionFromString() throws Exception { - assertThat( - subtaskIndexPathParameter.convertFromString("2147483647"), - equalTo(Integer.MAX_VALUE)); + void testConversionFromString() throws Exception { + assertThat(subtaskIndexPathParameter.convertFromString("2147483647")) + .isEqualTo(Integer.MAX_VALUE); } @Test - public void testConversionFromStringNegativeNumber() throws Exception { + void testConversionFromStringNegativeNumber() throws Exception { try { subtaskIndexPathParameter.convertFromString("-2147483648"); fail("Expected exception not thrown"); } catch (final ConversionException e) { - assertThat( - e.getMessage(), - equalTo("subtaskindex must be positive, was: " + Integer.MIN_VALUE)); + assertThat(e.getMessage()) + .isEqualTo("subtaskindex must be positive, was: " + Integer.MIN_VALUE); } } @Test - public void testConvertToString() throws Exception { - assertThat( - subtaskIndexPathParameter.convertToString(Integer.MAX_VALUE), - equalTo("2147483647")); + void testConvertToString() throws Exception { + assertThat(subtaskIndexPathParameter.convertToString(Integer.MAX_VALUE)) + .isEqualTo("2147483647"); } @Test - public void testIsMandatoryParameter() { - assertTrue(subtaskIndexPathParameter.isMandatory()); + void testIsMandatoryParameter() { + assertThat(subtaskIndexPathParameter.isMandatory()).isTrue(); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtasksTimesInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtasksTimesInfoTest.java index 83b03f6253f0e1..b04f802c082094 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtasksTimesInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/SubtasksTimesInfoTest.java @@ -26,7 +26,7 @@ import java.util.Map; /** Tests that the {@link SubtasksTimesInfo} can be marshalled and unmarshalled. */ -public class SubtasksTimesInfoTest extends RestResponseMarshallingTestBase { +class SubtasksTimesInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ThreadDumpInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ThreadDumpInfoTest.java index f8ae6b2e0656e1..cd076e95d755ad 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ThreadDumpInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ThreadDumpInfoTest.java @@ -18,7 +18,7 @@ package org.apache.flink.runtime.rest.messages; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; @@ -26,14 +26,10 @@ import java.util.Arrays; import java.util.Collection; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** Test for (un)marshalling of the {@link ThreadDumpInfo}. */ -public class ThreadDumpInfoTest extends RestResponseMarshallingTestBase { +class ThreadDumpInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { @@ -53,12 +49,12 @@ protected ThreadDumpInfo getTestResponseInstance() throws Exception { @Override protected void assertOriginalEqualsToUnmarshalled( ThreadDumpInfo expected, ThreadDumpInfo actual) { - assertThat( - actual.getThreadInfos(), containsInAnyOrder(expected.getThreadInfos().toArray())); + assertThat(actual.getThreadInfos()) + .isEqualTo(Arrays.asList(expected.getThreadInfos().toArray())); } @Test - public void testComparedWithDefaultJDKImplemetation() { + void testComparedWithDefaultJDKImplemetation() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); ThreadInfo threadInfo = threadMxBean.getThreadInfo(Thread.currentThread().getId(), Integer.MAX_VALUE); @@ -73,11 +69,11 @@ public void testComparedWithDefaultJDKImplemetation() { String[] stringified = Arrays.copyOfRange(stringifyThreadInfoLines, 1, stringifyThreadInfoLines.length); - assertArrayEquals(expected, stringified); + assertThat(stringified).isEqualTo(expected); } @Test - public void testStacktraceDepthLimitation() { + void testStacktraceDepthLimitation() { ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean(); ThreadInfo threadInfo = threadMxBean.getThreadInfo(Thread.currentThread().getId(), Integer.MAX_VALUE); @@ -85,12 +81,13 @@ public void testStacktraceDepthLimitation() { int expectedStacktraceDepth = threadInfo.getStackTrace().length; String stringifiedInfo = ThreadDumpInfo.stringifyThreadInfo(threadInfo, Integer.MAX_VALUE); - assertEquals(expectedStacktraceDepth, getOutputDepth(stringifiedInfo)); + assertThat(getOutputDepth(stringifiedInfo)).isEqualTo(expectedStacktraceDepth); String stringifiedInfoExceedMaxDepth = ThreadDumpInfo.stringifyThreadInfo(threadInfo, expectedStacktraceDepth - 1); - assertEquals(expectedStacktraceDepth - 1, getOutputDepth(stringifiedInfoExceedMaxDepth)); - assertTrue(stringifiedInfoExceedMaxDepth.contains("\t...")); + assertThat(getOutputDepth(stringifiedInfoExceedMaxDepth)) + .isEqualTo(expectedStacktraceDepth - 1); + assertThat(stringifiedInfoExceedMaxDepth.contains("\t...")).isTrue(); } private long getOutputDepth(String stringifiedInfo) { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureLevelTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureLevelTest.java index 1ab31a81b1a3c4..17047eb53d81ed 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureLevelTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureLevelTest.java @@ -19,33 +19,34 @@ package org.apache.flink.runtime.rest.messages; import org.apache.flink.runtime.rest.util.RestMapperUtils; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JobVertexBackPressureInfo.VertexBackPressureLevel}. */ -public class VertexBackPressureLevelTest extends TestLogger { +class VertexBackPressureLevelTest { /** * Tests that the enum values are serialized correctly. Clients, such as the Web UI, expect * values to be lower case. */ @Test - public void testJsonValue() throws Exception { - assertEquals( - "\"ok\"", - RestMapperUtils.getStrictObjectMapper() - .writeValueAsString(JobVertexBackPressureInfo.VertexBackPressureLevel.OK)); - assertEquals( - "\"low\"", - RestMapperUtils.getStrictObjectMapper() - .writeValueAsString(JobVertexBackPressureInfo.VertexBackPressureLevel.LOW)); - assertEquals( - "\"high\"", - RestMapperUtils.getStrictObjectMapper() - .writeValueAsString( - JobVertexBackPressureInfo.VertexBackPressureLevel.HIGH)); + void testJsonValue() throws Exception { + assertThat( + RestMapperUtils.getStrictObjectMapper() + .writeValueAsString( + JobVertexBackPressureInfo.VertexBackPressureLevel.OK)) + .isEqualTo("\"ok\""); + assertThat( + RestMapperUtils.getStrictObjectMapper() + .writeValueAsString( + JobVertexBackPressureInfo.VertexBackPressureLevel.LOW)) + .isEqualTo("\"low\""); + assertThat( + RestMapperUtils.getStrictObjectMapper() + .writeValueAsString( + JobVertexBackPressureInfo.VertexBackPressureLevel.HIGH)) + .isEqualTo("\"high\""); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureStatusTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureStatusTest.java index 61642add32ab9c..9fa61498410097 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureStatusTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/VertexBackPressureStatusTest.java @@ -19,29 +19,30 @@ package org.apache.flink.runtime.rest.messages; import org.apache.flink.runtime.rest.util.RestMapperUtils; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JobVertexBackPressureInfo.VertexBackPressureStatus}. */ -public class VertexBackPressureStatusTest extends TestLogger { +class VertexBackPressureStatusTest { /** * Tests that the enum values are serialized correctly. Clients, such as the Web UI, expect * values to be lower case. */ @Test - public void testJsonValue() throws Exception { - assertEquals( - "\"ok\"", - RestMapperUtils.getStrictObjectMapper() - .writeValueAsString(JobVertexBackPressureInfo.VertexBackPressureStatus.OK)); - assertEquals( - "\"deprecated\"", - RestMapperUtils.getStrictObjectMapper() - .writeValueAsString( - JobVertexBackPressureInfo.VertexBackPressureStatus.DEPRECATED)); + void testJsonValue() throws Exception { + assertThat( + RestMapperUtils.getStrictObjectMapper() + .writeValueAsString( + JobVertexBackPressureInfo.VertexBackPressureStatus.OK)) + .isEqualTo("\"ok\""); + assertThat( + RestMapperUtils.getStrictObjectMapper() + .writeValueAsString( + JobVertexBackPressureInfo.VertexBackPressureStatus + .DEPRECATED)) + .isEqualTo("\"deprecated\""); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnCancelJobTerminationHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnCancelJobTerminationHeadersTest.java index 013a4167af737e..e104b84b50200e 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnCancelJobTerminationHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnCancelJobTerminationHeadersTest.java @@ -19,28 +19,25 @@ package org.apache.flink.runtime.rest.messages; import org.apache.flink.runtime.rest.HttpMethodWrapper; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for the {@link YarnCancelJobTerminationHeaders}. */ -public class YarnCancelJobTerminationHeadersTest extends TestLogger { +public class YarnCancelJobTerminationHeadersTest { // instance under test private static final YarnCancelJobTerminationHeaders instance = YarnCancelJobTerminationHeaders.getInstance(); @Test - public void testMethod() { - assertThat(instance.getHttpMethod(), is(HttpMethodWrapper.GET)); + void testMethod() { + assertThat(instance.getHttpMethod()).isEqualTo(HttpMethodWrapper.GET); } @Test - public void testURL() { - assertThat(instance.getTargetRestEndpointURL(), endsWith("yarn-cancel")); + void testURL() { + assertThat(instance.getTargetRestEndpointURL()).endsWith("yarn-cancel"); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnStopJobTerminationHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnStopJobTerminationHeadersTest.java index 3f469b4e4700fd..7640f33f9b45ec 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnStopJobTerminationHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/YarnStopJobTerminationHeadersTest.java @@ -19,28 +19,25 @@ package org.apache.flink.runtime.rest.messages; import org.apache.flink.runtime.rest.HttpMethodWrapper; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link YarnStopJobTerminationHeaders}. */ -public class YarnStopJobTerminationHeadersTest extends TestLogger { +class YarnStopJobTerminationHeadersTest { // instance under test private static final YarnStopJobTerminationHeaders instance = YarnStopJobTerminationHeaders.getInstance(); @Test - public void testMethod() { - assertThat(instance.getHttpMethod(), is(HttpMethodWrapper.GET)); + void testMethod() { + assertThat(instance.getHttpMethod()).isEqualTo(HttpMethodWrapper.GET); } @Test - public void testURL() { - assertThat(instance.getTargetRestEndpointURL(), endsWith("yarn-stop")); + void testURL() { + assertThat(instance.getTargetRestEndpointURL()).endsWith("yarn-stop"); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointConfigInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointConfigInfoTest.java index a652ed89210f74..5ddfffc5694fea 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointConfigInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointConfigInfoTest.java @@ -18,11 +18,10 @@ package org.apache.flink.runtime.rest.messages.checkpoints; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; /** Tests for the {@link CheckpointConfigInfo}. */ -public class CheckpointConfigInfoTest - extends RestResponseMarshallingTestBase { +class CheckpointConfigInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return CheckpointConfigInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointingStatisticsTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointingStatisticsTest.java index 3afc8daac3a94f..25133f8b5eff2a 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointingStatisticsTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointingStatisticsTest.java @@ -23,7 +23,7 @@ import org.apache.flink.runtime.checkpoint.CheckpointType; import org.apache.flink.runtime.checkpoint.SavepointType; import org.apache.flink.runtime.jobgraph.JobVertexID; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import org.apache.flink.runtime.rest.messages.checkpoints.CheckpointStatistics.RestAPICheckpointType; import org.junit.jupiter.api.Test; @@ -37,8 +37,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; /** Tests for {@link CheckpointingStatistics}. */ -public class CheckpointingStatisticsTest - extends RestResponseMarshallingTestBase { +class CheckpointingStatisticsTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return CheckpointingStatistics.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsTest.java index 0bffe6f1c1a7f9..6dbc09c27f1253 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsTest.java @@ -19,11 +19,11 @@ package org.apache.flink.runtime.rest.messages.checkpoints; import org.apache.flink.runtime.checkpoint.CheckpointStatsStatus; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; /** Tests the (un)marshalling of {@link TaskCheckpointStatistics}. */ -public class TaskCheckpointStatisticsTest - extends RestResponseMarshallingTestBase { +class TaskCheckpointStatisticsTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsWithSubtaskDetailsTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsWithSubtaskDetailsTest.java index 4d2498aa071232..b5bf0601cf4c9b 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsWithSubtaskDetailsTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/checkpoints/TaskCheckpointStatisticsWithSubtaskDetailsTest.java @@ -19,14 +19,14 @@ package org.apache.flink.runtime.rest.messages.checkpoints; import org.apache.flink.runtime.checkpoint.CheckpointStatsStatus; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.ArrayList; import java.util.List; /** Tests (un)marshalling of {@link TaskCheckpointStatisticsWithSubtaskDetails}. */ -public class TaskCheckpointStatisticsWithSubtaskDetailsTest - extends RestResponseMarshallingTestBase { +class TaskCheckpointStatisticsWithSubtaskDetailsTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/dataset/ClusterDataSetListResponseBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/dataset/ClusterDataSetListResponseBodyTest.java index ddadd2d627708b..6fefeac0470171 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/dataset/ClusterDataSetListResponseBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/dataset/ClusterDataSetListResponseBodyTest.java @@ -19,26 +19,24 @@ import org.apache.flink.runtime.io.network.partition.DataSetMetaInfo; import org.apache.flink.runtime.jobgraph.IntermediateDataSetID; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import org.apache.flink.util.AbstractID; import org.apache.flink.util.StringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link ClusterDataSetListResponseBody}. */ -public class ClusterDataSetListResponseBodyTest - extends RestResponseMarshallingTestBase { +class ClusterDataSetListResponseBodyTest + extends RestResponseUnmarshallingTestBase { @Test - public void testFrom() { + void testFrom() { final Map originalDataSets = new HashMap<>(); originalDataSets.put( new IntermediateDataSetID(), DataSetMetaInfo.withNumRegisteredPartitions(1, 2)); @@ -47,7 +45,7 @@ public void testFrom() { List convertedDataSets = ClusterDataSetListResponseBody.from(originalDataSets).getDataSets(); - assertThat(convertedDataSets, hasSize(2)); + assertThat(convertedDataSets).hasSize(2); for (ClusterDataSetEntry convertedDataSet : convertedDataSets) { IntermediateDataSetID id = new IntermediateDataSetID( @@ -56,11 +54,10 @@ public void testFrom() { DataSetMetaInfo dataSetMetaInfo = originalDataSets.get(id); - assertThat( - convertedDataSet.isComplete(), - is( + assertThat(convertedDataSet.isComplete()) + .isEqualTo( dataSetMetaInfo.getNumRegisteredPartitions().orElse(0) - == dataSetMetaInfo.getNumTotalPartitions())); + == dataSetMetaInfo.getNumTotalPartitions()); } } @@ -83,13 +80,13 @@ protected void assertOriginalEqualsToUnmarshalled( final List expectedDataSets = expected.getDataSets(); final List actualDataSets = actual.getDataSets(); - assertThat(actualDataSets, hasSize(expectedDataSets.size())); + assertThat(actualDataSets).hasSize(expectedDataSets.size()); for (int i = 0; i < expectedDataSets.size(); i++) { ClusterDataSetEntry expectedDataSet = expectedDataSets.get(i); ClusterDataSetEntry actualDataSet = actualDataSets.get(i); - assertThat(actualDataSet.getDataSetId(), is(expectedDataSet.getDataSetId())); - assertThat(actualDataSet.isComplete(), is(expectedDataSet.isComplete())); + assertThat(actualDataSet.getDataSetId()).isEqualTo(expectedDataSet.getDataSetId()); + assertThat(actualDataSet.isComplete()).isEqualTo(expectedDataSet.isComplete()); } } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobDetailsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobDetailsInfoTest.java index 1c281cf24e05f1..216fcaf922b8d0 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobDetailsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobDetailsInfoTest.java @@ -23,7 +23,7 @@ import org.apache.flink.runtime.execution.ExecutionState; import org.apache.flink.runtime.jobgraph.JobVertexID; import org.apache.flink.runtime.rest.messages.JobPlanInfo; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import org.apache.flink.runtime.rest.messages.job.metrics.IOMetricsInfo; import java.util.ArrayList; @@ -33,7 +33,7 @@ import java.util.Random; /** Tests (un)marshalling of the {@link JobDetailsInfo}. */ -public class JobDetailsInfoTest extends RestResponseMarshallingTestBase { +class JobDetailsInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobExecutionResultResponseBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobExecutionResultResponseBodyTest.java index bf7586633e7a69..041124b3906d5c 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobExecutionResultResponseBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobExecutionResultResponseBodyTest.java @@ -22,12 +22,13 @@ import org.apache.flink.runtime.clusterframework.ApplicationStatus; import org.apache.flink.runtime.jobmaster.JobResult; import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; import org.apache.flink.util.OptionalFailure; import org.apache.flink.util.SerializedThrowable; import org.apache.flink.util.SerializedValue; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.IOException; import java.util.Arrays; @@ -36,13 +37,10 @@ import java.util.Map; import java.util.Optional; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Test for {@link JobExecutionResultResponseBody}. */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class JobExecutionResultResponseBodyTest extends RestResponseMarshallingTestBase { @@ -58,7 +56,7 @@ public class JobExecutionResultResponseBodyTest Collections.singletonMap( TEST_ACCUMULATOR_NAME, SerializedValue.fromBytes(TEST_ACCUMULATOR_VALUE)); - @Parameterized.Parameters + @Parameters public static Collection data() throws IOException { return Arrays.asList( new Object[][] { @@ -109,26 +107,22 @@ protected void assertOriginalEqualsToUnmarshalled( final JobExecutionResultResponseBody expected, final JobExecutionResultResponseBody actual) { - assertThat(actual.getStatus(), equalTo(actual.getStatus())); + assertThat(actual.getStatus()).isEqualTo(actual.getStatus()); final JobResult expectedJobExecutionResult = expected.getJobExecutionResult(); final JobResult actualJobExecutionResult = actual.getJobExecutionResult(); if (expectedJobExecutionResult != null) { - assertNotNull(actualJobExecutionResult); - - assertThat( - actualJobExecutionResult.getJobId(), - equalTo(expectedJobExecutionResult.getJobId())); - assertThat( - actualJobExecutionResult.getApplicationStatus(), - equalTo(expectedJobExecutionResult.getApplicationStatus())); - assertThat( - actualJobExecutionResult.getNetRuntime(), - equalTo(expectedJobExecutionResult.getNetRuntime())); - assertThat( - actualJobExecutionResult.getAccumulatorResults(), - equalTo(expectedJobExecutionResult.getAccumulatorResults())); + assertThat(actualJobExecutionResult).isNotNull(); + + assertThat(actualJobExecutionResult.getJobId()) + .isEqualTo(expectedJobExecutionResult.getJobId()); + assertThat(actualJobExecutionResult.getApplicationStatus()) + .isEqualTo(expectedJobExecutionResult.getApplicationStatus()); + assertThat(actualJobExecutionResult.getNetRuntime()) + .isEqualTo(expectedJobExecutionResult.getNetRuntime()); + assertThat(actualJobExecutionResult.getAccumulatorResults()) + .isEqualTo(expectedJobExecutionResult.getAccumulatorResults()); final Optional expectedFailureCauseOptional = expectedJobExecutionResult.getSerializedThrowable(); @@ -141,28 +135,26 @@ protected void assertOriginalEqualsToUnmarshalled( () -> new AssertionError( "actualFailureCause is not available")); - assertThat( - actualFailureCause.getFullStringifiedStackTrace(), - equalTo(expectedFailureCause.getFullStringifiedStackTrace())); - assertThat( - actualFailureCause.getOriginalErrorClassName(), - equalTo(expectedFailureCause.getOriginalErrorClassName())); - assertArrayEquals( - expectedFailureCause.getSerializedException(), - actualFailureCause.getSerializedException()); + assertThat(actualFailureCause.getFullStringifiedStackTrace()) + .isEqualTo(expectedFailureCause.getFullStringifiedStackTrace()); + assertThat(actualFailureCause.getOriginalErrorClassName()) + .isEqualTo(expectedFailureCause.getOriginalErrorClassName()); + assertThat(expectedFailureCause.getSerializedException()) + .isEqualTo(actualFailureCause.getSerializedException()); }); if (expectedJobExecutionResult.getAccumulatorResults() != null) { - assertNotNull(actualJobExecutionResult.getAccumulatorResults()); - assertArrayEquals( - actualJobExecutionResult - .getAccumulatorResults() - .get(TEST_ACCUMULATOR_NAME) - .getByteArray(), - expectedJobExecutionResult - .getAccumulatorResults() - .get(TEST_ACCUMULATOR_NAME) - .getByteArray()); + assertThat(actualJobExecutionResult.getAccumulatorResults()).isNotNull(); + assertThat( + actualJobExecutionResult + .getAccumulatorResults() + .get(TEST_ACCUMULATOR_NAME) + .getByteArray()) + .isEqualTo( + expectedJobExecutionResult + .getAccumulatorResults() + .get(TEST_ACCUMULATOR_NAME) + .getByteArray()); } } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobResourceRequirementsBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobResourceRequirementsBodyTest.java index cfb2ac8d522c82..426b084cb8d383 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobResourceRequirementsBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/JobResourceRequirementsBodyTest.java @@ -20,18 +20,19 @@ import org.apache.flink.runtime.jobgraph.JobResourceRequirements; import org.apache.flink.runtime.jobgraph.JobVertexID; -import org.apache.flink.runtime.rest.messages.RestRequestMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestRequestUnmarshallingTestBase; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; import java.util.Optional; -import static org.hamcrest.MatcherAssert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.HamcrestCondition.matching; /** Tests for the marshalling of {@link JobResourceRequirementsBody}. */ public class JobResourceRequirementsBodyTest - extends RestRequestMarshallingTestBase { + extends RestRequestUnmarshallingTestBase { @Override protected Class getTestRequestClass() { return JobResourceRequirementsBody.class; @@ -49,7 +50,7 @@ protected JobResourceRequirementsBody getTestRequestInstance() { @Override protected void assertOriginalEqualsToUnmarshalled( JobResourceRequirementsBody expected, JobResourceRequirementsBody actual) { - assertThat(expected, equalsChangeJobRequestBody(actual)); + assertThat(expected).satisfies(matching(equalsChangeJobRequestBody(actual))); } private EqualityChangeJobRequestBodyMatcher equalsChangeJobRequestBody( diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptAccumulatorsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptAccumulatorsInfoTest.java index 2ea0c2b43593c4..c977e0ee0f7d57 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptAccumulatorsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptAccumulatorsInfoTest.java @@ -20,7 +20,7 @@ import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.jobgraph.JobVertexID; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.ArrayList; import java.util.List; @@ -28,8 +28,8 @@ import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; /** Tests (un)marshalling of the {@link SubtaskExecutionAttemptAccumulatorsInfo}. */ -public class SubtaskExecutionAttemptAccumulatorsInfoTest - extends RestResponseMarshallingTestBase { +class SubtaskExecutionAttemptAccumulatorsInfoTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptDetailsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptDetailsInfoTest.java index c4110811e0cda6..1e800f919e8c3c 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptDetailsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtaskExecutionAttemptDetailsInfoTest.java @@ -19,7 +19,7 @@ package org.apache.flink.runtime.rest.messages.job; import org.apache.flink.runtime.execution.ExecutionState; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import org.apache.flink.runtime.rest.messages.job.metrics.IOMetricsInfo; import java.util.HashMap; @@ -27,8 +27,8 @@ import java.util.Random; /** Tests (un)marshalling of the {@link SubtaskExecutionAttemptDetailsInfo}. */ -public class SubtaskExecutionAttemptDetailsInfoTest - extends RestResponseMarshallingTestBase { +class SubtaskExecutionAttemptDetailsInfoTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtasksAllAccumulatorsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtasksAllAccumulatorsInfoTest.java index e40e59a9369539..e264d9d23f02c4 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtasksAllAccumulatorsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/SubtasksAllAccumulatorsInfoTest.java @@ -19,14 +19,14 @@ package org.apache.flink.runtime.rest.messages.job; import org.apache.flink.runtime.jobgraph.JobVertexID; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.ArrayList; import java.util.List; /** Tests (un)marshalling of the {@link SubtasksAllAccumulatorsInfo}. */ -public class SubtasksAllAccumulatorsInfoTest - extends RestResponseMarshallingTestBase { +class SubtasksAllAccumulatorsInfoTest + extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { return SubtasksAllAccumulatorsInfo.class; diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/AbstractMetricsHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/AbstractMetricsHeadersTest.java index 2532475adf6b14..da88f1065cce7d 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/AbstractMetricsHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/AbstractMetricsHeadersTest.java @@ -21,23 +21,21 @@ import org.apache.flink.runtime.rest.HttpMethodWrapper; import org.apache.flink.runtime.rest.messages.EmptyMessageParameters; import org.apache.flink.runtime.rest.messages.EmptyRequestBody; -import org.apache.flink.util.TestLogger; import org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link AbstractMetricsHeaders}. */ -public class AbstractMetricsHeadersTest extends TestLogger { +class AbstractMetricsHeadersTest { private AbstractMetricsHeaders metricsHandlerHeaders; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { metricsHandlerHeaders = new AbstractMetricsHeaders() { @Override @@ -58,24 +56,23 @@ public String getDescription() { } @Test - public void testHttpMethod() { - assertThat(metricsHandlerHeaders.getHttpMethod(), equalTo(HttpMethodWrapper.GET)); + void testHttpMethod() { + assertThat(metricsHandlerHeaders.getHttpMethod()).isEqualTo(HttpMethodWrapper.GET); } @Test - public void testResponseStatus() { - assertThat(metricsHandlerHeaders.getResponseStatusCode(), equalTo(HttpResponseStatus.OK)); + void testResponseStatus() { + assertThat(metricsHandlerHeaders.getResponseStatusCode()).isEqualTo(HttpResponseStatus.OK); } @Test - public void testRequestClass() { - assertThat(metricsHandlerHeaders.getRequestClass(), equalTo(EmptyRequestBody.class)); + void testRequestClass() { + assertThat(metricsHandlerHeaders.getRequestClass()).isEqualTo(EmptyRequestBody.class); } @Test - public void testResponseClass() { - assertThat( - metricsHandlerHeaders.getResponseClass(), - equalTo(MetricCollectionResponseBody.class)); + void testResponseClass() { + assertThat(metricsHandlerHeaders.getResponseClass()) + .isEqualTo(MetricCollectionResponseBody.class); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobManagerMetricsHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobManagerMetricsHeadersTest.java index ebca283d94bd45..4da88bc3354b8f 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobManagerMetricsHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobManagerMetricsHeadersTest.java @@ -18,31 +18,25 @@ package org.apache.flink.runtime.rest.messages.job.metrics; -import org.apache.flink.util.TestLogger; +import org.junit.jupiter.api.Test; -import org.junit.Test; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JobManagerMetricsHeaders}. */ -public class JobManagerMetricsHeadersTest extends TestLogger { +class JobManagerMetricsHeadersTest { private final JobManagerMetricsHeaders jobManagerMetricsHeaders = JobManagerMetricsHeaders.getInstance(); @Test - public void testUrl() { - assertThat( - jobManagerMetricsHeaders.getTargetRestEndpointURL(), - equalTo("/jobmanager/metrics")); + void testUrl() { + assertThat(jobManagerMetricsHeaders.getTargetRestEndpointURL()) + .isEqualTo("/jobmanager/metrics"); } @Test - public void testMessageParameters() { - assertThat( - jobManagerMetricsHeaders.getUnresolvedMessageParameters(), - instanceOf(JobManagerMetricsMessageParameters.class)); + void testMessageParameters() { + assertThat(jobManagerMetricsHeaders.getUnresolvedMessageParameters()) + .isInstanceOf(JobManagerMetricsMessageParameters.class); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobMetricsHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobMetricsHeadersTest.java index 6b39d3fb52c595..9d6388bbb5ee16 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobMetricsHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobMetricsHeadersTest.java @@ -19,30 +19,25 @@ package org.apache.flink.runtime.rest.messages.job.metrics; import org.apache.flink.runtime.rest.messages.JobIDPathParameter; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JobMetricsHeaders}. */ -public class JobMetricsHeadersTest extends TestLogger { +class JobMetricsHeadersTest { private final JobMetricsHeaders jobMetricsHeaders = JobMetricsHeaders.getInstance(); @Test - public void testUrl() { - assertThat( - jobMetricsHeaders.getTargetRestEndpointURL(), - equalTo("/jobs/:" + JobIDPathParameter.KEY + "/metrics")); + void testUrl() { + assertThat(jobMetricsHeaders.getTargetRestEndpointURL()) + .isEqualTo("/jobs/:" + JobIDPathParameter.KEY + "/metrics"); } @Test - public void testMessageParameters() { - assertThat( - jobMetricsHeaders.getUnresolvedMessageParameters(), - instanceOf(JobMetricsMessageParameters.class)); + void testMessageParameters() { + assertThat(jobMetricsHeaders.getUnresolvedMessageParameters()) + .isInstanceOf(JobMetricsMessageParameters.class); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobVertexMetricsHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobVertexMetricsHeadersTest.java index f06d8c6fbddc89..40b4bbf03ee2af 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobVertexMetricsHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/JobVertexMetricsHeadersTest.java @@ -20,36 +20,31 @@ import org.apache.flink.runtime.rest.messages.JobIDPathParameter; import org.apache.flink.runtime.rest.messages.JobVertexIdPathParameter; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JobVertexMetricsHeaders}. */ -public class JobVertexMetricsHeadersTest extends TestLogger { +class JobVertexMetricsHeadersTest { private final JobVertexMetricsHeaders jobVertexMetricsHeaders = JobVertexMetricsHeaders.getInstance(); @Test - public void testUrl() { - assertThat( - jobVertexMetricsHeaders.getTargetRestEndpointURL(), - equalTo( + void testUrl() { + assertThat(jobVertexMetricsHeaders.getTargetRestEndpointURL()) + .isEqualTo( "/jobs/:" + JobIDPathParameter.KEY + "/vertices/:" + JobVertexIdPathParameter.KEY - + "/metrics")); + + "/metrics"); } @Test - public void testMessageParameters() { - assertThat( - jobVertexMetricsHeaders.getUnresolvedMessageParameters(), - instanceOf(JobVertexMetricsMessageParameters.class)); + void testMessageParameters() { + assertThat(jobVertexMetricsHeaders.getUnresolvedMessageParameters()) + .isInstanceOf(JobVertexMetricsMessageParameters.class); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricCollectionResponseBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricCollectionResponseBodyTest.java index 8123e5edd45c37..ad0c20b6e7b15e 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricCollectionResponseBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricCollectionResponseBodyTest.java @@ -18,22 +18,18 @@ package org.apache.flink.runtime.rest.messages.job.metrics; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import org.apache.flink.runtime.rest.util.RestMapperUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.not; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link MetricCollectionResponseBody}. */ -public class MetricCollectionResponseBodyTest - extends RestResponseMarshallingTestBase { +class MetricCollectionResponseBodyTest + extends RestResponseUnmarshallingTestBase { private static final String TEST_METRIC_NAME = "metric1"; @@ -54,22 +50,22 @@ protected MetricCollectionResponseBody getTestResponseInstance() { protected void assertOriginalEqualsToUnmarshalled( MetricCollectionResponseBody expected, MetricCollectionResponseBody actual) { - assertThat(actual.getMetrics(), hasSize(1)); + assertThat(actual.getMetrics()).hasSize(1); final Metric metric = actual.getMetrics().iterator().next(); - assertThat(metric.getId(), equalTo(TEST_METRIC_NAME)); - assertThat(metric.getValue(), equalTo(TEST_METRIC_VALUE)); + assertThat(metric.getId()).isEqualTo(TEST_METRIC_NAME); + assertThat(metric.getValue()).isEqualTo(TEST_METRIC_VALUE); } @Test - public void testNullValueNotSerialized() throws Exception { + void testNullValueNotSerialized() throws Exception { final String json = RestMapperUtils.getStrictObjectMapper() .writeValueAsString( new MetricCollectionResponseBody( Collections.singleton(new Metric(TEST_METRIC_NAME)))); - assertThat(json, not(containsString("\"value\""))); - assertThat(json, not(containsString("\"metrics\""))); + assertThat(json).doesNotContain("\"value\""); + assertThat(json).doesNotContain("\"metrics\""); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricsFilterParameterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricsFilterParameterTest.java index bdf024e8713c35..63d42af9c096fe 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricsFilterParameterTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/MetricsFilterParameterTest.java @@ -18,33 +18,29 @@ package org.apache.flink.runtime.rest.messages.job.metrics; -import org.apache.flink.util.TestLogger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link MetricsFilterParameter}. */ -public class MetricsFilterParameterTest extends TestLogger { +class MetricsFilterParameterTest { private MetricsFilterParameter metricsFilterParameter; - @Before + @BeforeEach public void setUp() { metricsFilterParameter = new MetricsFilterParameter(); } @Test - public void testIsOptionalParameter() { - assertFalse(metricsFilterParameter.isMandatory()); + void testIsOptionalParameter() { + assertThat(metricsFilterParameter.isMandatory()).isFalse(); } @Test - public void testConversions() { - assertThat(metricsFilterParameter.convertValueToString("test"), equalTo("test")); - assertThat(metricsFilterParameter.convertStringToValue("test"), equalTo("test")); + void testConversions() { + assertThat(metricsFilterParameter.convertValueToString("test")).isEqualTo("test"); + assertThat(metricsFilterParameter.convertStringToValue("test")).isEqualTo("test"); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/SubtaskMetricsHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/SubtaskMetricsHeadersTest.java index f76c5e41349f91..c831166f4ce0ee 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/SubtaskMetricsHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/SubtaskMetricsHeadersTest.java @@ -21,37 +21,32 @@ import org.apache.flink.runtime.rest.messages.JobIDPathParameter; import org.apache.flink.runtime.rest.messages.JobVertexIdPathParameter; import org.apache.flink.runtime.rest.messages.SubtaskIndexPathParameter; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link SubtaskMetricsHeaders}. */ -public class SubtaskMetricsHeadersTest extends TestLogger { +public class SubtaskMetricsHeadersTest { private final SubtaskMetricsHeaders subtaskMetricsHeaders = SubtaskMetricsHeaders.getInstance(); @Test - public void testUrl() { - assertThat( - subtaskMetricsHeaders.getTargetRestEndpointURL(), - equalTo( + void testUrl() { + assertThat(subtaskMetricsHeaders.getTargetRestEndpointURL()) + .isEqualTo( "/jobs/:" + JobIDPathParameter.KEY + "/vertices/:" + JobVertexIdPathParameter.KEY + "/subtasks/:" + SubtaskIndexPathParameter.KEY - + "/metrics")); + + "/metrics"); } @Test - public void testMessageParameters() { - assertThat( - subtaskMetricsHeaders.getUnresolvedMessageParameters(), - instanceOf(SubtaskMetricsMessageParameters.class)); + void testMessageParameters() { + assertThat(subtaskMetricsHeaders.getUnresolvedMessageParameters()) + .isInstanceOf(SubtaskMetricsMessageParameters.class); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/TaskManagerMetricsHeadersTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/TaskManagerMetricsHeadersTest.java index 5cbc1afd31eb8f..c7d68897faa7bb 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/TaskManagerMetricsHeadersTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/TaskManagerMetricsHeadersTest.java @@ -19,31 +19,26 @@ package org.apache.flink.runtime.rest.messages.job.metrics; import org.apache.flink.runtime.rest.messages.taskmanager.TaskManagerIdPathParameter; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link TaskManagerMetricsHeaders}. */ -public class TaskManagerMetricsHeadersTest extends TestLogger { +public class TaskManagerMetricsHeadersTest { private final TaskManagerMetricsHeaders taskManagerMetricsHeaders = TaskManagerMetricsHeaders.getInstance(); @Test - public void testUrl() { - assertThat( - taskManagerMetricsHeaders.getTargetRestEndpointURL(), - equalTo("/taskmanagers/:" + TaskManagerIdPathParameter.KEY + "/metrics")); + void testUrl() { + assertThat(taskManagerMetricsHeaders.getTargetRestEndpointURL()) + .isEqualTo("/taskmanagers/:" + TaskManagerIdPathParameter.KEY + "/metrics"); } @Test - public void testMessageParameters() { - assertThat( - taskManagerMetricsHeaders.getUnresolvedMessageParameters(), - instanceOf(TaskManagerMetricsMessageParameters.class)); + void testMessageParameters() { + assertThat(taskManagerMetricsHeaders.getUnresolvedMessageParameters()) + .isInstanceOf(TaskManagerMetricsMessageParameters.class); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointDisposalRequestTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointDisposalRequestTest.java index c9856d97886850..4b94e29c81128a 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointDisposalRequestTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointDisposalRequestTest.java @@ -18,16 +18,15 @@ package org.apache.flink.runtime.rest.messages.job.savepoints; -import org.apache.flink.runtime.rest.messages.RestRequestMarshallingTestBase; - -import org.hamcrest.Matchers; -import org.junit.Assert; +import org.apache.flink.runtime.rest.messages.RestRequestUnmarshallingTestBase; import java.util.UUID; +import static org.assertj.core.api.Assertions.assertThat; + /** Tests the un/marshalling of the {@link SavepointDisposalRequest}. */ -public class SavepointDisposalRequestTest - extends RestRequestMarshallingTestBase { +class SavepointDisposalRequestTest + extends RestRequestUnmarshallingTestBase { @Override protected Class getTestRequestClass() { @@ -42,8 +41,6 @@ protected SavepointDisposalRequest getTestRequestInstance() { @Override protected void assertOriginalEqualsToUnmarshalled( SavepointDisposalRequest expected, SavepointDisposalRequest actual) { - Assert.assertThat( - actual.getSavepointPath(), - Matchers.is(Matchers.equalTo(expected.getSavepointPath()))); + assertThat(actual.getSavepointPath()).isEqualTo(expected.getSavepointPath()); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoMarshallingTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoMarshallingTest.java index 2d1374335d3ff9..0cfafe61bb9254 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoMarshallingTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoMarshallingTest.java @@ -19,23 +19,22 @@ package org.apache.flink.runtime.rest.messages.job.savepoints; import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; import org.apache.flink.util.SerializedThrowable; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; import java.util.Arrays; import java.util.Collection; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Marshalling tests for the {@link SavepointInfo}. */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class SavepointInfoMarshallingTest extends RestResponseMarshallingTestBase { - @Parameterized.Parameters + @Parameters public static Collection data() { return Arrays.asList( new Object[][] { @@ -66,17 +65,17 @@ protected SavepointInfo getTestResponseInstance() throws Exception { @Override protected void assertOriginalEqualsToUnmarshalled( SavepointInfo expected, SavepointInfo actual) { - assertThat(actual.getLocation(), is(expected.getLocation())); + assertThat(actual.getLocation()).isEqualTo(expected.getLocation()); if (expected.getFailureCause() != null) { - assertThat(actual.getFailureCause(), notNullValue()); + assertThat(actual.getFailureCause()).isNotNull(); assertThat( - actual.getFailureCause() - .deserializeError(ClassLoader.getSystemClassLoader()) - .getMessage(), - is( + actual.getFailureCause() + .deserializeError(ClassLoader.getSystemClassLoader()) + .getMessage()) + .isEqualTo( expected.getFailureCause() .deserializeError(ClassLoader.getSystemClassLoader()) - .getMessage())); + .getMessage()); } } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoTest.java index ffc62bf2c789c7..3bad39fb4b5485 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointInfoTest.java @@ -19,17 +19,16 @@ package org.apache.flink.runtime.rest.messages.job.savepoints; import org.apache.flink.util.SerializedThrowable; -import org.apache.flink.util.TestLogger; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; /** Tests for {@link SavepointInfo}. */ -public class SavepointInfoTest extends TestLogger { +class SavepointInfoTest { @Test - public void testSetBothLocationAndFailureCause() { + void testSetBothLocationAndFailureCause() { try { new SavepointInfo("/tmp", new SerializedThrowable(new RuntimeException())); fail("Expected exception not thrown"); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointTriggerRequestBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointTriggerRequestBodyTest.java index 5adf567871a351..dd0407fd492e46 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointTriggerRequestBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/SavepointTriggerRequestBodyTest.java @@ -21,17 +21,18 @@ import org.apache.flink.core.execution.SavepointFormatType; import org.apache.flink.runtime.rest.messages.RestRequestMarshallingTestBase; import org.apache.flink.runtime.rest.messages.TriggerId; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; import java.util.Arrays; import java.util.Collection; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link SavepointTriggerRequestBody}. */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class SavepointTriggerRequestBodyTest extends RestRequestMarshallingTestBase { @@ -42,7 +43,7 @@ public SavepointTriggerRequestBodyTest( this.savepointTriggerRequestBody = savepointTriggerRequestBody; } - @Parameterized.Parameters + @Parameters public static Collection data() { return Arrays.asList( new Object[][] { @@ -94,8 +95,8 @@ protected SavepointTriggerRequestBody getTestRequestInstance() { @Override protected void assertOriginalEqualsToUnmarshalled( final SavepointTriggerRequestBody expected, final SavepointTriggerRequestBody actual) { - assertEquals(expected.getTargetDirectory(), actual.getTargetDirectory()); - assertEquals(expected.getTriggerId(), actual.getTriggerId()); - assertEquals(expected.getFormatType(), actual.getFormatType()); + assertThat(actual.getTargetDirectory()).isEqualTo(expected.getTargetDirectory()); + assertThat(actual.getTriggerId()).isEqualTo(expected.getTriggerId()); + assertThat(actual.getFormatType()).isEqualTo(expected.getFormatType()); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/StopWithSavepointTriggerRequestBodyTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/StopWithSavepointTriggerRequestBodyTest.java index 913acec19bff7b..b91b9eac6bb6d6 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/StopWithSavepointTriggerRequestBodyTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/savepoints/StopWithSavepointTriggerRequestBodyTest.java @@ -22,17 +22,18 @@ import org.apache.flink.runtime.rest.messages.RestRequestMarshallingTestBase; import org.apache.flink.runtime.rest.messages.TriggerId; import org.apache.flink.runtime.rest.messages.job.savepoints.stop.StopWithSavepointRequestBody; +import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension; +import org.apache.flink.testutils.junit.extensions.parameterized.Parameters; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.extension.ExtendWith; import java.util.Arrays; import java.util.Collection; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link StopWithSavepointRequestBody}. */ -@RunWith(Parameterized.class) +@ExtendWith(ParameterizedTestExtension.class) public class StopWithSavepointTriggerRequestBodyTest extends RestRequestMarshallingTestBase { @@ -43,7 +44,7 @@ public StopWithSavepointTriggerRequestBodyTest( this.savepointTriggerRequestBody = savepointTriggerRequestBody; } - @Parameterized.Parameters + @Parameters public static Collection data() { return Arrays.asList( new Object[][] { @@ -96,9 +97,9 @@ protected StopWithSavepointRequestBody getTestRequestInstance() { protected void assertOriginalEqualsToUnmarshalled( final StopWithSavepointRequestBody expected, final StopWithSavepointRequestBody actual) { - assertEquals(expected.getTargetDirectory(), actual.getTargetDirectory()); - assertEquals(expected.getTriggerId(), actual.getTriggerId()); - assertEquals(expected.shouldDrain(), actual.shouldDrain()); - assertEquals(expected.getFormatType(), actual.getFormatType()); + assertThat(expected.getTargetDirectory()).isEqualTo(actual.getTargetDirectory()); + assertThat(expected.getTriggerId()).isEqualTo(actual.getTriggerId()); + assertThat(expected.shouldDrain()).isEqualTo(actual.shouldDrain()); + assertThat(expected.getFormatType()).isEqualTo(actual.getFormatType()); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/JobResultDeserializerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/JobResultDeserializerTest.java index c9752f9fc3438a..ebb234dc6630e1 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/JobResultDeserializerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/JobResultDeserializerTest.java @@ -20,27 +20,24 @@ import org.apache.flink.api.common.JobID; import org.apache.flink.runtime.jobmaster.JobResult; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.jackson.JacksonMapperFactory; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonMappingException; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link JobResultDeserializer}. */ -public class JobResultDeserializerTest extends TestLogger { +class JobResultDeserializerTest { private ObjectMapper objectMapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { final SimpleModule simpleModule = new SimpleModule(); simpleModule.addDeserializer(JobResult.class, new JobResultDeserializer()); @@ -49,7 +46,7 @@ public void setUp() { } @Test - public void testDeserialization() throws Exception { + void testDeserialization() throws Exception { final JobResult jobResult = objectMapper.readValue( "{\n" @@ -60,16 +57,15 @@ public void testDeserialization() throws Exception { + "}", JobResult.class); - assertThat( - jobResult.getJobId(), - equalTo(JobID.fromHexString("1bb5e8c7df49938733b7c6a73678de6a"))); - assertThat(jobResult.getNetRuntime(), equalTo(0L)); - assertThat(jobResult.getAccumulatorResults().size(), equalTo(0)); - assertThat(jobResult.getSerializedThrowable().isPresent(), equalTo(false)); + assertThat(jobResult.getJobId()) + .isEqualTo(JobID.fromHexString("1bb5e8c7df49938733b7c6a73678de6a")); + assertThat(jobResult.getNetRuntime()).isZero(); + assertThat(jobResult.getAccumulatorResults().size()).isZero(); + assertThat(jobResult.getSerializedThrowable()).isNotPresent(); } @Test - public void testInvalidType() throws Exception { + void testInvalidType() throws Exception { try { objectMapper.readValue( "{\n" @@ -78,20 +74,19 @@ public void testInvalidType() throws Exception { + "}", JobResult.class); } catch (final JsonMappingException e) { - assertThat( - e.getMessage(), - containsString("Expected token VALUE_NUMBER_INT (was VALUE_STRING)")); + assertThat(e.getMessage()) + .contains("Expected token VALUE_NUMBER_INT (was VALUE_STRING)"); } } @Test - public void testIncompleteJobResult() throws Exception { + void testIncompleteJobResult() throws Exception { try { objectMapper.readValue( "{\n" + "\t\"id\": \"1bb5e8c7df49938733b7c6a73678de6a\"\n" + "}", JobResult.class); } catch (final JsonMappingException e) { - assertThat(e.getMessage(), containsString("Could not deserialize JobResult")); + assertThat(e.getMessage()).contains("Could not deserialize JobResult"); } } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedThrowableSerializerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedThrowableSerializerTest.java index b167fa7fbcb326..a237bfa50ef902 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedThrowableSerializerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedThrowableSerializerTest.java @@ -19,25 +19,23 @@ package org.apache.flink.runtime.rest.messages.json; import org.apache.flink.util.SerializedThrowable; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.jackson.JacksonMapperFactory; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.module.SimpleModule; -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.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link SerializedThrowableSerializer} and {@link SerializedThrowableDeserializer}. */ -public class SerializedThrowableSerializerTest extends TestLogger { +class SerializedThrowableSerializerTest { private ObjectMapper objectMapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { final SimpleModule simpleModule = new SimpleModule(); simpleModule.addDeserializer( SerializedThrowable.class, new SerializedThrowableDeserializer()); @@ -48,7 +46,7 @@ public void setUp() { } @Test - public void testSerializationDeserialization() throws Exception { + void testSerializationDeserialization() throws Exception { Exception cause = new Exception("cause"); Exception root = new Exception("message", cause); Exception suppressed = new Exception("suppressed"); @@ -60,19 +58,18 @@ public void testSerializationDeserialization() throws Exception { final SerializedThrowable deserializedSerializedThrowable = objectMapper.readValue(json, SerializedThrowable.class); - assertEquals("java.lang.Exception: message", deserializedSerializedThrowable.getMessage()); - assertEquals( - serializedThrowable.getFullStringifiedStackTrace(), - deserializedSerializedThrowable.getFullStringifiedStackTrace()); - assertEquals( - "java.lang.Exception: cause", - deserializedSerializedThrowable.getCause().getMessage()); - assertTrue(deserializedSerializedThrowable.getCause() instanceof SerializedThrowable); - assertEquals(1, deserializedSerializedThrowable.getSuppressed().length); - assertEquals( - "java.lang.Exception: suppressed", - deserializedSerializedThrowable.getSuppressed()[0].getMessage()); - assertTrue( - deserializedSerializedThrowable.getSuppressed()[0] instanceof SerializedThrowable); + assertThat(deserializedSerializedThrowable.getMessage()) + .isEqualTo("java.lang.Exception: message"); + assertThat(serializedThrowable.getFullStringifiedStackTrace()) + .isEqualTo(deserializedSerializedThrowable.getFullStringifiedStackTrace()); + assertThat(deserializedSerializedThrowable.getCause().getMessage()) + .isEqualTo("java.lang.Exception: cause"); + assertThat(deserializedSerializedThrowable.getCause()) + .isInstanceOf(SerializedThrowable.class); + assertThat(deserializedSerializedThrowable.getSuppressed().length).isOne(); + assertThat(deserializedSerializedThrowable.getSuppressed()[0].getMessage()) + .isEqualTo("java.lang.Exception: suppressed"); + assertThat(deserializedSerializedThrowable.getSuppressed()[0]) + .isInstanceOf(SerializedThrowable.class); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedValueSerializerTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedValueSerializerTest.java index 6e6ec96cc64be9..f9c1389f6ebc5d 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedValueSerializerTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/json/SerializedValueSerializerTest.java @@ -19,7 +19,6 @@ package org.apache.flink.runtime.rest.messages.json; import org.apache.flink.util.SerializedValue; -import org.apache.flink.util.TestLogger; import org.apache.flink.util.jackson.JacksonMapperFactory; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.type.TypeReference; @@ -27,20 +26,20 @@ import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.module.SimpleModule; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.io.Serializable; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link SerializedValueSerializer} and {@link SerializedValueDeserializer}. */ -public class SerializedValueSerializerTest extends TestLogger { +class SerializedValueSerializerTest { private ObjectMapper objectMapper; - @Before - public void setUp() { + @BeforeEach + void setUp() { objectMapper = JacksonMapperFactory.createObjectMapper(); final SimpleModule simpleModule = new SimpleModule(); final JavaType serializedValueWildcardType = @@ -55,7 +54,7 @@ public void setUp() { } @Test - public void testSerializationDeserialization() throws Exception { + void testSerializationDeserialization() throws Exception { final String json = objectMapper.writeValueAsString(new SerializedValue<>(new TestClass())); final SerializedValue serializedValue = @@ -63,8 +62,8 @@ public void testSerializationDeserialization() throws Exception { final TestClass deserializedValue = serializedValue.deserializeValue(ClassLoader.getSystemClassLoader()); - assertEquals("baz", deserializedValue.foo); - assertEquals(1, deserializedValue.bar); + assertThat(deserializedValue.foo).isEqualTo("baz"); + assertThat(deserializedValue.bar).isOne(); } private static class TestClass implements Serializable { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/LogListInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/LogListInfoTest.java index c5e036cfbd6cc2..16c3f2e7adaddb 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/LogListInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/LogListInfoTest.java @@ -22,12 +22,12 @@ import org.apache.flink.runtime.rest.messages.LogInfo; import org.apache.flink.runtime.rest.messages.LogListInfo; import org.apache.flink.runtime.rest.messages.ResponseBody; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.Arrays; /** Tests for (un)marshalling of {@link LogListInfo}. */ -public class LogListInfoTest extends RestResponseMarshallingTestBase { +class LogListInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerDetailsInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerDetailsInfoTest.java index e4406bf5cc3f4b..4d8b93d252187c 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerDetailsInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerDetailsInfoTest.java @@ -21,7 +21,7 @@ import org.apache.flink.api.common.JobID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.resourcemanager.TaskManagerInfoWithSlots; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.ArrayList; import java.util.Collections; @@ -30,8 +30,7 @@ import java.util.UUID; /** Tests (un)marshalling of {@link TaskManagerDetailsInfo}. */ -public class TaskManagerDetailsInfoTest - extends RestResponseMarshallingTestBase { +class TaskManagerDetailsInfoTest extends RestResponseUnmarshallingTestBase { private static final Random random = new Random(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerIdPathParameterTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerIdPathParameterTest.java index 828e875779f52f..459fbf3d70704e 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerIdPathParameterTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerIdPathParameterTest.java @@ -19,38 +19,35 @@ package org.apache.flink.runtime.rest.messages.taskmanager; import org.apache.flink.runtime.clusterframework.types.ResourceID; -import org.apache.flink.util.TestLogger; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** Tests for {@link TaskManagerIdPathParameter}. */ -public class TaskManagerIdPathParameterTest extends TestLogger { +class TaskManagerIdPathParameterTest { private TaskManagerIdPathParameter taskManagerIdPathParameter; - @Before - public void setUp() { + @BeforeEach + void setUp() { taskManagerIdPathParameter = new TaskManagerIdPathParameter(); } @Test - public void testConversions() { + void testConversions() { final String resourceIdString = "foo"; final ResourceID resourceId = taskManagerIdPathParameter.convertFromString(resourceIdString); - assertThat(resourceId.getResourceIdString(), equalTo(resourceIdString)); + assertThat(resourceId.getResourceIdString()).isEqualTo(resourceIdString); - assertThat( - taskManagerIdPathParameter.convertToString(resourceId), equalTo(resourceIdString)); + assertThat(taskManagerIdPathParameter.convertToString(resourceId)) + .isEqualTo(resourceIdString); } @Test - public void testIsMandatory() { - assertTrue(taskManagerIdPathParameter.isMandatory()); + void testIsMandatory() { + assertThat(taskManagerIdPathParameter.isMandatory()).isTrue(); } } diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerInfoTest.java index 140134ee95300a..8c2e44133c752f 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagerInfoTest.java @@ -21,14 +21,14 @@ import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.instance.HardwareDescription; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import org.apache.flink.runtime.taskexecutor.TaskExecutorMemoryConfiguration; import java.util.Random; import java.util.UUID; /** Test for (un)marshalling of the {@link TaskManagerInfo}. */ -public class TaskManagerInfoTest extends RestResponseMarshallingTestBase { +class TaskManagerInfoTest extends RestResponseUnmarshallingTestBase { private static final Random random = new Random(); diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagersInfoTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagersInfoTest.java index 5292c2932a8ff9..863600d1791328 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagersInfoTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/taskmanager/TaskManagersInfoTest.java @@ -18,14 +18,14 @@ package org.apache.flink.runtime.rest.messages.taskmanager; -import org.apache.flink.runtime.rest.messages.RestResponseMarshallingTestBase; +import org.apache.flink.runtime.rest.messages.RestResponseUnmarshallingTestBase; import java.util.Arrays; import static org.apache.flink.runtime.rest.messages.taskmanager.TaskManagerInfoTest.createRandomTaskManagerInfo; /** Test for (un)marshalling of {@link TaskManagersInfo}. */ -public class TaskManagersInfoTest extends RestResponseMarshallingTestBase { +class TaskManagersInfoTest extends RestResponseUnmarshallingTestBase { @Override protected Class getTestResponseClass() { diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/versioning/RuntimeRestAPIVersionTest.java b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/versioning/RuntimeRestAPIVersionTest.java index 80df563618cd6d..52c2a464416479 100644 --- a/flink-runtime/src/test/java/org/apache/flink/runtime/rest/versioning/RuntimeRestAPIVersionTest.java +++ b/flink-runtime/src/test/java/org/apache/flink/runtime/rest/versioning/RuntimeRestAPIVersionTest.java @@ -18,36 +18,35 @@ package org.apache.flink.runtime.rest.versioning; -import org.apache.flink.util.TestLogger; - -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; +import static org.assertj.core.api.Assertions.assertThat; + /** Tests for {@link RuntimeRestAPIVersion}. */ -public class RuntimeRestAPIVersionTest extends TestLogger { +class RuntimeRestAPIVersionTest { @Test - public void testGetLatest() { + void testGetLatest() { Collection candidates = Arrays.asList(RuntimeRestAPIVersion.V0, RuntimeRestAPIVersion.V1); - Assert.assertEquals(RuntimeRestAPIVersion.V1, RestAPIVersion.getLatestVersion(candidates)); + assertThat(RestAPIVersion.getLatestVersion(candidates)).isEqualTo(RuntimeRestAPIVersion.V1); } @Test - public void testSingleDefaultVersion() { + void testSingleDefaultVersion() { final List defaultVersions = Arrays.stream(RuntimeRestAPIVersion.values()) .filter(RuntimeRestAPIVersion::isDefaultVersion) .collect(Collectors.toList()); - Assert.assertEquals( - "Only one RestAPIVersion should be marked as the default. Defaults: " - + defaultVersions, - 1, - defaultVersions.size()); + assertThat(defaultVersions.size()) + .as( + "Only one RestAPIVersion should be marked as the default. Defaults: " + + defaultVersions) + .isOne(); } }