You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by ch...@apache.org on 2022/04/27 10:55:37 UTC
[flink] branch master updated: [FLINK-25550][k8s] Migrate tests to JUnit 5
This is an automated email from the ASF dual-hosted git repository.
chesnay pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git
The following commit(s) were added to refs/heads/master by this push:
new 6fc5f789869 [FLINK-25550][k8s] Migrate tests to JUnit 5
6fc5f789869 is described below
commit 6fc5f789869433688eb5f62494f1a4404e0dd11b
Author: Weijie Guo <re...@163.com>
AuthorDate: Wed Apr 27 18:55:30 2022 +0800
[FLINK-25550][k8s] Migrate tests to JUnit 5
---
.../KubernetesClusterClientFactoryTest.java | 10 +-
.../KubernetesClusterDescriptorTest.java | 153 +++---
...netesResource.java => KubernetesExtension.java} | 24 +-
.../kubernetes/KubernetesPodTemplateTestUtils.java | 9 +-
.../KubernetesResourceManagerDriverTest.java | 143 +++---
.../flink/kubernetes/KubernetesTestBase.java | 66 +--
.../flink/kubernetes/KubernetesWorkerNodeTest.java | 23 +-
...er.java => MixedKubernetesServerExtension.java} | 14 +-
.../kubernetes/cli/KubernetesSessionCliTest.java | 104 ++--
.../KubernetesDeploymentTargetTest.java | 36 +-
.../KubernetesWorkerResourceSpecFactoryTest.java | 29 +-
.../KubernetesCheckpointIDCounterTest.java | 128 ++---
...HighAvailabilityRecoverFromSavepointITCase.java | 64 +--
.../KubernetesHighAvailabilityTestBase.java | 15 +-
...KubernetesLeaderElectionAndRetrievalITCase.java | 34 +-
.../KubernetesLeaderElectionDriverTest.java | 116 +++--
.../KubernetesLeaderRetrievalDriverTest.java | 26 +-
...sMultipleComponentLeaderElectionDriverTest.java | 13 +-
.../KubernetesStateHandleStoreITCase.java | 34 +-
.../KubernetesStateHandleStoreTest.java | 530 +++++++++++----------
.../highavailability/KubernetesTestFixture.java | 10 +-
.../kubeclient/Fabric8FlinkKubeClientITCase.java | 38 +-
.../kubeclient/Fabric8FlinkKubeClientTest.java | 381 +++++++--------
.../decorators/CmdJobManagerDecoratorTest.java | 38 +-
.../decorators/CmdTaskManagerDecoratorTest.java | 37 +-
.../DecoratorWithPodTemplateTestBase.java | 87 ++--
.../decorators/EnvSecretsDecoratorTest.java | 11 +-
.../decorators/ExternalServiceDecoratorTest.java | 57 +--
.../decorators/FlinkConfMountDecoratorTest.java | 84 ++--
.../decorators/HadoopConfMountDecoratorTest.java | 122 +++--
.../InitJobManagerDecoratorAccountTest.java | 14 +-
.../decorators/InitJobManagerDecoratorTest.java | 124 +++--
...InitJobManagerDecoratorWithPodTemplateTest.java | 17 +-
.../InitTaskManagerDecoratorAccountTest.java | 14 +-
.../decorators/InitTaskManagerDecoratorTest.java | 114 +++--
...nitTaskManagerDecoratorWithPodTemplateTest.java | 31 +-
.../decorators/InternalServiceDecoratorTest.java | 37 +-
.../decorators/KerberosMountDecoratorTest.java | 81 ++--
.../decorators/MountSecretsDecoratorTest.java | 46 +-
.../decorators/PodTemplateMountDecoratorTest.java | 52 +-
.../KubernetesFactoryWithPodTemplateTestBase.java | 127 +++--
.../factory/KubernetesJobManagerFactoryTest.java | 237 +++++----
...rnetesJobManagerFactoryWithPodTemplateTest.java | 2 +-
.../factory/KubernetesTaskManagerFactoryTest.java | 45 +-
...netesTaskManagerFactoryWithPodTemplateTest.java | 2 +-
.../AbstractKubernetesParametersTest.java | 82 ++--
.../KubernetesJobManagerParametersTest.java | 154 +++---
.../KubernetesTaskManagerParametersTest.java | 83 ++--
.../kubeclient/resources/FlinkPodTest.java | 27 +-
.../resources/KubernetesLeaderElectorITCase.java | 31 +-
.../resources/KubernetesLeaderElectorTest.java | 19 +-
.../kubeclient/resources/KubernetesPodTest.java | 13 +-
.../resources/KubernetesPodsWatcherTest.java | 42 +-
.../resources/KubernetesSharedInformerITCase.java | 71 ++-
.../kubeclient/services/ServiceTypeTest.java | 30 +-
.../kubernetes/utils/KubernetesUtilsTest.java | 141 +++---
.../org.junit.jupiter.api.extension.Extension | 16 +
.../flink/test/junit5/MiniClusterExtension.java | 4 +-
58 files changed, 1940 insertions(+), 2152 deletions(-)
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterClientFactoryTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterClientFactoryTest.java
index 29968f36057..d6a162d175f 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterClientFactoryTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterClientFactoryTest.java
@@ -25,15 +25,15 @@ import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.kubernetes.executors.KubernetesSessionClusterExecutor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** Test for the {@link KubernetesClusterClientFactory} discovery. */
-public class KubernetesClusterClientFactoryTest {
+class KubernetesClusterClientFactoryTest {
@Test
- public void testKubernetesClusterClientFactoryDiscoveryWithSessionExecutor() {
+ void testKubernetesClusterClientFactoryDiscoveryWithSessionExecutor() {
testKubernetesClusterClientFactoryDiscoveryHelper(KubernetesSessionClusterExecutor.NAME);
}
@@ -45,6 +45,6 @@ public class KubernetesClusterClientFactoryTest {
final ClusterClientFactory<String> factory =
serviceLoader.getClusterClientFactory(configuration);
- assertTrue(factory instanceof KubernetesClusterClientFactory);
+ assertThat(factory).isInstanceOf(KubernetesClusterClientFactory.class);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterDescriptorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterDescriptorTest.java
index e4e7865120f..0bb60dff9e8 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterDescriptorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesClusterDescriptorTest.java
@@ -40,21 +40,17 @@ import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.EnvVar;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.apps.Deployment;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
-import java.util.stream.Collectors;
-import static org.apache.flink.core.testutils.CommonTestUtils.assertThrows;
import static org.apache.flink.kubernetes.utils.Constants.ENV_FLINK_POD_IP_ADDRESS;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for the {@link KubernetesClusterDescriptor}. */
-public class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
+class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
private static final String MOCK_SERVICE_HOST_NAME = "mock-host-name-of-service";
private static final String MOCK_SERVICE_IP = "192.168.0.1";
@@ -77,7 +73,7 @@ public class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
}
@Test
- public void testDeploySessionCluster() throws Exception {
+ void testDeploySessionCluster() throws Exception {
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.SESSION.getName());
final ClusterClient<String> clusterClient = deploySessionCluster().getClusterClient();
checkClusterClient(clusterClient);
@@ -86,7 +82,7 @@ public class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
}
@Test
- public void testDeployHighAvailabilitySessionCluster() throws ClusterDeploymentException {
+ void testDeployHighAvailabilitySessionCluster() throws ClusterDeploymentException {
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.SESSION.getName());
flinkConfig.setString(
HighAvailabilityOptions.HA_MODE, HighAvailabilityMode.ZOOKEEPER.toString());
@@ -105,33 +101,30 @@ public class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
.getSpec()
.getContainers()
.get(0);
- assertTrue(
- "Environment " + ENV_FLINK_POD_IP_ADDRESS + " should be set.",
- jmContainer.getEnv().stream()
- .map(EnvVar::getName)
- .collect(Collectors.toList())
- .contains(ENV_FLINK_POD_IP_ADDRESS));
+ assertThat(jmContainer.getEnv().stream().map(EnvVar::getName))
+ .withFailMessage("Environment " + ENV_FLINK_POD_IP_ADDRESS + " should be set.")
+ .contains(ENV_FLINK_POD_IP_ADDRESS);
clusterClient.close();
}
@Test
- public void testKillCluster() throws Exception {
+ void testKillCluster() throws Exception {
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.SESSION.getName());
deploySessionCluster();
- assertEquals(2, kubeClient.services().list().getItems().size());
+ assertThat(kubeClient.services().list().getItems()).hasSize(2);
descriptor.killCluster(CLUSTER_ID);
// Mock kubernetes server do not delete the accompanying resources by gc.
- assertTrue(kubeClient.apps().deployments().list().getItems().isEmpty());
- assertEquals(2, kubeClient.services().list().getItems().size());
- assertEquals(1, kubeClient.configMaps().list().getItems().size());
+ assertThat(kubeClient.apps().deployments().list().getItems()).isEmpty();
+ assertThat(kubeClient.services().list().getItems()).hasSize(2);
+ assertThat(kubeClient.configMaps().list().getItems()).hasSize(1);
}
@Test
- public void testDeployApplicationCluster() {
+ void testDeployApplicationCluster() {
flinkConfig.set(
PipelineOptions.JARS, Collections.singletonList("local:///path/of/user.jar"));
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.APPLICATION.getName());
@@ -148,53 +141,70 @@ public class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
}
@Test
- public void testDeployApplicationClusterWithNonLocalSchema() {
+ void testDeployApplicationClusterWithNonLocalSchema() {
flinkConfig.set(
PipelineOptions.JARS, Collections.singletonList("file:///path/of/user.jar"));
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.APPLICATION.getName());
- assertThrows(
- "Only \"local\" is supported as schema for application mode.",
- IllegalArgumentException.class,
- () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig));
+ assertThatThrownBy(
+ () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig))
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining(
+ "Only \"local\" is supported as schema for application mode."));
}
@Test
- public void testDeployApplicationClusterWithClusterAlreadyExists() {
+ void testDeployApplicationClusterWithClusterAlreadyExists() {
flinkConfig.set(
PipelineOptions.JARS, Collections.singletonList("local:///path/of/user.jar"));
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.APPLICATION.getName());
mockExpectedServiceFromServerSide(loadBalancerSvc);
- assertThrows(
- "The Flink cluster " + CLUSTER_ID + " already exists.",
- ClusterDeploymentException.class,
- () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig));
+ assertThatThrownBy(
+ () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig))
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(ClusterDeploymentException.class)
+ .hasMessageContaining(
+ "The Flink cluster "
+ + CLUSTER_ID
+ + " already exists."));
}
@Test
- public void testDeployApplicationClusterWithDeploymentTargetNotCorrectlySet() {
+ void testDeployApplicationClusterWithDeploymentTargetNotCorrectlySet() {
flinkConfig.set(
PipelineOptions.JARS, Collections.singletonList("local:///path/of/user.jar"));
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.SESSION.getName());
- assertThrows(
- "Expected deployment.target=kubernetes-application",
- ClusterDeploymentException.class,
- () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig));
+ assertThatThrownBy(
+ () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig))
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(ClusterDeploymentException.class)
+ .hasMessageContaining(
+ "Expected deployment.target=kubernetes-application"));
}
@Test
- public void testDeployApplicationClusterWithMultipleJarsSet() {
+ void testDeployApplicationClusterWithMultipleJarsSet() {
flinkConfig.set(
PipelineOptions.JARS,
Arrays.asList("local:///path/of/user.jar", "local:///user2.jar"));
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.APPLICATION.getName());
- assertThrows(
- "Should only have one jar",
- IllegalArgumentException.class,
- () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig));
+ assertThatThrownBy(
+ () -> descriptor.deployApplicationCluster(clusterSpecification, appConfig))
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Should only have one jar"));
}
@Test
- public void testDeployApplicationClusterWithClusterIP() throws Exception {
+ void testDeployApplicationClusterWithClusterIP() throws Exception {
flinkConfig.set(
PipelineOptions.JARS, Collections.singletonList("local:///path/of/user.jar"));
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.APPLICATION.getName());
@@ -209,9 +219,8 @@ public class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
final String address = CLUSTER_ID + Constants.FLINK_REST_SERVICE_SUFFIX + "." + NAMESPACE;
final int port = flinkConfig.get(RestOptions.PORT);
- assertThat(
- clusterClient.getWebInterfaceURL(),
- is(String.format("http://%s:%d", address, port)));
+ assertThat(clusterClient.getWebInterfaceURL())
+ .isEqualTo(String.format("http://%s:%d", address, port));
}
private ClusterClientProvider<String> deploySessionCluster() throws ClusterDeploymentException {
@@ -220,44 +229,42 @@ public class KubernetesClusterDescriptorTest extends KubernetesClientTestBase {
}
private void checkClusterClient(ClusterClient<String> clusterClient) {
- assertEquals(CLUSTER_ID, clusterClient.getClusterId());
+ assertThat(clusterClient.getClusterId()).isEqualTo(CLUSTER_ID);
// Both HA and non-HA mode, the web interface should always be the Kubernetes exposed
// service address.
- assertEquals(
- String.format("http://%s:%d", MOCK_SERVICE_IP, REST_PORT),
- clusterClient.getWebInterfaceURL());
+ assertThat(clusterClient.getWebInterfaceURL())
+ .isEqualTo(String.format("http://%s:%d", MOCK_SERVICE_IP, REST_PORT));
}
private void checkUpdatedConfigAndResourceSetting() {
// Check updated flink config options
- assertEquals(
- String.valueOf(Constants.BLOB_SERVER_PORT),
- flinkConfig.getString(BlobServerOptions.PORT));
- assertEquals(
- String.valueOf(Constants.TASK_MANAGER_RPC_PORT),
- flinkConfig.getString(TaskManagerOptions.RPC_PORT));
- assertEquals(
- InternalServiceDecorator.getNamespacedInternalServiceName(CLUSTER_ID, NAMESPACE),
- flinkConfig.getString(JobManagerOptions.ADDRESS));
+ assertThat(flinkConfig.getString(BlobServerOptions.PORT))
+ .isEqualTo(String.valueOf(Constants.BLOB_SERVER_PORT));
+ assertThat(flinkConfig.getString(TaskManagerOptions.RPC_PORT))
+ .isEqualTo(String.valueOf(Constants.TASK_MANAGER_RPC_PORT));
+ assertThat(flinkConfig.getString(JobManagerOptions.ADDRESS))
+ .isEqualTo(
+ InternalServiceDecorator.getNamespacedInternalServiceName(
+ CLUSTER_ID, NAMESPACE));
final Deployment jmDeployment = kubeClient.apps().deployments().list().getItems().get(0);
final Container jmContainer =
jmDeployment.getSpec().getTemplate().getSpec().getContainers().get(0);
- assertEquals(
- String.valueOf(clusterSpecification.getMasterMemoryMB()),
- jmContainer
- .getResources()
- .getRequests()
- .get(Constants.RESOURCE_NAME_MEMORY)
- .getAmount());
- assertEquals(
- String.valueOf(clusterSpecification.getMasterMemoryMB()),
- jmContainer
- .getResources()
- .getLimits()
- .get(Constants.RESOURCE_NAME_MEMORY)
- .getAmount());
+ assertThat(
+ jmContainer
+ .getResources()
+ .getRequests()
+ .get(Constants.RESOURCE_NAME_MEMORY)
+ .getAmount())
+ .isEqualTo(String.valueOf(clusterSpecification.getMasterMemoryMB()));
+ assertThat(
+ jmContainer
+ .getResources()
+ .getLimits()
+ .get(Constants.RESOURCE_NAME_MEMORY)
+ .getAmount())
+ .isEqualTo(String.valueOf(clusterSpecification.getMasterMemoryMB()));
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesResource.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesExtension.java
similarity index 79%
rename from flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesResource.java
rename to flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesExtension.java
index 05c6dca3929..f50c03c1151 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesResource.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesExtension.java
@@ -22,18 +22,21 @@ import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
-import org.apache.flink.util.StringUtils;
-import org.junit.Assume;
+import org.junit.jupiter.api.extension.AfterAllCallback;
+import org.junit.jupiter.api.extension.BeforeAllCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.rules.ExternalResource;
+import static org.assertj.core.api.Assumptions.assumeThat;
+
/**
* {@link ExternalResource} which has a configured real Kubernetes cluster and client. We assume
* that one already has a running Kubernetes cluster. And all the ITCases assume that the
* environment ITCASE_KUBECONFIG is set with a valid kube config file. In the E2E tests, we will use
* a minikube for the testing.
*/
-public class KubernetesResource extends ExternalResource {
+public class KubernetesExtension implements BeforeAllCallback, AfterAllCallback {
private static final String CLUSTER_ID = "flink-itcase-cluster";
private static final int KUBERNETES_TRANSACTIONAL_OPERATION_MAX_RETRIES = 100;
@@ -44,16 +47,15 @@ public class KubernetesResource extends ExternalResource {
public static void checkEnv() {
final String kubeConfigEnv = System.getenv("ITCASE_KUBECONFIG");
- Assume.assumeTrue(
- "ITCASE_KUBECONFIG environment is not set.",
- !StringUtils.isNullOrWhitespaceOnly(kubeConfigEnv));
+ assumeThat(kubeConfigEnv)
+ .withFailMessage("ITCASE_KUBECONFIG environment is not set.")
+ .isNotBlank();
kubeConfigFile = kubeConfigEnv;
}
@Override
- public void before() {
+ public void beforeAll(ExtensionContext extensionContext) throws Exception {
checkEnv();
-
configuration = new Configuration();
configuration.set(KubernetesConfigOptions.KUBE_CONFIG_FILE, kubeConfigFile);
configuration.setString(KubernetesConfigOptions.CLUSTER_ID, CLUSTER_ID);
@@ -65,8 +67,10 @@ public class KubernetesResource extends ExternalResource {
}
@Override
- public void after() {
- flinkKubeClient.close();
+ public void afterAll(ExtensionContext extensionContext) throws Exception {
+ if (flinkKubeClient != null) {
+ flinkKubeClient.close();
+ }
}
public Configuration getConfiguration() {
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesPodTemplateTestUtils.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesPodTemplateTestUtils.java
index 38ea3c89e42..c1ffdb9f10e 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesPodTemplateTestUtils.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesPodTemplateTestUtils.java
@@ -31,10 +31,7 @@ import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* Utilities for the Kubernetes pod template tests. The create methods are to provide the init
@@ -53,7 +50,7 @@ public class KubernetesPodTemplateTestUtils {
KubernetesPodTemplateTestUtils.class
.getClassLoader()
.getResource(TESTING_TEMPLATE_FILE_NAME);
- assertThat(podTemplateUrl, not(nullValue()));
+ assertThat(podTemplateUrl).isNotNull();
return new File(podTemplateUrl.getPath());
}
@@ -120,7 +117,7 @@ public class KubernetesPodTemplateTestUtils {
podSpec.getContainers().stream()
.filter(e -> e.getName().equals(containerName))
.collect(Collectors.toList());
- assertThat(containers.size(), is(1));
+ assertThat(containers).hasSize(1);
return containers.get(0);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesResourceManagerDriverTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesResourceManagerDriverTest.java
index 6d09f903ca0..b8600a093e4 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesResourceManagerDriverTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesResourceManagerDriverTest.java
@@ -37,7 +37,7 @@ import org.apache.flink.runtime.testutils.CommonTestUtils;
import org.apache.flink.util.concurrent.FutureUtils;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collection;
@@ -47,14 +47,12 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.empty;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.fail;
/** Tests for {@link KubernetesResourceManagerDriver}. */
-public class KubernetesResourceManagerDriverTest
+class KubernetesResourceManagerDriverTest
extends ResourceManagerDriverTestBase<KubernetesWorkerNode> {
private static final String CLUSTER_ID = "testing-flink-cluster";
@@ -63,7 +61,7 @@ public class KubernetesResourceManagerDriverTest
new KubernetesResourceManagerDriverConfiguration(CLUSTER_ID, "localhost:9000");
@Test
- public void testOnPodAdded() throws Exception {
+ void testOnPodAdded() throws Exception {
new Context() {
{
final CompletableFuture<KubernetesPod> createPodFuture = new CompletableFuture<>();
@@ -99,9 +97,9 @@ public class KubernetesResourceManagerDriverTest
requestResourceFuture.thenAccept(
(workerNode) -> {
validateInMainThread();
- assertThat(
- workerNode.getResourceID().toString(),
- is(pod.getName()));
+ assertThat(workerNode.getResourceID())
+ .asString()
+ .isEqualTo(pod.getName());
});
// send onAdded event
@@ -115,7 +113,7 @@ public class KubernetesResourceManagerDriverTest
}
@Test
- public void testOnPodModified() throws Exception {
+ void testOnPodModified() throws Exception {
new Context() {
{
testOnPodTerminated((pod) -> getPodCallbackHandler().onModified(pod));
@@ -124,7 +122,7 @@ public class KubernetesResourceManagerDriverTest
}
@Test
- public void testOnPodDeleted() throws Exception {
+ void testOnPodDeleted() throws Exception {
new Context() {
{
testOnPodTerminated((pod) -> getPodCallbackHandler().onDeleted(pod));
@@ -133,7 +131,7 @@ public class KubernetesResourceManagerDriverTest
}
@Test
- public void testOnError() throws Exception {
+ void testOnError() throws Exception {
new Context() {
{
testOnPodTerminated((pod) -> getPodCallbackHandler().onError(pod));
@@ -142,7 +140,7 @@ public class KubernetesResourceManagerDriverTest
}
@Test
- public void testFatalHandleError() throws Exception {
+ void testFatalHandleError() throws Exception {
new Context() {
{
final CompletableFuture<Throwable> onErrorFuture = new CompletableFuture<>();
@@ -152,16 +150,15 @@ public class KubernetesResourceManagerDriverTest
() -> {
final Throwable testingError = new Throwable("testing error");
getPodCallbackHandler().handleError(testingError);
- assertThat(
- onErrorFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS),
- is(testingError));
+ assertThat(onErrorFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS))
+ .isEqualTo(testingError);
});
}
};
}
@Test
- public void testRecoverPreviousAttemptWorkersPodTerminated() throws Exception {
+ void testRecoverPreviousAttemptWorkersPodTerminated() throws Exception {
new Context() {
{
final KubernetesPod previousAttemptPod =
@@ -186,20 +183,17 @@ public class KubernetesResourceManagerDriverTest
() -> {
// validate the terminated pod from previous attempt is not recovered
// and is removed
- assertThat(
- recoveredWorkersFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS),
- empty());
- assertThat(
- stopPodFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS),
- is(previousAttemptPod.getName()));
+ assertThat(recoveredWorkersFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS))
+ .isEmpty();
+ assertThat(stopPodFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS))
+ .isEqualTo(previousAttemptPod.getName());
});
}
};
}
@Test
- public void testNewWatchCreationWhenKubernetesTooOldResourceVersionException()
- throws Exception {
+ void testNewWatchCreationWhenKubernetesTooOldResourceVersionException() throws Exception {
new Context() {
{
runTest(
@@ -210,28 +204,32 @@ public class KubernetesResourceManagerDriverTest
new Exception("too old resource version")));
// Verify the old watch is closed and a new one is created
CommonTestUtils.waitUntilCondition(() -> getPodsWatches().size() == 2);
- assertThat(getPodsWatches().get(0).isClosed(), is(true));
- assertThat(getPodsWatches().get(1).isClosed(), is(false));
+ assertThat(getPodsWatches().get(0).isClosed()).isTrue();
+ assertThat(getPodsWatches().get(1).isClosed()).isFalse();
});
}
};
}
- @Test(expected = ExpectedTestException.class)
+ @Test
public void testThrowExceptionWhenWatchPodsFailInInitializing() throws Exception {
new Context() {
{
- flinkKubeClientBuilder.setWatchPodsAndDoCallbackFunction(
- (ignore1, ignore2) -> {
- throw new ExpectedTestException();
- });
- runTest(() -> {});
+ assertThatThrownBy(
+ () -> {
+ flinkKubeClientBuilder.setWatchPodsAndDoCallbackFunction(
+ (ignore1, ignore2) -> {
+ throw new ExpectedTestException();
+ });
+ runTest(() -> {});
+ })
+ .isInstanceOf(ExpectedTestException.class);
}
};
}
@Test
- public void testThrowExceptionWhenWatchPodsFailInHandlingError() throws Exception {
+ void testThrowExceptionWhenWatchPodsFailInHandlingError() throws Exception {
new Context() {
{
final CompletableFuture<Throwable> onErrorFuture = new CompletableFuture<>();
@@ -251,9 +249,8 @@ public class KubernetesResourceManagerDriverTest
runTest(
() -> {
getPodCallbackHandler().handleError(testingError);
- assertThat(
- onErrorFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS),
- is(testingError));
+ assertThat(onErrorFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS))
+ .isEqualTo(testingError);
});
}
};
@@ -357,16 +354,16 @@ public class KubernetesResourceManagerDriverTest
@Override
protected void validateInitialization() throws Exception {
- assertNotNull(getPodCallbackHandler());
+ assertThat(getPodCallbackHandler()).isNotNull();
}
@Override
protected void validateWorkersRecoveredFromPreviousAttempt(
Collection<KubernetesWorkerNode> workers) {
- assertThat(workers.size(), is(1));
+ assertThat(workers).hasSize(1);
final ResourceID resourceId = workers.iterator().next().getResourceID();
- assertThat(resourceId.toString(), is(previousAttemptPod.getName()));
+ assertThat(resourceId).asString().isEqualTo(previousAttemptPod.getName());
}
@Override
@@ -376,14 +373,14 @@ public class KubernetesResourceManagerDriverTest
@Override
protected void validateDeregisterApplication() throws Exception {
- assertThat(
- stopAndCleanupClusterFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS), is(CLUSTER_ID));
+ assertThat(stopAndCleanupClusterFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS))
+ .isEqualTo(CLUSTER_ID);
}
@Override
protected void validateRequestedResources(
Collection<TaskExecutorProcessSpec> taskExecutorProcessSpecs) throws Exception {
- assertThat(taskExecutorProcessSpecs.size(), is(1));
+ assertThat(taskExecutorProcessSpecs).hasSize(1);
final TaskExecutorProcessSpec taskExecutorProcessSpec =
taskExecutorProcessSpecs.iterator().next();
@@ -392,51 +389,58 @@ public class KubernetesResourceManagerDriverTest
pod.getInternalResource().getSpec().getContainers().get(0).getResources();
assertThat(
- resourceRequirements
- .getRequests()
- .get(Constants.RESOURCE_NAME_MEMORY)
- .getAmount(),
- is(
+ resourceRequirements
+ .getRequests()
+ .get(Constants.RESOURCE_NAME_MEMORY)
+ .getAmount())
+ .isEqualTo(
String.valueOf(
taskExecutorProcessSpec
.getTotalProcessMemorySize()
- .getMebiBytes())));
+ .getMebiBytes()));
assertThat(
- resourceRequirements.getRequests().get(Constants.RESOURCE_NAME_CPU).getAmount(),
- is(
+ resourceRequirements
+ .getRequests()
+ .get(Constants.RESOURCE_NAME_CPU)
+ .getAmount())
+ .isEqualTo(
String.valueOf(
taskExecutorProcessSpec
.getCpuCores()
.getValue()
- .doubleValue())));
+ .doubleValue()));
assertThat(
- resourceRequirements
- .getLimits()
- .get(Constants.RESOURCE_NAME_MEMORY)
- .getAmount(),
- is(
+ resourceRequirements
+ .getLimits()
+ .get(Constants.RESOURCE_NAME_MEMORY)
+ .getAmount())
+ .isEqualTo(
String.valueOf(
taskExecutorProcessSpec
.getTotalProcessMemorySize()
- .getMebiBytes())));
+ .getMebiBytes()));
assertThat(
- resourceRequirements.getLimits().get(Constants.RESOURCE_NAME_CPU).getAmount(),
- is(
+ resourceRequirements
+ .getLimits()
+ .get(Constants.RESOURCE_NAME_CPU)
+ .getAmount())
+ .isEqualTo(
String.valueOf(
taskExecutorProcessSpec
.getCpuCores()
.getValue()
- .doubleValue())));
+ .doubleValue()));
}
@Override
protected void validateReleaseResources(Collection<KubernetesWorkerNode> workerNodes)
throws Exception {
- assertThat(workerNodes.size(), is(1));
+ assertThat(workerNodes).hasSize(1);
final ResourceID resourceId = workerNodes.iterator().next().getResourceID();
- assertThat(stopPodFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS), is(resourceId.toString()));
+ assertThat(stopPodFuture.get(TIMEOUT_SEC, TimeUnit.SECONDS))
+ .isEqualTo(resourceId.toString());
}
void testOnPodTerminated(Consumer<List<KubernetesPod>> sendPodTerminatedEvent)
@@ -467,13 +471,14 @@ public class KubernetesResourceManagerDriverTest
CompletableFuture.allOf(
stopPodFuture.thenAccept(
(podname) ->
- assertThat(podname, is(pod.getName()))),
+ assertThat(podname)
+ .isEqualTo(pod.getName())),
onWorkerTerminatedConsumer.thenAccept(
(resourceId) -> {
validateInMainThread();
- assertThat(
- resourceId.toString(),
- is(pod.getName()));
+ assertThat(resourceId)
+ .asString()
+ .isEqualTo(pod.getName());
}));
sendPodTerminatedEvent.accept(
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesTestBase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesTestBase.java
index d5aa7c3d99c..857ae39b1b8 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesTestBase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesTestBase.java
@@ -28,19 +28,13 @@ import org.apache.flink.kubernetes.kubeclient.Fabric8FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.runtime.clusterframework.BootstrapTools;
-import org.apache.flink.util.TestLogger;
import org.apache.flink.util.concurrent.Executors;
-import io.fabric8.kubernetes.api.model.Config;
-import io.fabric8.kubernetes.api.model.ConfigBuilder;
-import io.fabric8.kubernetes.api.model.NamedClusterBuilder;
-import io.fabric8.kubernetes.api.model.NamedContextBuilder;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
-import io.fabric8.kubernetes.client.utils.Serialization;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.extension.RegisterExtension;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
@@ -48,7 +42,10 @@ import java.util.HashMap;
import java.util.Map;
/** Base test class for Kubernetes. */
-public class KubernetesTestBase extends TestLogger {
+public class KubernetesTestBase {
+ @RegisterExtension
+ protected final MixedKubernetesServerExtension server =
+ new MixedKubernetesServerExtension(true, true);
protected static final String NAMESPACE = "test";
protected static final String CLUSTER_ID = "my-flink-cluster1";
@@ -59,10 +56,6 @@ public class KubernetesTestBase extends TestLogger {
KubernetesConfigOptions.ImagePullPolicy.IfNotPresent;
protected static final int JOB_MANAGER_MEMORY = 768;
- @Rule public MixedKubernetesServer server = new MixedKubernetesServer(true, true);
-
- @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
protected File flinkConfDir;
protected File hadoopConfDir;
@@ -88,11 +81,12 @@ public class KubernetesTestBase extends TestLogger {
protected void onSetup() throws Exception {}
- @Before
- public final void setup() throws Exception {
- flinkConfDir = temporaryFolder.newFolder().getAbsoluteFile();
- hadoopConfDir = temporaryFolder.newFolder().getAbsoluteFile();
- kerberosDir = temporaryFolder.newFolder().getAbsoluteFile();
+ @BeforeEach
+ void setup(@TempDir File flinkConfDir, @TempDir File hadoopConfDir, @TempDir File kerberosDir)
+ throws Exception {
+ this.flinkConfDir = flinkConfDir.getAbsoluteFile();
+ this.hadoopConfDir = hadoopConfDir.getAbsoluteFile();
+ this.kerberosDir = kerberosDir.getAbsoluteFile();
setupFlinkConfig();
writeFlinkConfiguration();
@@ -105,8 +99,8 @@ public class KubernetesTestBase extends TestLogger {
onSetup();
}
- @After
- public void tearDown() throws Exception {
+ @AfterEach
+ void tearDown() throws Exception {
flinkKubeClient.close();
}
@@ -137,32 +131,4 @@ public class KubernetesTestBase extends TestLogger {
KubernetesTestUtils.createTemporyFile("some keytab", kerberosDir, KEYTAB_FILE);
KubernetesTestUtils.createTemporyFile("some conf", kerberosDir, KRB5_CONF_FILE);
}
-
- protected String writeKubeConfigForMockKubernetesServer() throws Exception {
- final Config kubeConfig =
- new ConfigBuilder()
- .withApiVersion(server.getClient().getApiVersion())
- .withClusters(
- new NamedClusterBuilder()
- .withName(CLUSTER_ID)
- .withNewCluster()
- .withNewServer(server.getClient().getMasterUrl().toString())
- .withInsecureSkipTlsVerify(true)
- .endCluster()
- .build())
- .withContexts(
- new NamedContextBuilder()
- .withName(CLUSTER_ID)
- .withNewContext()
- .withCluster(CLUSTER_ID)
- .withUser(
- server.getClient().getConfiguration().getUsername())
- .endContext()
- .build())
- .withNewCurrentContext(CLUSTER_ID)
- .build();
- final File kubeConfigFile = new File(temporaryFolder.newFolder(".kube"), "config");
- Serialization.yamlMapper().writeValue(kubeConfigFile, kubeConfig);
- return kubeConfigFile.getAbsolutePath();
- }
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesWorkerNodeTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesWorkerNodeTest.java
index 9d6de54428e..6ad6c0f032e 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesWorkerNodeTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/KubernetesWorkerNodeTest.java
@@ -19,30 +19,27 @@
package org.apache.flink.kubernetes;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
-import org.apache.flink.util.TestLogger;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
-/** Tests for {@link KubernetesWorkerNode}. */
-public class KubernetesWorkerNodeTest extends TestLogger {
-
- @Rule public final ExpectedException exception = ExpectedException.none();
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+/** Tests for {@link KubernetesWorkerNode}. */
+class KubernetesWorkerNodeTest {
@Test
public void testGetAttemptFromWorkerNode() throws Exception {
final String correctPodName = "flink-on-kubernetes-taskmanager-11-5";
final KubernetesWorkerNode workerNode =
new KubernetesWorkerNode(new ResourceID(correctPodName));
- Assert.assertEquals(11L, workerNode.getAttempt());
+ assertThat(workerNode.getAttempt()).isEqualTo(11L);
final String wrongPodName = "flink-on-kubernetes-xxxtaskmanager-11-5";
final KubernetesWorkerNode workerNode1 =
new KubernetesWorkerNode(new ResourceID(wrongPodName));
- exception.expect(Exception.class);
- exception.expectMessage("Error to parse KubernetesWorkerNode from " + wrongPodName + ".");
- workerNode1.getAttempt();
+ assertThatThrownBy(() -> workerNode1.getAttempt())
+ .isInstanceOf(Exception.class)
+ .hasMessageContaining(
+ "Error to parse KubernetesWorkerNode from " + wrongPodName + ".");
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/MixedKubernetesServer.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/MixedKubernetesServerExtension.java
similarity index 83%
rename from flink-kubernetes/src/test/java/org/apache/flink/kubernetes/MixedKubernetesServer.java
rename to flink-kubernetes/src/test/java/org/apache/flink/kubernetes/MixedKubernetesServerExtension.java
index c5745632610..1c68160dbaa 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/MixedKubernetesServer.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/MixedKubernetesServerExtension.java
@@ -26,14 +26,16 @@ import io.fabric8.mockwebserver.ServerResponse;
import io.fabric8.mockwebserver.dsl.MockServerExpectation;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
-import org.junit.rules.ExternalResource;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
import java.util.HashMap;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
/** The mock server that host MixedDispatcher. */
-public class MixedKubernetesServer extends ExternalResource {
+public class MixedKubernetesServerExtension implements BeforeEachCallback, AfterEachCallback {
private KubernetesMockServer mock;
private NamespacedKubernetesClient client;
@@ -43,13 +45,14 @@ public class MixedKubernetesServer extends ExternalResource {
private final MockWebServer mockWebServer;
- public MixedKubernetesServer(boolean https, boolean crudMode) {
+ public MixedKubernetesServerExtension(boolean https, boolean crudMode) {
this.https = https;
this.crudMode = crudMode;
mockWebServer = new MockWebServer();
}
- public void before() {
+ @Override
+ public void beforeEach(ExtensionContext extensionContext) throws Exception {
final HashMap<ServerRequest, Queue<ServerResponse>> response = new HashMap<>();
mock =
crudMode
@@ -64,7 +67,8 @@ public class MixedKubernetesServer extends ExternalResource {
client = mock.createClient();
}
- public void after() {
+ @Override
+ public void afterEach(ExtensionContext extensionContext) throws Exception {
mock.destroy();
client.close();
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/cli/KubernetesSessionCliTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/cli/KubernetesSessionCliTest.java
index 7ebec9187a9..f9242927607 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/cli/KubernetesSessionCliTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/cli/KubernetesSessionCliTest.java
@@ -32,40 +32,39 @@ import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.executors.KubernetesSessionClusterExecutor;
-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.nio.file.Path;
import java.util.Map;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.entry;
/** Tests for the {@link KubernetesSessionCli}. */
-public class KubernetesSessionCliTest {
+class KubernetesSessionCliTest {
- @Rule public TemporaryFolder tmp = new TemporaryFolder();
+ @TempDir public Path confDirPath;
@Test
- public void testKubernetesSessionCliSetsDeploymentTargetCorrectly() throws CliArgsException {
+ void testKubernetesSessionCliSetsDeploymentTargetCorrectly() throws CliArgsException {
final KubernetesSessionCli cli =
- new KubernetesSessionCli(new Configuration(), tmp.getRoot().getAbsolutePath());
+ new KubernetesSessionCli(
+ new Configuration(), confDirPath.toAbsolutePath().toString());
final String[] args = {};
final Configuration configuration = cli.getEffectiveConfiguration(args);
- assertEquals(
- KubernetesSessionClusterExecutor.NAME, configuration.get(DeploymentOptions.TARGET));
+ assertThat(KubernetesSessionClusterExecutor.NAME)
+ .isEqualTo(configuration.get(DeploymentOptions.TARGET));
}
@Test
- public void testDynamicProperties() throws Exception {
+ void testDynamicProperties() throws Exception {
final KubernetesSessionCli cli =
- new KubernetesSessionCli(new Configuration(), tmp.getRoot().getAbsolutePath());
+ new KubernetesSessionCli(
+ new Configuration(), confDirPath.toAbsolutePath().toString());
final String[] args =
new String[] {
"-e",
@@ -77,20 +76,21 @@ public class KubernetesSessionCliTest {
final Configuration executorConfig = cli.getEffectiveConfiguration(args);
final ClusterClientFactory<String> clientFactory = getClusterClientFactory(executorConfig);
- Assert.assertNotNull(clientFactory);
+ assertThat(clientFactory).isNotNull();
final Map<String, String> executorConfigMap = executorConfig.toMap();
- assertEquals(4, executorConfigMap.size());
- assertEquals("5 min", executorConfigMap.get("akka.ask.timeout"));
- assertEquals("-DappName=foobar", executorConfigMap.get("env.java.opts"));
- assertEquals(
- tmp.getRoot().getAbsolutePath(),
- executorConfig.get(DeploymentOptionsInternal.CONF_DIR));
- assertTrue(executorConfigMap.containsKey(DeploymentOptions.TARGET.key()));
+ assertThat(executorConfigMap).hasSize(4);
+ assertThat(executorConfigMap)
+ .contains(
+ entry("akka.ask.timeout", "5 min"),
+ entry("env.java.opts", "-DappName=foobar"));
+ assertThat(executorConfig.get(DeploymentOptionsInternal.CONF_DIR))
+ .isEqualTo(confDirPath.toAbsolutePath().toString());
+ assertThat(executorConfigMap).containsKey(DeploymentOptions.TARGET.key());
}
@Test
- public void testCorrectSettingOfMaxSlots() throws Exception {
+ void testCorrectSettingOfMaxSlots() throws Exception {
final String[] params =
new String[] {
"-e",
@@ -107,11 +107,11 @@ public class KubernetesSessionCliTest {
// each task manager has 3 slots but the parallelism is 7. Thus the slots should be
// increased.
- assertEquals(3, clusterSpecification.getSlotsPerTaskManager());
+ assertThat(clusterSpecification.getSlotsPerTaskManager()).isEqualTo(3);
}
@Test
- public void testResumeFromKubernetesID() throws Exception {
+ void testResumeFromKubernetesID() throws Exception {
final KubernetesSessionCli cli = createFlinkKubernetesCustomCliWithJmAndTmTotalMemory(1024);
final String clusterId = "my-test-CLUSTER_ID";
@@ -125,7 +125,7 @@ public class KubernetesSessionCliTest {
final Configuration executorConfig = cli.getEffectiveConfiguration(args);
final ClusterClientFactory clientFactory = getClusterClientFactory(executorConfig);
- assertEquals(clusterId, clientFactory.getClusterId(executorConfig));
+ assertThat(clientFactory.getClusterId(executorConfig)).isEqualTo(clusterId);
}
/**
@@ -133,7 +133,7 @@ public class KubernetesSessionCliTest {
* ClusterSpecification} is created.
*/
@Test
- public void testCommandLineClusterSpecification() throws Exception {
+ void testCommandLineClusterSpecification() throws Exception {
final Configuration configuration = new Configuration();
final int jobManagerMemory = 1337;
final int taskManagerMemory = 7331;
@@ -154,23 +154,23 @@ public class KubernetesSessionCliTest {
};
final KubernetesSessionCli cli =
- new KubernetesSessionCli(configuration, tmp.getRoot().getAbsolutePath());
+ new KubernetesSessionCli(configuration, confDirPath.toAbsolutePath().toString());
Configuration executorConfig = cli.getEffectiveConfiguration(args);
ClusterClientFactory<String> clientFactory = getClusterClientFactory(executorConfig);
ClusterSpecification clusterSpecification =
clientFactory.getClusterSpecification(executorConfig);
- assertThat(clusterSpecification.getMasterMemoryMB(), is(jobManagerMemory));
- assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(taskManagerMemory));
- assertThat(clusterSpecification.getSlotsPerTaskManager(), is(slotsPerTaskManager));
+ assertThat(clusterSpecification.getMasterMemoryMB()).isEqualTo(jobManagerMemory);
+ assertThat(clusterSpecification.getTaskManagerMemoryMB()).isEqualTo(taskManagerMemory);
+ assertThat(clusterSpecification.getSlotsPerTaskManager()).isEqualTo(slotsPerTaskManager);
}
/**
* Tests that the configuration settings are used to create the {@link ClusterSpecification}.
*/
@Test
- public void testConfigurationClusterSpecification() throws Exception {
+ void testConfigurationClusterSpecification() throws Exception {
final Configuration configuration = new Configuration();
final int jobManagerMemory = 1337;
configuration.set(
@@ -183,21 +183,21 @@ public class KubernetesSessionCliTest {
final String[] args = {"-e", KubernetesSessionClusterExecutor.NAME};
final KubernetesSessionCli cli =
- new KubernetesSessionCli(configuration, tmp.getRoot().getAbsolutePath());
+ new KubernetesSessionCli(configuration, confDirPath.toAbsolutePath().toString());
Configuration executorConfig = cli.getEffectiveConfiguration(args);
ClusterClientFactory<String> clientFactory = getClusterClientFactory(executorConfig);
ClusterSpecification clusterSpecification =
clientFactory.getClusterSpecification(executorConfig);
- assertThat(clusterSpecification.getMasterMemoryMB(), is(jobManagerMemory));
- assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(taskManagerMemory));
- assertThat(clusterSpecification.getSlotsPerTaskManager(), is(slotsPerTaskManager));
+ assertThat(clusterSpecification.getMasterMemoryMB()).isEqualTo(jobManagerMemory);
+ assertThat(clusterSpecification.getTaskManagerMemoryMB()).isEqualTo(taskManagerMemory);
+ assertThat(clusterSpecification.getSlotsPerTaskManager()).isEqualTo(slotsPerTaskManager);
}
/** Tests the specifying heap memory with unit (MB) for job manager and task manager. */
@Test
- public void testHeapMemoryPropertyWithUnitMB() throws Exception {
+ void testHeapMemoryPropertyWithUnitMB() throws Exception {
final String[] args =
new String[] {
"-e",
@@ -213,13 +213,13 @@ public class KubernetesSessionCliTest {
final ClusterSpecification clusterSpecification =
clientFactory.getClusterSpecification(executorConfig);
- assertThat(clusterSpecification.getMasterMemoryMB(), is(1024));
- assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(2048));
+ assertThat(clusterSpecification.getMasterMemoryMB()).isEqualTo(1024);
+ assertThat(clusterSpecification.getTaskManagerMemoryMB()).isEqualTo(2048);
}
/** Tests the specifying heap memory with arbitrary unit for job manager and task manager. */
@Test
- public void testHeapMemoryPropertyWithArbitraryUnit() throws Exception {
+ void testHeapMemoryPropertyWithArbitraryUnit() throws Exception {
final String[] args =
new String[] {
"-e",
@@ -235,35 +235,35 @@ public class KubernetesSessionCliTest {
final ClusterSpecification clusterSpecification =
clientFactory.getClusterSpecification(executorConfig);
- assertThat(clusterSpecification.getMasterMemoryMB(), is(1024));
- assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(3072));
+ assertThat(clusterSpecification.getMasterMemoryMB()).isEqualTo(1024);
+ assertThat(clusterSpecification.getTaskManagerMemoryMB()).isEqualTo(3072);
}
/** Tests the specifying heap memory with old config key for job manager and task manager. */
@Test
- public void testHeapMemoryPropertyWithOldConfigKey() throws Exception {
+ void testHeapMemoryPropertyWithOldConfigKey() throws Exception {
Configuration configuration = new Configuration();
configuration.set(DeploymentOptions.TARGET, KubernetesSessionClusterExecutor.NAME);
configuration.setInteger(JobManagerOptions.JOB_MANAGER_HEAP_MEMORY_MB, 2048);
configuration.setInteger(TaskManagerOptions.TASK_MANAGER_HEAP_MEMORY_MB, 4096);
final KubernetesSessionCli cli =
- new KubernetesSessionCli(configuration, tmp.getRoot().getAbsolutePath());
+ new KubernetesSessionCli(configuration, confDirPath.toAbsolutePath().toString());
final Configuration executorConfig = cli.getEffectiveConfiguration(new String[] {});
final ClusterClientFactory<String> clientFactory = getClusterClientFactory(executorConfig);
final ClusterSpecification clusterSpecification =
clientFactory.getClusterSpecification(executorConfig);
- assertThat(clusterSpecification.getMasterMemoryMB(), is(2048));
- assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(4096));
+ assertThat(clusterSpecification.getMasterMemoryMB()).isEqualTo(2048);
+ assertThat(clusterSpecification.getTaskManagerMemoryMB()).isEqualTo(4096);
}
/**
* Tests the specifying heap memory with config default value for job manager and task manager.
*/
@Test
- public void testHeapMemoryPropertyWithConfigDefaultValue() throws Exception {
+ void testHeapMemoryPropertyWithConfigDefaultValue() throws Exception {
final String[] args = new String[] {"-e", KubernetesSessionClusterExecutor.NAME};
final KubernetesSessionCli cli = createFlinkKubernetesCustomCliWithJmAndTmTotalMemory(1024);
@@ -273,8 +273,8 @@ public class KubernetesSessionCliTest {
final ClusterSpecification clusterSpecification =
clientFactory.getClusterSpecification(executorConfig);
- assertThat(clusterSpecification.getMasterMemoryMB(), is(1024));
- assertThat(clusterSpecification.getTaskManagerMemoryMB(), is(1024));
+ assertThat(clusterSpecification.getMasterMemoryMB()).isEqualTo(1024);
+ assertThat(clusterSpecification.getTaskManagerMemoryMB()).isEqualTo(1024);
}
private ClusterClientFactory<String> getClusterClientFactory(
@@ -291,6 +291,6 @@ public class KubernetesSessionCliTest {
JobManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(totalMemory));
configuration.set(
TaskManagerOptions.TOTAL_PROCESS_MEMORY, MemorySize.ofMebiBytes(totalMemory));
- return new KubernetesSessionCli(configuration, tmp.getRoot().getAbsolutePath());
+ return new KubernetesSessionCli(configuration, confDirPath.toAbsolutePath().toString());
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/configuration/KubernetesDeploymentTargetTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/configuration/KubernetesDeploymentTargetTest.java
index c7e5cf2f4b6..0d71573654f 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/configuration/KubernetesDeploymentTargetTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/configuration/KubernetesDeploymentTargetTest.java
@@ -21,43 +21,45 @@ package org.apache.flink.kubernetes.configuration;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.DeploymentOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for the {@link KubernetesDeploymentTarget}. */
-public class KubernetesDeploymentTargetTest {
+class KubernetesDeploymentTargetTest {
@Test
- public void testCorrectInstantiationFromConfiguration() {
+ void testCorrectInstantiationFromConfiguration() {
for (KubernetesDeploymentTarget t : KubernetesDeploymentTarget.values()) {
testCorrectInstantiationFromConfigurationHelper(t);
}
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testInvalidInstantiationFromConfiguration() {
final Configuration configuration = getConfigurationWithTarget("invalid-target");
- KubernetesDeploymentTarget.fromConfig(configuration);
+ assertThatThrownBy(() -> KubernetesDeploymentTarget.fromConfig(configuration))
+ .isInstanceOf(IllegalArgumentException.class);
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testNullInstantiationFromConfiguration() {
- KubernetesDeploymentTarget.fromConfig(new Configuration());
+ assertThatThrownBy(() -> KubernetesDeploymentTarget.fromConfig(new Configuration()))
+ .isInstanceOf(IllegalArgumentException.class);
}
@Test
- public void testThatAValidOptionIsValid() {
- assertTrue(
- KubernetesDeploymentTarget.isValidKubernetesTarget(
- KubernetesDeploymentTarget.APPLICATION.getName()));
+ void testThatAValidOptionIsValid() {
+ assertThat(
+ KubernetesDeploymentTarget.isValidKubernetesTarget(
+ KubernetesDeploymentTarget.APPLICATION.getName()))
+ .isTrue();
}
@Test
- public void testThatAnInvalidOptionIsInvalid() {
- assertFalse(KubernetesDeploymentTarget.isValidKubernetesTarget("invalid-target"));
+ void testThatAnInvalidOptionIsInvalid() {
+ assertThat(KubernetesDeploymentTarget.isValidKubernetesTarget("invalid-target")).isFalse();
}
private void testCorrectInstantiationFromConfigurationHelper(
@@ -67,7 +69,7 @@ public class KubernetesDeploymentTargetTest {
final KubernetesDeploymentTarget actualDeploymentTarget =
KubernetesDeploymentTarget.fromConfig(configuration);
- assertSame(actualDeploymentTarget, expectedDeploymentTarget);
+ assertThat(expectedDeploymentTarget).isSameAs(actualDeploymentTarget);
}
private Configuration getConfigurationWithTarget(final String target) {
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/entrypoint/KubernetesWorkerResourceSpecFactoryTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/entrypoint/KubernetesWorkerResourceSpecFactoryTest.java
index bc204a140aa..79583ff9ea1 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/entrypoint/KubernetesWorkerResourceSpecFactoryTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/entrypoint/KubernetesWorkerResourceSpecFactoryTest.java
@@ -22,48 +22,43 @@ import org.apache.flink.api.common.resources.CPUResource;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.TaskManagerOptions;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
-import org.apache.flink.util.TestLogger;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for {@link KubernetesWorkerResourceSpecFactory}. */
-public class KubernetesWorkerResourceSpecFactoryTest extends TestLogger {
+class KubernetesWorkerResourceSpecFactoryTest {
@Test
- public void testGetCpuCoresCommonOption() {
+ void testGetCpuCoresCommonOption() {
final Configuration configuration = new Configuration();
configuration.setDouble(TaskManagerOptions.CPU_CORES, 1.0);
configuration.setDouble(KubernetesConfigOptions.TASK_MANAGER_CPU, 2.0);
configuration.setDouble(KubernetesConfigOptions.TASK_MANAGER_CPU_LIMIT_FACTOR, 1.5);
configuration.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 3);
- assertThat(
- KubernetesWorkerResourceSpecFactory.getDefaultCpus(configuration),
- is(new CPUResource(1.0)));
+ assertThat(KubernetesWorkerResourceSpecFactory.getDefaultCpus(configuration))
+ .isEqualTo(new CPUResource(1.0));
}
@Test
- public void testGetCpuCoresKubernetesOption() {
+ void testGetCpuCoresKubernetesOption() {
final Configuration configuration = new Configuration();
configuration.setDouble(KubernetesConfigOptions.TASK_MANAGER_CPU, 2.0);
configuration.setDouble(KubernetesConfigOptions.TASK_MANAGER_CPU_LIMIT_FACTOR, 1.5);
configuration.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 3);
- assertThat(
- KubernetesWorkerResourceSpecFactory.getDefaultCpus(configuration),
- is(new CPUResource(2.0)));
+ assertThat(KubernetesWorkerResourceSpecFactory.getDefaultCpus(configuration))
+ .isEqualTo(new CPUResource(2.0));
}
@Test
- public void testGetCpuCoresNumSlots() {
+ void testGetCpuCoresNumSlots() {
final Configuration configuration = new Configuration();
configuration.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 3);
- assertThat(
- KubernetesWorkerResourceSpecFactory.getDefaultCpus(configuration),
- is(new CPUResource(3.0)));
+ assertThat(KubernetesWorkerResourceSpecFactory.getDefaultCpus(configuration))
+ .isEqualTo(new CPUResource(3.0));
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesCheckpointIDCounterTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesCheckpointIDCounterTest.java
index f599e5c30d8..9e206353e17 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesCheckpointIDCounterTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesCheckpointIDCounterTest.java
@@ -19,25 +19,23 @@
package org.apache.flink.kubernetes.highavailability;
import org.apache.flink.api.common.JobStatus;
-import org.apache.flink.core.testutils.FlinkMatchers;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesLeaderElector;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.kubernetes.utils.KubernetesUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CompletionException;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.fail;
+import static org.apache.flink.core.testutils.FlinkAssertions.anyCauseMatches;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link KubernetesCheckpointIDCounter} operations. */
-public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilityTestBase {
+class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilityTestBase {
@Test
- public void testGetAndIncrement() throws Exception {
+ void testGetAndIncrement() throws Exception {
new Context() {
{
runTest(
@@ -49,15 +47,15 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
flinkKubeClient, LEADER_CONFIGMAP_NAME, LOCK_IDENTITY);
checkpointIDCounter.setCount(100L);
final long counter = checkpointIDCounter.getAndIncrement();
- assertThat(counter, is(100L));
- assertThat(checkpointIDCounter.get(), is(101L));
+ assertThat(counter).isEqualTo(100L);
+ assertThat(checkpointIDCounter.get()).isEqualTo(101L);
});
}
};
}
@Test
- public void testShutdown() throws Exception {
+ void testShutdown() throws Exception {
new Context() {
{
runTest(
@@ -71,26 +69,20 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
checkpointIDCounter.setCount(100L);
- assertThat(
- getLeaderConfigMap()
- .getData()
- .get(Constants.CHECKPOINT_COUNTER_KEY),
- is("100"));
+ assertThat(getLeaderConfigMap().getData())
+ .containsEntry(Constants.CHECKPOINT_COUNTER_KEY, "100");
checkpointIDCounter.shutdown(JobStatus.FINISHED).join();
- assertThat(
- getLeaderConfigMap()
- .getData()
- .containsKey(Constants.CHECKPOINT_COUNTER_KEY),
- is(false));
+ assertThat(getLeaderConfigMap().getData())
+ .doesNotContainKey(Constants.CHECKPOINT_COUNTER_KEY);
});
}
};
}
@Test
- public void testShutdownForLocallyTerminatedJobStatus() throws Exception {
+ void testShutdownForLocallyTerminatedJobStatus() throws Exception {
new Context() {
{
runTest(
@@ -104,26 +96,20 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
checkpointIDCounter.setCount(100L);
- assertThat(
- getLeaderConfigMap()
- .getData()
- .get(Constants.CHECKPOINT_COUNTER_KEY),
- is("100"));
+ assertThat(getLeaderConfigMap().getData())
+ .containsEntry(Constants.CHECKPOINT_COUNTER_KEY, "100");
checkpointIDCounter.shutdown(JobStatus.SUSPENDED).join();
- assertThat(
- getLeaderConfigMap()
- .getData()
- .containsKey(Constants.CHECKPOINT_COUNTER_KEY),
- is(true));
+ assertThat(getLeaderConfigMap().getData())
+ .containsKey(Constants.CHECKPOINT_COUNTER_KEY);
});
}
};
}
@Test
- public void testIdempotentShutdown() throws Exception {
+ void testIdempotentShutdown() throws Exception {
new Context() {
{
runTest(
@@ -135,19 +121,13 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
flinkKubeClient, LEADER_CONFIGMAP_NAME, LOCK_IDENTITY);
checkpointIDCounter.start();
- assertThat(
- getLeaderConfigMap()
- .getData()
- .containsKey(Constants.CHECKPOINT_COUNTER_KEY),
- is(false));
+ assertThat(getLeaderConfigMap().getData())
+ .doesNotContainKey(Constants.CHECKPOINT_COUNTER_KEY);
checkpointIDCounter.shutdown(JobStatus.FINISHED).join();
- assertThat(
- getLeaderConfigMap()
- .getData()
- .containsKey(Constants.CHECKPOINT_COUNTER_KEY),
- is(false));
+ assertThat(getLeaderConfigMap().getData())
+ .doesNotContainKey(Constants.CHECKPOINT_COUNTER_KEY);
// a second shutdown should work without causing any errors
checkpointIDCounter.shutdown(JobStatus.FINISHED).join();
@@ -157,7 +137,7 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
}
@Test
- public void testShutdownFailureDueToMissingConfigMap() throws Exception {
+ void testShutdownFailureDueToMissingConfigMap() throws Exception {
new Context() {
{
runTest(
@@ -174,10 +154,12 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
// ConfigMap) causes an unexpected failure which we want to simulate
// here
flinkKubeClient.deleteConfigMap(LEADER_CONFIGMAP_NAME);
-
- assertThrows(
- CompletionException.class,
- () -> checkpointIDCounter.shutdown(JobStatus.FINISHED).get());
+ assertThatThrownBy(
+ () ->
+ checkpointIDCounter
+ .shutdown(JobStatus.FINISHED)
+ .get())
+ .satisfies(anyCauseMatches(CompletionException.class));
// fixing the internal issue should make the shutdown succeed again
KubernetesUtils.createConfigMapIfItDoesNotExist(
@@ -189,7 +171,7 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
}
@Test
- public void testGetAndIncrementWithNoLeadership() throws Exception {
+ void testGetAndIncrementWithNoLeadership() throws Exception {
new Context() {
{
runTest(
@@ -208,25 +190,22 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
.getAnnotations()
.remove(KubernetesLeaderElector.LEADER_ANNOTATION_KEY);
- try {
- checkpointIDCounter.getAndIncrement();
- fail(
- "We should get an exception when trying to GetAndIncrement no leadership.");
- } catch (Exception ex) {
- final String errMsg =
- "Failed to update ConfigMap "
- + LEADER_CONFIGMAP_NAME
- + " since "
- + "current KubernetesCheckpointIDCounter does not have the leadership.";
- assertThat(ex, FlinkMatchers.containsMessage(errMsg));
- }
+ final String errMsg =
+ "Failed to update ConfigMap "
+ + LEADER_CONFIGMAP_NAME
+ + " since "
+ + "current KubernetesCheckpointIDCounter does not have the leadership.";
+ assertThatThrownBy(
+ () -> checkpointIDCounter.getAndIncrement(),
+ "We should get an exception when trying to GetAndIncrement no leadership.")
+ .satisfies(anyCauseMatches(errMsg));
});
}
};
}
@Test
- public void testSetAndGet() throws Exception {
+ void testSetAndGet() throws Exception {
new Context() {
{
runTest(
@@ -238,14 +217,14 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
flinkKubeClient, LEADER_CONFIGMAP_NAME, LOCK_IDENTITY);
checkpointIDCounter.setCount(100L);
final long counter = checkpointIDCounter.get();
- assertThat(counter, is(100L));
+ assertThat(counter).isEqualTo(100L);
});
}
};
}
@Test
- public void testGetWhenConfigMapNotExist() throws Exception {
+ void testGetWhenConfigMapNotExist() throws Exception {
new Context() {
{
runTest(
@@ -253,23 +232,20 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
final KubernetesCheckpointIDCounter checkpointIDCounter =
new KubernetesCheckpointIDCounter(
flinkKubeClient, LEADER_CONFIGMAP_NAME, LOCK_IDENTITY);
- try {
- checkpointIDCounter.get();
- fail(
- "We should get an exception when trying to get checkpoint id counter but "
- + "ConfigMap does not exist.");
- } catch (Exception ex) {
- final String errMsg =
- "ConfigMap " + LEADER_CONFIGMAP_NAME + " does not exist.";
- assertThat(ex, FlinkMatchers.containsMessage(errMsg));
- }
+
+ final String errMsg =
+ "ConfigMap " + LEADER_CONFIGMAP_NAME + " does not exist.";
+ assertThatThrownBy(
+ () -> checkpointIDCounter.get(),
+ "We should get an exception when trying to get checkpoint id counter but ConfigMap does not exist.")
+ .satisfies(anyCauseMatches(errMsg));
});
}
};
}
@Test
- public void testSetWithNoLeadershipShouldNotBeIssued() throws Exception {
+ void testSetWithNoLeadershipShouldNotBeIssued() throws Exception {
new Context() {
{
runTest(
@@ -290,7 +266,7 @@ public class KubernetesCheckpointIDCounterTest extends KubernetesHighAvailabilit
.remove(KubernetesLeaderElector.LEADER_ANNOTATION_KEY);
checkpointIDCounter.setCount(100L);
- assertThat(checkpointIDCounter.get(), is(2L));
+ assertThat(checkpointIDCounter.get()).isEqualTo(2L);
});
}
};
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityRecoverFromSavepointITCase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityRecoverFromSavepointITCase.java
index baa0603df52..386d3115e07 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityRecoverFromSavepointITCase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityRecoverFromSavepointITCase.java
@@ -31,7 +31,7 @@ import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HighAvailabilityOptions;
import org.apache.flink.core.execution.SavepointFormatType;
-import org.apache.flink.kubernetes.KubernetesResource;
+import org.apache.flink.kubernetes.KubernetesExtension;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
@@ -45,19 +45,20 @@ import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.DiscardingSink;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;
-import org.apache.flink.test.util.MiniClusterWithClientResource;
+import org.apache.flink.test.junit5.InjectClusterClient;
+import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.testutils.TestingUtils;
import org.apache.flink.util.Collector;
import org.apache.flink.util.FlinkRuntimeException;
-import org.apache.flink.util.TestLogger;
-import org.junit.Before;
-import org.junit.ClassRule;
-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.extension.RegisterExtension;
+import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@@ -67,7 +68,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* Tests for recovering from savepoint when Kubernetes HA is enabled. The savepoint will be
* persisted as a checkpoint and stored in the ConfigMap when recovered successfully.
*/
-public class KubernetesHighAvailabilityRecoverFromSavepointITCase extends TestLogger {
+class KubernetesHighAvailabilityRecoverFromSavepointITCase {
private static final long TIMEOUT = 60 * 1000;
@@ -75,32 +76,37 @@ public class KubernetesHighAvailabilityRecoverFromSavepointITCase extends TestLo
private static final String FLAT_MAP_UID = "my-flat-map";
- @ClassRule public static KubernetesResource kubernetesResource = new KubernetesResource();
+ private static Path temporaryPath;
- @ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
-
- @Rule
- public MiniClusterWithClientResource miniClusterResource =
- new MiniClusterWithClientResource(
+ @RegisterExtension
+ private static final MiniClusterExtension miniClusterExtension =
+ new MiniClusterExtension(
new MiniClusterResourceConfiguration.Builder()
.setConfiguration(getConfiguration())
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(1)
.build());
+ @RegisterExtension
+ private static final KubernetesExtension kubernetesExtension = new KubernetesExtension();
+
private ClusterClient<?> clusterClient;
private String savepointPath;
- @Before
- public void setup() throws Exception {
- clusterClient = miniClusterResource.getClusterClient();
- savepointPath = temporaryFolder.newFolder("savepoints").getAbsolutePath();
+ @BeforeEach
+ void setup(@InjectClusterClient ClusterClient<?> clusterClient) throws Exception {
+ this.clusterClient = clusterClient;
+ this.savepointPath =
+ Files.createDirectory(temporaryPath.resolve("savepoints"))
+ .toAbsolutePath()
+ .toString();
}
@Test
- public void testRecoverFromSavepoint() throws Exception {
- final JobGraph jobGraph = createJobGraph();
+ void testRecoverFromSavepoint() throws Exception {
+ Path stateBackend1 = Files.createDirectory(temporaryPath.resolve("stateBackend1"));
+ final JobGraph jobGraph = createJobGraph(stateBackend1.toFile());
clusterClient
.submitJob(jobGraph)
.get(TestingUtils.infiniteTime().toMilliseconds(), TimeUnit.MILLISECONDS);
@@ -121,7 +127,8 @@ public class KubernetesHighAvailabilityRecoverFromSavepointITCase extends TestLo
1000);
// Start a new job with savepoint 2
- final JobGraph jobGraphWithSavepoint = createJobGraph();
+ Path stateBackend2 = Files.createDirectory(temporaryPath.resolve("stateBackend2"));
+ final JobGraph jobGraphWithSavepoint = createJobGraph(stateBackend2.toFile());
final JobID jobId = jobGraphWithSavepoint.getJobID();
jobGraphWithSavepoint.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(savepoint2Path));
@@ -130,19 +137,19 @@ public class KubernetesHighAvailabilityRecoverFromSavepointITCase extends TestLo
assertThat(clusterClient.requestJobResult(jobId).join().isSuccess()).isTrue();
}
- private Configuration getConfiguration() {
+ private static Configuration getConfiguration() {
Configuration configuration = new Configuration();
configuration.set(KubernetesConfigOptions.CLUSTER_ID, CLUSTER_ID);
configuration.set(
HighAvailabilityOptions.HA_MODE,
KubernetesHaServicesFactory.class.getCanonicalName());
try {
- configuration.set(
- HighAvailabilityOptions.HA_STORAGE_PATH,
- temporaryFolder.newFolder().getAbsolutePath());
+ temporaryPath = Files.createTempDirectory("haStorage");
} catch (IOException e) {
throw new FlinkRuntimeException("Failed to create HA storage", e);
}
+ configuration.set(
+ HighAvailabilityOptions.HA_STORAGE_PATH, temporaryPath.toAbsolutePath().toString());
return configuration;
}
@@ -158,11 +165,10 @@ public class KubernetesHighAvailabilityRecoverFromSavepointITCase extends TestLo
return null;
}
- private JobGraph createJobGraph() throws Exception {
+ private JobGraph createJobGraph(File stateBackendFolder) throws Exception {
final StreamExecutionEnvironment sEnv =
StreamExecutionEnvironment.getExecutionEnvironment();
- final StateBackend stateBackend =
- new FsStateBackend(temporaryFolder.newFolder().toURI(), 1);
+ final StateBackend stateBackend = new FsStateBackend(stateBackendFolder.toURI(), 1);
sEnv.setStateBackend(stateBackend);
sEnv.addSource(new InfiniteSourceFunction())
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityTestBase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityTestBase.java
index eddefe81a92..ade0974a1b5 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityTestBase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesHighAvailabilityTestBase.java
@@ -29,12 +29,11 @@ import org.apache.flink.runtime.leaderelection.TestingLeaderElectionEventHandler
import org.apache.flink.runtime.leaderretrieval.LeaderRetrievalDriver;
import org.apache.flink.runtime.leaderretrieval.TestingLeaderRetrievalEventHandler;
import org.apache.flink.util.ExecutorUtils;
-import org.apache.flink.util.TestLogger;
import org.apache.flink.util.concurrent.ExecutorThreadFactory;
import org.apache.flink.util.function.RunnableWithException;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import java.util.Map;
import java.util.UUID;
@@ -44,7 +43,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/** Base class for high availability unit tests with a configured testing Kubernetes client. */
-public class KubernetesHighAvailabilityTestBase extends TestLogger {
+class KubernetesHighAvailabilityTestBase {
private static final String CLUSTER_ID = "leader-test-cluster";
public static final String LOCK_IDENTITY = UUID.randomUUID().toString();
@@ -57,15 +56,15 @@ public class KubernetesHighAvailabilityTestBase extends TestLogger {
protected ExecutorService executorService;
protected ExecutorService watchCallbackExecutorService;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
executorService = Executors.newFixedThreadPool(4, new ExecutorThreadFactory("IO-Executor"));
watchCallbackExecutorService =
Executors.newCachedThreadPool(new ExecutorThreadFactory("Watch-Callback"));
}
- @After
- public void teardown() {
+ @AfterEach
+ void teardown() {
ExecutorUtils.gracefulShutdown(
TIMEOUT, TimeUnit.MILLISECONDS, watchCallbackExecutorService, executorService);
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionAndRetrievalITCase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionAndRetrievalITCase.java
index 694e8a83c00..c52c89994f9 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionAndRetrievalITCase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionAndRetrievalITCase.java
@@ -19,7 +19,7 @@
package org.apache.flink.kubernetes.highavailability;
import org.apache.flink.configuration.Configuration;
-import org.apache.flink.kubernetes.KubernetesResource;
+import org.apache.flink.kubernetes.KubernetesExtension;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.configuration.KubernetesLeaderElectionConfiguration;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
@@ -29,10 +29,9 @@ import org.apache.flink.runtime.leaderelection.LeaderInformation;
import org.apache.flink.runtime.leaderelection.TestingLeaderElectionEventHandler;
import org.apache.flink.runtime.leaderretrieval.TestingLeaderRetrievalEventHandler;
import org.apache.flink.util.ExecutorUtils;
-import org.apache.flink.util.TestLogger;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
@@ -40,8 +39,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.apache.flink.kubernetes.utils.Constants.LABEL_CONFIGMAP_TYPE_HIGH_AVAILABILITY;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* IT Tests for the {@link KubernetesLeaderElectionDriver} and {@link
@@ -49,21 +47,23 @@ import static org.hamcrest.Matchers.is;
* become the leader and {@link KubernetesLeaderRetrievalDriver} could retrieve the leader address
* from Kubernetes.
*/
-public class KubernetesLeaderElectionAndRetrievalITCase extends TestLogger {
+class KubernetesLeaderElectionAndRetrievalITCase {
private static final String LEADER_CONFIGMAP_NAME = "leader-test-cluster";
private static final String LEADER_ADDRESS =
"akka.tcp://flink@172.20.1.21:6123/user/rpc/dispatcher";
- @ClassRule public static KubernetesResource kubernetesResource = new KubernetesResource();
+
+ @RegisterExtension
+ private static final KubernetesExtension kubernetesExtension = new KubernetesExtension();
@Test
- public void testLeaderElectionAndRetrieval() throws Exception {
+ void testLeaderElectionAndRetrieval() throws Exception {
final String configMapName = LEADER_CONFIGMAP_NAME + System.currentTimeMillis();
KubernetesLeaderElectionDriver leaderElectionDriver = null;
KubernetesLeaderRetrievalDriver leaderRetrievalDriver = null;
- final FlinkKubeClient flinkKubeClient = kubernetesResource.getFlinkKubeClient();
- final Configuration configuration = kubernetesResource.getConfiguration();
+ final FlinkKubeClient flinkKubeClient = kubernetesExtension.getFlinkKubeClient();
+ final Configuration configuration = kubernetesExtension.getConfiguration();
final String clusterId = configuration.getString(KubernetesConfigOptions.CLUSTER_ID);
final KubernetesConfigMapSharedWatcher configMapSharedWatcher =
@@ -103,16 +103,14 @@ public class KubernetesLeaderElectionAndRetrievalITCase extends TestLogger {
// Check the new leader is confirmed
final LeaderInformation confirmedLeaderInformation =
electionEventHandler.getConfirmedLeaderInformation();
- assertThat(confirmedLeaderInformation.getLeaderAddress(), is(LEADER_ADDRESS));
+ assertThat(confirmedLeaderInformation.getLeaderAddress()).isEqualTo(LEADER_ADDRESS);
// Check the leader retrieval driver should be notified the leader address
retrievalEventHandler.waitForNewLeader();
- assertThat(
- retrievalEventHandler.getLeaderSessionID(),
- is(confirmedLeaderInformation.getLeaderSessionID()));
- assertThat(
- retrievalEventHandler.getAddress(),
- is(confirmedLeaderInformation.getLeaderAddress()));
+ assertThat(retrievalEventHandler.getLeaderSessionID())
+ .isEqualByComparingTo(confirmedLeaderInformation.getLeaderSessionID());
+ assertThat(retrievalEventHandler.getAddress())
+ .isEqualTo(confirmedLeaderInformation.getLeaderAddress());
} finally {
electionEventHandler.close();
if (leaderElectionDriver != null) {
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionDriverTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionDriverTest.java
index 6072051ea58..a7654938cd0 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionDriverTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderElectionDriverTest.java
@@ -18,50 +18,47 @@
package org.apache.flink.kubernetes.highavailability;
-import org.apache.flink.core.testutils.FlinkMatchers;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
import org.apache.flink.runtime.leaderelection.LeaderInformation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
+import static org.apache.flink.core.testutils.FlinkAssertions.assertThatChainOfCauses;
import static org.apache.flink.kubernetes.utils.Constants.LABEL_CONFIGMAP_TYPE_HIGH_AVAILABILITY;
import static org.apache.flink.kubernetes.utils.Constants.LABEL_CONFIGMAP_TYPE_KEY;
import static org.apache.flink.kubernetes.utils.Constants.LEADER_ADDRESS_KEY;
import static org.apache.flink.kubernetes.utils.Constants.LEADER_SESSION_ID_KEY;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.notNullValue;
-import static org.hamcrest.Matchers.nullValue;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link KubernetesLeaderElectionDriver}. */
-public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabilityTestBase {
+class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabilityTestBase {
@Test
- public void testIsLeader() throws Exception {
+ void testIsLeader() throws Exception {
new Context() {
{
runTest(
() -> {
// Grant leadership
leaderCallbackGrantLeadership();
- assertThat(electionEventHandler.isLeader(), is(true));
+ assertThat(electionEventHandler.isLeader()).isTrue();
assertThat(
- electionEventHandler
- .getConfirmedLeaderInformation()
- .getLeaderAddress(),
- is(LEADER_ADDRESS));
+ electionEventHandler
+ .getConfirmedLeaderInformation()
+ .getLeaderAddress())
+ .isEqualTo(LEADER_ADDRESS);
});
}
};
}
@Test
- public void testNotLeader() throws Exception {
+ void testNotLeader() throws Exception {
new Context() {
{
runTest(
@@ -71,24 +68,21 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
getLeaderCallback().notLeader();
electionEventHandler.waitForRevokeLeader();
- assertThat(electionEventHandler.isLeader(), is(false));
- assertThat(
- electionEventHandler.getConfirmedLeaderInformation(),
- is(LeaderInformation.empty()));
+ assertThat(electionEventHandler.isLeader()).isFalse();
+ assertThat(electionEventHandler.getConfirmedLeaderInformation())
+ .isEqualTo(LeaderInformation.empty());
// The ConfigMap should also be cleared
- assertThat(
- getLeaderConfigMap().getData().get(LEADER_ADDRESS_KEY),
- is(nullValue()));
- assertThat(
- getLeaderConfigMap().getData().get(LEADER_SESSION_ID_KEY),
- is(nullValue()));
+ assertThat(getLeaderConfigMap().getData())
+ .doesNotContainKey(LEADER_ADDRESS_KEY);
+ assertThat(getLeaderConfigMap().getData())
+ .doesNotContainKey(LEADER_SESSION_ID_KEY);
});
}
};
}
@Test
- public void testHasLeadershipWhenConfigMapNotExist() throws Exception {
+ void testHasLeadershipWhenConfigMapNotExist() throws Exception {
new Context() {
{
runTest(
@@ -97,17 +91,16 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
electionEventHandler.waitForError();
final String errorMsg =
"ConfigMap " + LEADER_CONFIGMAP_NAME + " does not exist.";
- assertThat(electionEventHandler.getError(), is(notNullValue()));
- assertThat(
- electionEventHandler.getError(),
- FlinkMatchers.containsMessage(errorMsg));
+ assertThat(electionEventHandler.getError()).isNotNull();
+ assertThatChainOfCauses(electionEventHandler.getError())
+ .anySatisfy(t -> assertThat(t).hasMessageContaining(errorMsg));
});
}
};
}
@Test
- public void testWriteLeaderInformation() throws Exception {
+ void testWriteLeaderInformation() throws Exception {
new Context() {
{
runTest(
@@ -118,19 +111,19 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
LeaderInformation.known(UUID.randomUUID(), LEADER_ADDRESS);
leaderElectionDriver.writeLeaderInformation(leader);
- assertThat(
- getLeaderConfigMap().getData().get(LEADER_ADDRESS_KEY),
- is(leader.getLeaderAddress()));
- assertThat(
- getLeaderConfigMap().getData().get(LEADER_SESSION_ID_KEY),
- is(leader.getLeaderSessionID().toString()));
+ assertThat(getLeaderConfigMap().getData())
+ .containsEntry(LEADER_ADDRESS_KEY, leader.getLeaderAddress());
+ assertThat(getLeaderConfigMap().getData())
+ .containsEntry(
+ LEADER_SESSION_ID_KEY,
+ leader.getLeaderSessionID().toString());
});
}
};
}
@Test
- public void testWriteLeaderInformationWhenConfigMapNotExist() throws Exception {
+ void testWriteLeaderInformationWhenConfigMapNotExist() throws Exception {
new Context() {
{
runTest(
@@ -143,17 +136,16 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
"Could not write leader information since ConfigMap "
+ LEADER_CONFIGMAP_NAME
+ " does not exist.";
- assertThat(electionEventHandler.getError(), is(notNullValue()));
- assertThat(
- electionEventHandler.getError(),
- FlinkMatchers.containsMessage(errorMsg));
+ assertThat(electionEventHandler.getError()).isNotNull();
+ assertThatChainOfCauses(electionEventHandler.getError())
+ .anySatisfy(t -> assertThat(t).hasMessageContaining(errorMsg));
});
}
};
}
@Test
- public void testLeaderConfigMapModifiedExternallyShouldBeCorrected() throws Exception {
+ void testLeaderConfigMapModifiedExternallyShouldBeCorrected() throws Exception {
new Context() {
{
runTest(
@@ -181,19 +173,18 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
callbackHandler.onModified(Collections.singletonList(updatedConfigMap));
// The leader should be corrected
- assertThat(
- getLeaderConfigMap().getData().get(LEADER_ADDRESS_KEY),
- is(LEADER_ADDRESS));
- assertThat(
- getLeaderConfigMap().getData().get(LEADER_SESSION_ID_KEY),
- is(leaderSessionId.toString()));
+ assertThat(getLeaderConfigMap().getData())
+ .containsEntry(LEADER_ADDRESS_KEY, LEADER_ADDRESS);
+ assertThat(getLeaderConfigMap().getData())
+ .containsEntry(
+ LEADER_SESSION_ID_KEY, leaderSessionId.toString());
});
}
};
}
@Test
- public void testLeaderConfigMapDeletedExternally() throws Exception {
+ void testLeaderConfigMapDeletedExternally() throws Exception {
new Context() {
{
runTest(
@@ -208,17 +199,16 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
electionEventHandler.waitForError();
final String errorMsg =
"ConfigMap " + LEADER_CONFIGMAP_NAME + " is deleted externally";
- assertThat(electionEventHandler.getError(), is(notNullValue()));
- assertThat(
- electionEventHandler.getError(),
- FlinkMatchers.containsMessage(errorMsg));
+ assertThat(electionEventHandler.getError()).isNotNull();
+ assertThatChainOfCauses(electionEventHandler.getError())
+ .anySatisfy(t -> assertThat(t).hasMessageContaining(errorMsg));
});
}
};
}
@Test
- public void testErrorForwarding() throws Exception {
+ void testErrorForwarding() throws Exception {
new Context() {
{
runTest(
@@ -233,17 +223,16 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
electionEventHandler.waitForError();
final String errorMsg =
"Error while watching the ConfigMap " + LEADER_CONFIGMAP_NAME;
- assertThat(electionEventHandler.getError(), is(notNullValue()));
- assertThat(
- electionEventHandler.getError(),
- FlinkMatchers.containsMessage(errorMsg));
+ assertThat(electionEventHandler.getError()).isNotNull();
+ assertThatChainOfCauses(electionEventHandler.getError())
+ .anySatisfy(t -> assertThat(t).hasMessageContaining(errorMsg));
});
}
};
}
@Test
- public void testHighAvailabilityLabelsCorrectlySet() throws Exception {
+ void testHighAvailabilityLabelsCorrectlySet() throws Exception {
new Context() {
{
runTest(
@@ -252,10 +241,11 @@ public class KubernetesLeaderElectionDriverTest extends KubernetesHighAvailabili
final Map<String, String> leaderLabels =
getLeaderConfigMap().getLabels();
- assertThat(leaderLabels.size(), is(3));
- assertThat(
- leaderLabels.get(LABEL_CONFIGMAP_TYPE_KEY),
- is(LABEL_CONFIGMAP_TYPE_HIGH_AVAILABILITY));
+ assertThat(leaderLabels).hasSize(3);
+ assertThat(leaderLabels)
+ .containsEntry(
+ LABEL_CONFIGMAP_TYPE_KEY,
+ LABEL_CONFIGMAP_TYPE_HIGH_AVAILABILITY);
});
}
};
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderRetrievalDriverTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderRetrievalDriverTest.java
index 3193f9f1549..5e09c729655 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderRetrievalDriverTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesLeaderRetrievalDriverTest.java
@@ -18,24 +18,22 @@
package org.apache.flink.kubernetes.highavailability;
-import org.apache.flink.core.testutils.FlinkMatchers;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
import org.apache.flink.kubernetes.utils.Constants;
-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.is;
-import static org.hamcrest.Matchers.nullValue;
+import static org.apache.flink.core.testutils.FlinkAssertions.assertThatChainOfCauses;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link KubernetesLeaderRetrievalDriver}. */
-public class KubernetesLeaderRetrievalDriverTest extends KubernetesHighAvailabilityTestBase {
+class KubernetesLeaderRetrievalDriverTest extends KubernetesHighAvailabilityTestBase {
@Test
- public void testErrorForwarding() throws Exception {
+ void testErrorForwarding() throws Exception {
new Context() {
{
runTest(
@@ -49,16 +47,15 @@ public class KubernetesLeaderRetrievalDriverTest extends KubernetesHighAvailabil
final String errMsg =
"Error while watching the ConfigMap " + LEADER_CONFIGMAP_NAME;
retrievalEventHandler.waitForError();
- assertThat(
- retrievalEventHandler.getError(),
- FlinkMatchers.containsMessage(errMsg));
+ assertThatChainOfCauses(retrievalEventHandler.getError())
+ .anySatisfy(t -> assertThat(t).hasMessageContaining(errMsg));
});
}
};
}
@Test
- public void testKubernetesLeaderRetrievalOnModified() throws Exception {
+ void testKubernetesLeaderRetrievalOnModified() throws Exception {
new Context() {
{
runTest(
@@ -76,14 +73,15 @@ public class KubernetesLeaderRetrievalDriverTest extends KubernetesHighAvailabil
callbackHandler.onModified(
Collections.singletonList(getLeaderConfigMap()));
- assertThat(retrievalEventHandler.waitForNewLeader(), is(newLeader));
+ assertThat(retrievalEventHandler.waitForNewLeader())
+ .isEqualTo(newLeader);
});
}
};
}
@Test
- public void testKubernetesLeaderRetrievalOnModifiedWithEmpty() throws Exception {
+ void testKubernetesLeaderRetrievalOnModifiedWithEmpty() throws Exception {
new Context() {
{
runTest(
@@ -98,7 +96,7 @@ public class KubernetesLeaderRetrievalDriverTest extends KubernetesHighAvailabil
callbackHandler.onModified(
Collections.singletonList(getLeaderConfigMap()));
retrievalEventHandler.waitForEmptyLeaderInformation();
- assertThat(retrievalEventHandler.getAddress(), is(nullValue()));
+ assertThat(retrievalEventHandler.getAddress()).isNull();
});
}
};
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesMultipleComponentLeaderElectionDriverTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesMultipleComponentLeaderElectionDriverTest.java
index 738d7b8d051..ce2363b9664 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesMultipleComponentLeaderElectionDriverTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesMultipleComponentLeaderElectionDriverTest.java
@@ -32,11 +32,9 @@ import org.apache.flink.runtime.leaderretrieval.DefaultLeaderRetrievalService;
import org.apache.flink.runtime.util.TestingFatalErrorHandlerExtension;
import org.apache.flink.testutils.TestingUtils;
import org.apache.flink.testutils.executor.TestExecutorExtension;
-import org.apache.flink.util.TestLoggerExtension;
import org.apache.flink.util.function.RunnableWithException;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.Collections;
@@ -46,8 +44,7 @@ import java.util.concurrent.ScheduledExecutorService;
import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link KubernetesMultipleComponentLeaderElectionDriver}. */
-@ExtendWith(TestLoggerExtension.class)
-public class KubernetesMultipleComponentLeaderElectionDriverTest {
+class KubernetesMultipleComponentLeaderElectionDriverTest {
private static final String CLUSTER_ID = "test-cluster";
private static final String LEADER_CONFIGMAP_NAME = "leader-configmap-name";
@@ -62,7 +59,7 @@ public class KubernetesMultipleComponentLeaderElectionDriverTest {
TestingUtils.defaultExecutorExtension();
@Test
- public void testElectionDriverGainsLeadership() throws Exception {
+ void testElectionDriverGainsLeadership() throws Exception {
new TestFixture() {
{
runTest(
@@ -75,7 +72,7 @@ public class KubernetesMultipleComponentLeaderElectionDriverTest {
}
@Test
- public void testElectionDriverLosesLeadership() throws Exception {
+ void testElectionDriverLosesLeadership() throws Exception {
new TestFixture() {
{
runTest(
@@ -90,7 +87,7 @@ public class KubernetesMultipleComponentLeaderElectionDriverTest {
}
@Test
- public void testPublishLeaderInformation() throws Exception {
+ void testPublishLeaderInformation() throws Exception {
new TestFixture() {
{
runTest(
@@ -127,7 +124,7 @@ public class KubernetesMultipleComponentLeaderElectionDriverTest {
}
@Test
- public void testLeaderInformationChangeNotifiesListener() throws Exception {
+ void testLeaderInformationChangeNotifiesListener() throws Exception {
new TestFixture() {
{
runTest(
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreITCase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreITCase.java
index 5c78168953e..3f6606e4bd4 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreITCase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreITCase.java
@@ -19,23 +19,20 @@
package org.apache.flink.kubernetes.highavailability;
import org.apache.flink.configuration.Configuration;
-import org.apache.flink.kubernetes.KubernetesResource;
+import org.apache.flink.kubernetes.KubernetesExtension;
import org.apache.flink.kubernetes.configuration.KubernetesLeaderElectionConfiguration;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesLeaderElector;
import org.apache.flink.kubernetes.kubeclient.resources.TestingLeaderCallbackHandler;
import org.apache.flink.runtime.persistence.TestingLongStateHandleHelper;
-import org.apache.flink.util.TestLogger;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.UUID;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.notNullValue;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* IT Tests for the {@link KubernetesStateHandleStore}. We expect only the leader could update the
@@ -44,18 +41,20 @@ import static org.hamcrest.Matchers.notNullValue;
* org.apache.flink.runtime.jobmanager.JobGraphStore} and {@link
* org.apache.flink.runtime.checkpoint.CompletedCheckpointStore} implementation for Kubernetes.
*/
-public class KubernetesStateHandleStoreITCase extends TestLogger {
+class KubernetesStateHandleStoreITCase {
private static final String LEADER_CONFIGMAP_NAME = "leader-test-cluster";
- @ClassRule public static KubernetesResource kubernetesResource = new KubernetesResource();
+
+ @RegisterExtension
+ private static final KubernetesExtension kubernetesExtension = new KubernetesExtension();
private final FlinkKubeClientFactory kubeClientFactory = new FlinkKubeClientFactory();
private static final String KEY = "state-handle-test";
@Test
- public void testMultipleKubernetesStateHandleStores() throws Exception {
- final Configuration configuration = kubernetesResource.getConfiguration();
+ void testMultipleKubernetesStateHandleStores() throws Exception {
+ final Configuration configuration = kubernetesExtension.getConfiguration();
final String leaderConfigMapName = LEADER_CONFIGMAP_NAME + System.currentTimeMillis();
final int leaderNum = 3;
@@ -105,12 +104,11 @@ public class KubernetesStateHandleStoreITCase extends TestLogger {
}
// Only the leader could add successfully
- assertThat(expectedState, is(notNullValue()));
- assertThat(stateHandleStores[0].getAllAndLock().size(), is(1));
- assertThat(
- stateHandleStores[0].getAllAndLock().get(0).f0.retrieveState().getValue(),
- is(expectedState));
- assertThat(stateHandleStores[0].getAllAndLock().get(0).f1, is(KEY));
+ assertThat(expectedState).isNotNull();
+ assertThat(stateHandleStores[0].getAllAndLock()).hasSize(1);
+ assertThat(stateHandleStores[0].getAllAndLock().get(0).f0.retrieveState().getValue())
+ .isEqualTo(expectedState);
+ assertThat(stateHandleStores[0].getAllAndLock().get(0).f1).isEqualTo(KEY);
} finally {
TestingLongStateHandleHelper.clearGlobalState();
// Cleanup the resources
@@ -122,7 +120,7 @@ public class KubernetesStateHandleStoreITCase extends TestLogger {
kubeClients[i].close();
}
}
- kubernetesResource.getFlinkKubeClient().deleteConfigMap(leaderConfigMapName).get();
+ kubernetesExtension.getFlinkKubeClient().deleteConfigMap(leaderConfigMapName).get();
}
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreTest.java
index c2b46c8ed80..e246dda45a9 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesStateHandleStoreTest.java
@@ -19,7 +19,6 @@
package org.apache.flink.kubernetes.highavailability;
import org.apache.flink.api.common.JobID;
-import org.apache.flink.core.testutils.FlinkMatchers;
import org.apache.flink.kubernetes.highavailability.KubernetesStateHandleStore.StateHandleWithDeleteMarker;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
@@ -28,13 +27,12 @@ import org.apache.flink.runtime.persistence.PossibleInconsistentStateException;
import org.apache.flink.runtime.persistence.StateHandleStore;
import org.apache.flink.runtime.persistence.StringResourceVersion;
import org.apache.flink.runtime.persistence.TestingLongStateHandleHelper;
-import org.apache.flink.runtime.state.RetrievableStateHandle;
import org.apache.flink.util.FlinkRuntimeException;
import org.apache.flink.util.concurrent.FutureUtils;
import org.apache.flink.util.function.FunctionUtils;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
@@ -42,18 +40,15 @@ import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.hamcrest.Matchers.notNullValue;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.fail;
+import static org.apache.flink.core.testutils.FlinkAssertions.anyCauseMatches;
+import static org.apache.flink.core.testutils.FlinkAssertions.assertThatChainOfCauses;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.fail;
/** Tests for {@link KubernetesStateHandleStore} operations. */
-public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTestBase {
+class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTestBase {
private static final String PREFIX = "test-prefix-";
@@ -64,15 +59,15 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
private TestingLongStateHandleHelper.LongStateHandle state;
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
super.setup();
state = new TestingLongStateHandleHelper.LongStateHandle(12345L);
TestingLongStateHandleHelper.clearGlobalState();
}
@Test
- public void testAdd() throws Exception {
+ void testAdd() throws Exception {
new Context() {
{
runTest(
@@ -89,15 +84,15 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
filter,
LOCK_IDENTITY);
store.addAndLock(key, state);
- assertThat(store.getAllAndLock().size(), is(1));
- assertThat(store.getAndLock(key).retrieveState(), is(state));
+ assertThat(store.getAllAndLock()).hasSize(1);
+ assertThat(store.getAndLock(key).retrieveState()).isEqualTo(state);
});
}
};
}
@Test
- public void testAddAndLockWithExistingKey() throws Exception {
+ void testAddAndLockWithExistingKey() throws Exception {
new Context() {
{
runTest(
@@ -120,31 +115,33 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
final TestingLongStateHandleHelper.LongStateHandle newState =
new TestingLongStateHandleHelper.LongStateHandle(12345L);
- try {
- store.addAndLock(key, newState);
- fail("Exception should be thrown.");
- } catch (StateHandleStore.AlreadyExistException ex) {
- final String msg =
- String.format(
- "%s already exists in ConfigMap %s",
- key, LEADER_CONFIGMAP_NAME);
- assertThat(ex, FlinkMatchers.containsMessage(msg));
- }
+ final String msg =
+ String.format(
+ "%s already exists in ConfigMap %s",
+ key, LEADER_CONFIGMAP_NAME);
+ assertThatThrownBy(
+ () -> store.addAndLock(key, newState),
+ "Exception should be thrown.")
+ .satisfies(
+ anyCauseMatches(
+ StateHandleStore.AlreadyExistException.class,
+ msg));
// Both initial & new handles should be in the storage (we never clean
// it for testing).
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(2));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(2);
// Only the new one (second entry in the store) should have been
// discarded.
- assertThat(oldState.isDiscarded(), is(false));
- assertThat(newState.isDiscarded(), is(true));
+ assertThat(oldState.isDiscarded()).isFalse();
+ assertThat(newState.isDiscarded()).isTrue();
});
}
};
}
@Test
- public void testAddAndLockWithDeletingEntry() throws Exception {
+ void testAddAndLockWithDeletingEntry() throws Exception {
new Context() {
{
runTest(
@@ -169,22 +166,24 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
store.addAndLock(
key, new TestingLongStateHandleHelper.LongStateHandle(3L));
- assertThat(store.getAndLock(key).retrieveState().getValue(), is(3L));
+ assertThat(store.getAndLock(key).retrieveState().getValue())
+ .isEqualTo(3L);
// Both initial & new handles should be in the storage (we never clean
// it for testing).
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(2));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(2);
// Only the old one (first entry in the store) should have been
// discarded.
- assertThat(oldState.getNumberOfSuccessfulDiscardCalls(), is(1));
- assertThat(newState.getNumberOfSuccessfulDiscardCalls(), is(0));
+ assertThat(oldState.getNumberOfSuccessfulDiscardCalls()).isEqualTo(1);
+ assertThat(newState.getNumberOfSuccessfulDiscardCalls()).isEqualTo(0);
});
}
};
}
@Test
- public void testAddWithPossiblyInconsistentStateHandling() throws Exception {
+ void testAddWithPossiblyInconsistentStateHandling() throws Exception {
new Context() {
{
runTest(
@@ -214,15 +213,17 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
} catch (PossibleInconsistentStateException ex) {
// PossibleInconsistentStateException is expected
}
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(1));
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(0));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(1);
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(0);
});
}
};
}
@Test
- public void testAddFailedWhenConfigMapNotExistAndDiscardState() throws Exception {
+ void testAddFailedWhenConfigMapNotExistAndDiscardState() throws Exception {
new Context() {
{
runTest(
@@ -236,29 +237,27 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
longStateStorage,
filter,
LOCK_IDENTITY);
-
- try {
- store.addAndLock(key, state);
- fail("Exception should be thrown.");
- } catch (Exception ex) {
- final String msg =
- String.format(
- "ConfigMap %s does not exist.",
- LEADER_CONFIGMAP_NAME);
- assertThat(ex, FlinkMatchers.containsMessage(msg));
- }
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(1));
+ final String msg =
+ String.format(
+ "ConfigMap %s does not exist.", LEADER_CONFIGMAP_NAME);
+ assertThatThrownBy(
+ () -> store.addAndLock(key, state),
+ "Exception should be thrown.")
+ .satisfies(anyCauseMatches(msg));
+
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(1);
assertThat(
- TestingLongStateHandleHelper
- .getDiscardCallCountForStateHandleByIndex(0),
- is(1));
+ TestingLongStateHandleHelper
+ .getDiscardCallCountForStateHandleByIndex(0))
+ .isEqualTo(1);
});
}
};
}
@Test
- public void testReplace() throws Exception {
+ void testReplace() throws Exception {
new Context() {
{
runTest(
@@ -282,15 +281,15 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
final StringResourceVersion resourceVersion = store.exists(key);
store.replace(key, resourceVersion, newState);
- assertThat(store.getAllAndLock().size(), is(1));
- assertThat(store.getAndLock(key).retrieveState(), is(newState));
+ assertThat(store.getAllAndLock()).hasSize(1);
+ assertThat(store.getAndLock(key).retrieveState()).isEqualTo(newState);
});
}
};
}
@Test
- public void testReplaceWithKeyNotExist() throws Exception {
+ void testReplaceWithKeyNotExist() throws Exception {
new Context() {
{
runTest(
@@ -309,26 +308,30 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
final TestingLongStateHandleHelper.LongStateHandle newState =
new TestingLongStateHandleHelper.LongStateHandle(23456L);
- try {
- assertThat(
- store.exists(key), is(StringResourceVersion.notExisting()));
- store.replace(key, StringResourceVersion.notExisting(), newState);
- fail("Exception should be thrown.");
- } catch (StateHandleStore.NotExistException e) {
- final String msg =
- String.format(
- "Could not find %s in ConfigMap %s",
- key, LEADER_CONFIGMAP_NAME);
- assertThat(e, FlinkMatchers.containsMessage(msg));
- }
- assertThat(store.getAllAndLock().size(), is(0));
+ assertThat(store.exists(key))
+ .isEqualByComparingTo(StringResourceVersion.notExisting());
+ final String msg =
+ String.format(
+ "Could not find %s in ConfigMap %s",
+ key, LEADER_CONFIGMAP_NAME);
+ assertThatThrownBy(
+ () ->
+ store.replace(
+ key,
+ StringResourceVersion.notExisting(),
+ newState),
+ "Exception should be thrown.")
+ .satisfies(
+ anyCauseMatches(
+ StateHandleStore.NotExistException.class, msg));
+ assertThat(store.getAllAndLock()).isEmpty();
});
}
};
}
@Test
- public void testReplaceWithDeletingKey() throws Exception {
+ void testReplaceWithDeletingKey() throws Exception {
new Context() {
{
runTest(
@@ -350,26 +353,29 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
final TestingLongStateHandleHelper.LongStateHandle newState =
new TestingLongStateHandleHelper.LongStateHandle(23456L);
- assertThat(store.exists(key), is(StringResourceVersion.notExisting()));
- assertThrows(
- StateHandleStore.NotExistException.class,
- () ->
- store.replace(
- key,
- StringResourceVersion.notExisting(),
- newState));
-
+ assertThat(store.exists(key))
+ .isEqualByComparingTo(StringResourceVersion.notExisting());
+ assertThatThrownBy(
+ () ->
+ store.replace(
+ key,
+ StringResourceVersion.notExisting(),
+ newState))
+ .satisfies(
+ anyCauseMatches(
+ StateHandleStore.NotExistException.class));
// Both handles should have been stored and discarded.
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(2));
- assertThat(oldState.isDiscarded(), is(true));
- assertThat(newState.isDiscarded(), is(true));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(2);
+ assertThat(oldState.isDiscarded()).isTrue();
+ assertThat(newState.isDiscarded()).isTrue();
});
}
};
}
@Test
- public void testReplaceWithDeletingKeyWithFailingDiscard() throws Exception {
+ void testReplaceWithDeletingKeyWithFailingDiscard() throws Exception {
new Context() {
{
runTest(
@@ -399,31 +405,45 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
final TestingLongStateHandleHelper.LongStateHandle newState =
new TestingLongStateHandleHelper.LongStateHandle(23456L);
- assertThat(store.exists(key), is(StringResourceVersion.notExisting()));
- final StateHandleStore.NotExistException exception =
- assertThrows(
- StateHandleStore.NotExistException.class,
+ assertThat(store.exists(key))
+ .isEqualByComparingTo(StringResourceVersion.notExisting());
+ assertThatThrownBy(
() ->
store.replace(
key,
StringResourceVersion.notExisting(),
- newState));
- assertThat(exception.getSuppressed().length, is(1));
- assertThat(
- exception.getSuppressed()[0],
- FlinkMatchers.containsCause(discardException));
+ newState))
+ .satisfies(
+ cause -> {
+ assertThat(cause)
+ .isInstanceOf(
+ StateHandleStore.NotExistException
+ .class);
+ assertThat(cause.getSuppressed()).hasSize(1);
+ assertThatChainOfCauses(cause.getSuppressed()[0])
+ .anySatisfy(
+ ex ->
+ assertThat(ex)
+ .isInstanceOf(
+ discardException
+ .getClass())
+ .hasMessageContaining(
+ discardException
+ .getMessage()));
+ });
// Only the new handle should have been discarded.
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(2));
- assertThat(oldState.isDiscarded(), is(false));
- assertThat(newState.isDiscarded(), is(true));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(2);
+ assertThat(oldState.isDiscarded()).isFalse();
+ assertThat(newState.isDiscarded()).isTrue();
});
}
};
}
@Test
- public void testReplaceWithNoLeadershipAndDiscardState() throws Exception {
+ void testReplaceWithNoLeadershipAndDiscardState() throws Exception {
new Context() {
{
runTest(
@@ -452,26 +472,27 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
final StringResourceVersion resourceVersion = store.exists(key);
store.replace(key, resourceVersion, newState);
- assertThat(store.getAllAndLock().size(), is(1));
+ assertThat(store.getAllAndLock()).hasSize(1);
// The state do not change
- assertThat(store.getAndLock(key).retrieveState(), is(state));
+ assertThat(store.getAndLock(key).retrieveState()).isEqualTo(state);
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(2));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(2);
assertThat(
- TestingLongStateHandleHelper
- .getDiscardCallCountForStateHandleByIndex(0),
- is(0));
+ TestingLongStateHandleHelper
+ .getDiscardCallCountForStateHandleByIndex(0))
+ .isEqualTo(0);
assertThat(
- TestingLongStateHandleHelper
- .getDiscardCallCountForStateHandleByIndex(1),
- is(1));
+ TestingLongStateHandleHelper
+ .getDiscardCallCountForStateHandleByIndex(1))
+ .isEqualTo(1);
});
}
};
}
@Test
- public void testReplaceFailedAndDiscardState() throws Exception {
+ void testReplaceFailedAndDiscardState() throws Exception {
final FlinkRuntimeException updateException = new FlinkRuntimeException("Failed to update");
new Context() {
{
@@ -510,34 +531,38 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
final TestingLongStateHandleHelper.LongStateHandle newState =
new TestingLongStateHandleHelper.LongStateHandle(23456L);
final StringResourceVersion resourceVersion = anotherStore.exists(key);
- assertThat(resourceVersion.isExisting(), is(true));
- try {
- anotherStore.replace(key, resourceVersion, newState);
- fail(
- "We should get an exception when kube client failed to update.");
- } catch (Exception ex) {
- assertThat(ex, FlinkMatchers.containsCause(updateException));
- }
- assertThat(anotherStore.getAllAndLock().size(), is(1));
+ assertThat(resourceVersion.isExisting()).isTrue();
+ assertThatThrownBy(
+ () ->
+ anotherStore.replace(
+ key, resourceVersion, newState),
+ "We should get an exception when kube client failed to update.")
+ .satisfies(
+ anyCauseMatches(
+ updateException.getClass(),
+ updateException.getMessage()));
+ assertThat(anotherStore.getAllAndLock()).hasSize(1);
// The state do not change
- assertThat(anotherStore.getAndLock(key).retrieveState(), is(state));
+ assertThat(anotherStore.getAndLock(key).retrieveState())
+ .isEqualTo(state);
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(2));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(2);
assertThat(
- TestingLongStateHandleHelper
- .getDiscardCallCountForStateHandleByIndex(0),
- is(0));
+ TestingLongStateHandleHelper
+ .getDiscardCallCountForStateHandleByIndex(0))
+ .isEqualTo(0);
assertThat(
- TestingLongStateHandleHelper
- .getDiscardCallCountForStateHandleByIndex(1),
- is(1));
+ TestingLongStateHandleHelper
+ .getDiscardCallCountForStateHandleByIndex(1))
+ .isEqualTo(1);
});
}
};
}
@Test
- public void testReplaceFailedWithPossiblyInconsistentState() throws Exception {
+ void testReplaceFailedWithPossiblyInconsistentState() throws Exception {
final PossibleInconsistentStateException updateException =
new PossibleInconsistentStateException();
new Context() {
@@ -575,38 +600,39 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
LOCK_IDENTITY);
final StringResourceVersion resourceVersion = anotherStore.exists(key);
- assertThat(resourceVersion.isExisting(), is(true));
- try {
- anotherStore.replace(
- key,
- resourceVersion,
- new TestingLongStateHandleHelper.LongStateHandle(23456L));
- fail(
- "An exception having a PossibleInconsistentStateException as its cause should have been thrown.");
- } catch (Exception ex) {
- assertThat(ex, is(updateException));
- }
- assertThat(anotherStore.getAllAndLock().size(), is(1));
+ assertThat(resourceVersion.isExisting()).isTrue();
+ assertThatThrownBy(
+ () ->
+ anotherStore.replace(
+ key,
+ resourceVersion,
+ new TestingLongStateHandleHelper
+ .LongStateHandle(23456L)),
+ "An exception having a PossibleInconsistentStateException as its cause should have been thrown.")
+ .isEqualTo(updateException);
+ assertThat(anotherStore.getAllAndLock()).hasSize(1);
// The state does not change
- assertThat(anotherStore.getAndLock(key).retrieveState(), is(state));
+ assertThat(anotherStore.getAndLock(key).retrieveState())
+ .isEqualTo(state);
- assertThat(TestingLongStateHandleHelper.getGlobalStorageSize(), is(2));
+ assertThat(TestingLongStateHandleHelper.getGlobalStorageSize())
+ .isEqualTo(2);
// no state was discarded
assertThat(
- TestingLongStateHandleHelper
- .getDiscardCallCountForStateHandleByIndex(0),
- is(0));
+ TestingLongStateHandleHelper
+ .getDiscardCallCountForStateHandleByIndex(0))
+ .isEqualTo(0);
assertThat(
- TestingLongStateHandleHelper
- .getDiscardCallCountForStateHandleByIndex(1),
- is(0));
+ TestingLongStateHandleHelper
+ .getDiscardCallCountForStateHandleByIndex(1))
+ .isEqualTo(0);
});
}
};
}
@Test
- public void testGetAndExist() throws Exception {
+ void testGetAndExist() throws Exception {
new Context() {
{
runTest(
@@ -623,17 +649,16 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
filter,
LOCK_IDENTITY);
store.addAndLock(key, state);
- assertThat(
- store.exists(key),
- is(not(StringResourceVersion.notExisting())));
- assertThat(store.getAndLock(key).retrieveState(), is(state));
+ assertThat(store.exists(key))
+ .isNotEqualByComparingTo(StringResourceVersion.notExisting());
+ assertThat(store.getAndLock(key).retrieveState()).isEqualTo(state);
});
}
};
}
@Test
- public void testExistsWithDeletingEntry() throws Exception {
+ void testExistsWithDeletingEntry() throws Exception {
new Context() {
{
runTest(
@@ -654,16 +679,16 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
LOCK_IDENTITY);
final StringResourceVersion resourceVersion = store.exists(key);
- assertThat(resourceVersion.isExisting(), is(false));
+ assertThat(resourceVersion.isExisting()).isFalse();
// We don't try to pro-actively remove the entry here.
- assertThat(state.isDiscarded(), is(false));
+ assertThat(state.isDiscarded()).isFalse();
});
}
};
}
@Test
- public void testGetNonExistingKey() throws Exception {
+ void testGetNonExistingKey() throws Exception {
new Context() {
{
runTest(
@@ -681,26 +706,24 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
LOCK_IDENTITY);
final String nonExistingKey = "non-existing-key";
store.addAndLock(key, state);
- assertThat(
- store.exists(nonExistingKey),
- is(StringResourceVersion.notExisting()));
- try {
- store.getAndLock(nonExistingKey);
- fail("Exception should be thrown.");
- } catch (StateHandleStore.NotExistException e) {
- final String msg =
- String.format(
- "Could not find %s in ConfigMap %s",
- nonExistingKey, LEADER_CONFIGMAP_NAME);
- assertThat(e, FlinkMatchers.containsMessage(msg));
- }
+ assertThat(store.exists(nonExistingKey))
+ .isEqualByComparingTo(StringResourceVersion.notExisting());
+
+ final String msg =
+ String.format(
+ "Could not find %s in ConfigMap %s",
+ nonExistingKey, LEADER_CONFIGMAP_NAME);
+ assertThatThrownBy(
+ () -> store.getAndLock(nonExistingKey),
+ "Exception should be thrown.")
+ .satisfies(anyCauseMatches(msg));
});
}
};
}
@Test
- public void testGetAll() throws Exception {
+ void testGetAll() throws Exception {
new Context() {
{
runTest(
@@ -732,19 +755,19 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
TestingLongStateHandleHelper.LongStateHandle[]
::new);
assertThat(
- Arrays.stream(actual)
- .map(
- TestingLongStateHandleHelper.LongStateHandle
- ::getValue)
- .collect(Collectors.toList()),
- containsInAnyOrder(expected.toArray()));
+ Arrays.stream(actual)
+ .map(
+ TestingLongStateHandleHelper
+ .LongStateHandle
+ ::getValue))
+ .containsExactlyInAnyOrderElementsOf(expected);
});
}
};
}
@Test
- public void testGetAllHandles() throws Exception {
+ void testGetAllHandles() throws Exception {
new Context() {
{
runTest(
@@ -767,15 +790,14 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
}
final String[] actual = store.getAllHandles().toArray(new String[0]);
expected.sort(Comparator.comparing(e -> e));
- assertThat(
- Arrays.asList(actual), containsInAnyOrder(expected.toArray()));
+ assertThat(actual).containsExactlyInAnyOrderElementsOf(expected);
});
}
};
}
@Test
- public void testRemove() throws Exception {
+ void testRemove() throws Exception {
new Context() {
{
runTest(
@@ -792,19 +814,20 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
filter,
LOCK_IDENTITY);
store.addAndLock(key, state);
- assertThat(store.getAllAndLock().size(), is(1));
- assertThat(store.releaseAndTryRemove(key), is(true));
- assertThat(store.getAllAndLock().size(), is(0));
+ assertThat(store.getAllAndLock()).hasSize(1);
+ assertThat(store.releaseAndTryRemove(key)).isTrue();
+ assertThat(store.getAllAndLock()).hasSize(0);
// State should also be discarded.
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(1));
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(1);
});
}
};
}
@Test
- public void testRemoveOfNonExistingState() throws Exception {
+ void testRemoveOfNonExistingState() throws Exception {
new Context() {
{
runTest(
@@ -820,18 +843,19 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
longStateStorage,
filter,
LOCK_IDENTITY);
- assertThat(store.getAllAndLock().size(), is(0));
- assertThat(store.releaseAndTryRemove(key), is(true));
- assertThat(store.getAllAndLock().size(), is(0));
+ assertThat(store.getAllAndLock()).hasSize(0);
+ assertThat(store.releaseAndTryRemove(key)).isTrue();
+ assertThat(store.getAllAndLock()).hasSize(0);
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(0));
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(0);
});
}
};
}
@Test
- public void testRemoveFailedShouldNotDiscardState() throws Exception {
+ void testRemoveFailedShouldNotDiscardState() throws Exception {
new Context() {
{
runTest(
@@ -856,17 +880,18 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
.getAnnotations()
.remove(KubernetesLeaderElector.LEADER_ANNOTATION_KEY);
- assertThat(store.releaseAndTryRemove(key), is(false));
- assertThat(store.getAllAndLock().size(), is(1));
+ assertThat(store.releaseAndTryRemove(key)).isFalse();
+ assertThat(store.getAllAndLock()).hasSize(1);
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(0));
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(0);
});
}
};
}
@Test
- public void testRemoveAllHandlesAndDiscardState() throws Exception {
+ void testRemoveAllHandlesAndDiscardState() throws Exception {
new Context() {
{
runTest(
@@ -886,17 +911,18 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
store.addAndLock(
key + "1",
new TestingLongStateHandleHelper.LongStateHandle(2L));
- assertThat(store.getAllAndLock().size(), is(2));
+ assertThat(store.getAllAndLock()).hasSize(2);
store.releaseAndTryRemoveAll();
- assertThat(store.getAllAndLock().size(), is(0));
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(2));
+ assertThat(store.getAllAndLock()).hasSize(0);
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(2);
});
}
};
}
@Test
- public void testRemoveAllHandles() throws Exception {
+ void testRemoveAllHandles() throws Exception {
new Context() {
{
runTest(
@@ -919,22 +945,22 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
store.addAndLock(
key + "1",
new TestingLongStateHandleHelper.LongStateHandle(2L));
- assertThat(store.getAllAndLock().size(), is(2));
+ assertThat(store.getAllAndLock()).hasSize(2);
store.clearEntries();
- assertThat(store.getAllAndLock().size(), is(0));
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(0));
+ assertThat(store.getAllAndLock()).hasSize(0);
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(0);
// Should only remove the key with specified prefix.
- assertThat(
- getLeaderConfigMap().getData().containsKey(anotherKey),
- is(true));
+ assertThat(getLeaderConfigMap().getData().containsKey(anotherKey))
+ .isTrue();
});
}
};
}
@Test
- public void testReleaseAndTryRemoveIsIdempotent() throws Exception {
+ void testReleaseAndTryRemoveIsIdempotent() throws Exception {
new Context() {
{
runTest(
@@ -963,40 +989,41 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
}
}));
- assertThat(store.getAllAndLock().size(), is(1));
- assertThat(
- store.getAndLock(key),
- is(notNullValue(RetrievableStateHandle.class)));
+ assertThat(store.getAllAndLock()).hasSize(1);
+ assertThat(store.getAndLock(key)).isNotNull();
// First remove attempt should fail when we're discarding the underlying
// state.
- final Exception exception =
- assertThrows(
- Exception.class, () -> store.releaseAndTryRemove(key));
- assertThat(exception, FlinkMatchers.containsCause(discardException));
+ assertThatThrownBy(() -> store.releaseAndTryRemove(key))
+ .satisfies(
+ anyCauseMatches(
+ discardException.getClass(),
+ discardException.getMessage()));
// Now we should see that the node is "soft-deleted". This means it can
// no longer be accessed by the get methods, but the underlying state
// still exists.
- assertThat(store.getAllAndLock().size(), is(0));
- assertThrows(Exception.class, () -> store.getAndLock(key));
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(0));
- assertThat(getLeaderConfigMap().getData().containsKey(key), is(true));
+ assertThat(store.getAllAndLock()).hasSize(0);
+ assertThatThrownBy(() -> store.getAndLock(key));
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(0);
+ assertThat(getLeaderConfigMap().getData().containsKey(key)).isTrue();
// Second retry should succeed and remove the underlying state and the
// reference in config map.
- assertThat(store.releaseAndTryRemove(key), is(true));
- assertThat(store.getAllAndLock().size(), is(0));
- assertThrows(Exception.class, () -> store.getAndLock(key));
- assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount(), is(1));
- assertThat(getLeaderConfigMap().getData().containsKey(key), is(false));
+ assertThat(store.releaseAndTryRemove(key)).isTrue();
+ assertThat(store.getAllAndLock()).hasSize(0);
+ assertThatThrownBy(() -> store.getAndLock(key));
+ assertThat(TestingLongStateHandleHelper.getGlobalDiscardCount())
+ .isEqualTo(1);
+ assertThat(getLeaderConfigMap().getData().containsKey(key)).isFalse();
});
}
};
}
@Test
- public void testReleaseAndTryRemoveAllIsIdempotent() throws Exception {
+ void testReleaseAndTryRemoveAllIsIdempotent() throws Exception {
new Context() {
{
runTest(
@@ -1033,58 +1060,55 @@ public class KubernetesStateHandleStoreTest extends KubernetesHighAvailabilityTe
}
// All keys should be retrievable
- assertThat(store.getAllAndLock().size(), is(numKeys));
+ assertThat(store.getAllAndLock()).hasSize(numKeys);
for (int idx = 0; idx < numKeys; idx++) {
- assertThat(
- store.getAndLock(key + "_" + idx),
- is(notNullValue(RetrievableStateHandle.class)));
+ assertThat(store.getAndLock(key + "_" + idx)).isNotNull();
}
// First remove attempt should fail when we're discarding the underlying
// state.
- final Exception exception =
- assertThrows(Exception.class, store::releaseAndTryRemoveAll);
- assertThat(exception, FlinkMatchers.containsCause(discardException));
+ assertThatThrownBy(store::releaseAndTryRemoveAll)
+ .satisfies(
+ anyCauseMatches(
+ discardException.getClass(),
+ discardException.getMessage()));
// Now we should see that the all nodes are "soft-deleted". This means
// it can no longer be accessed by the get methods, but the underlying
// state still exists.
- assertThat(store.getAllAndLock().size(), is(0));
+ assertThat(store.getAllAndLock()).hasSize(0);
for (int idx = 0; idx < numKeys; idx++) {
final String indexKey = key + "_" + idx;
- assertThrows(Exception.class, () -> store.getAndLock(indexKey));
- assertThat(
- getLeaderConfigMap().getData().containsKey(indexKey),
- is(true));
+ assertThatThrownBy(() -> store.getAndLock(indexKey));
+ assertThat(getLeaderConfigMap().getData()).containsKey(indexKey);
}
// Half of the state handles should have been discarded.
assertThat(
- states.stream()
- .filter(
- TestingLongStateHandleHelper.LongStateHandle
- ::isDiscarded)
- .count(),
- is((long) numKeys / 2));
+ states.stream()
+ .filter(
+ TestingLongStateHandleHelper
+ .LongStateHandle
+ ::isDiscarded))
+ .hasSize(numKeys / 2);
// Second retry should succeed and remove the underlying state and the
// reference in config map.
store.releaseAndTryRemoveAll();
- assertThat(store.getAllAndLock().size(), is(0));
+ assertThat(store.getAllAndLock()).hasSize(0);
for (int idx = 0; idx < numKeys; idx++) {
final String indexKey = key + "_" + idx;
- assertThrows(Exception.class, () -> store.getAndLock(indexKey));
- assertThat(
- getLeaderConfigMap().getData().containsKey(indexKey),
- is(false));
+ assertThatThrownBy(() -> store.getAndLock(indexKey));
+ assertThat(getLeaderConfigMap().getData())
+ .doesNotContainKey(indexKey);
}
// All handles should have been discarded.
assertThat(
- states.stream()
- .filter(
- TestingLongStateHandleHelper.LongStateHandle
- ::isDiscarded)
- .count(),
- is((long) numKeys));
+ states.stream()
+ .filter(
+ TestingLongStateHandleHelper
+ .LongStateHandle
+ ::isDiscarded))
+ .hasSize(numKeys);
});
}
};
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesTestFixture.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesTestFixture.java
index 9545ea53e58..7375293a0b8 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesTestFixture.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/highavailability/KubernetesTestFixture.java
@@ -40,9 +40,7 @@ import java.util.concurrent.TimeUnit;
import static org.apache.flink.kubernetes.kubeclient.resources.KubernetesLeaderElector.LEADER_ANNOTATION_KEY;
import static org.apache.flink.kubernetes.utils.Constants.LABEL_CONFIGMAP_TYPE_HIGH_AVAILABILITY;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.greaterThanOrEqualTo;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Test fixture for Kubernetes tests that sets up a mock {@link FlinkKubeClient}. */
class KubernetesTestFixture {
@@ -112,7 +110,7 @@ class KubernetesTestFixture {
KubernetesConfigMap getLeaderConfigMap() {
final Optional<KubernetesConfigMap> configMapOpt =
flinkKubeClient.getConfigMap(leaderConfigmapName);
- assertThat(configMapOpt.isPresent(), is(true));
+ assertThat(configMapOpt).isPresent();
return configMapOpt.get();
}
@@ -124,13 +122,13 @@ class KubernetesTestFixture {
FlinkKubeClient.WatchCallbackHandler<KubernetesConfigMap> getLeaderElectionConfigMapCallback()
throws Exception {
- assertThat(configMapCallbackFutures.size(), is(greaterThanOrEqualTo(1)));
+ assertThat(configMapCallbackFutures).hasSizeGreaterThanOrEqualTo(1);
return configMapCallbackFutures.get(0).get(TIMEOUT, TimeUnit.MILLISECONDS);
}
FlinkKubeClient.WatchCallbackHandler<KubernetesConfigMap> getLeaderRetrievalConfigMapCallback()
throws Exception {
- assertThat(configMapCallbackFutures.size(), is(2));
+ assertThat(configMapCallbackFutures).hasSize(2);
return configMapCallbackFutures.get(1).get(TIMEOUT, TimeUnit.MILLISECONDS);
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientITCase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientITCase.java
index 5817ec2b1a8..9adb7253b36 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientITCase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientITCase.java
@@ -18,17 +18,16 @@
package org.apache.flink.kubernetes.kubeclient;
-import org.apache.flink.kubernetes.KubernetesResource;
+import org.apache.flink.kubernetes.KubernetesExtension;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
-import org.apache.flink.util.TestLogger;
import org.apache.flink.util.concurrent.ExecutorThreadFactory;
import org.apache.flink.util.concurrent.FutureUtils;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.ArrayList;
import java.util.HashMap;
@@ -40,17 +39,16 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.everyItem;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* IT Tests for {@link org.apache.flink.kubernetes.kubeclient.Fabric8FlinkKubeClient} with real K8s
* server and client.
*/
-public class Fabric8FlinkKubeClientITCase extends TestLogger {
+class Fabric8FlinkKubeClientITCase {
- @ClassRule public static KubernetesResource kubernetesResource = new KubernetesResource();
+ @RegisterExtension
+ private static final KubernetesExtension kubernetesExtension = new KubernetesExtension();
private static final String TEST_CONFIG_MAP_NAME = "test-config-map";
@@ -69,9 +67,9 @@ public class Fabric8FlinkKubeClientITCase extends TestLogger {
private ExecutorService executorService;
- @Before
- public void setup() throws Exception {
- flinkKubeClient = kubernetesResource.getFlinkKubeClient();
+ @BeforeEach
+ void setup() throws Exception {
+ flinkKubeClient = kubernetesExtension.getFlinkKubeClient();
flinkKubeClient
.createConfigMap(
new KubernetesConfigMap(
@@ -87,8 +85,8 @@ public class Fabric8FlinkKubeClientITCase extends TestLogger {
data.size(), new ExecutorThreadFactory("test-leader-io"));
}
- @After
- public void teardown() throws Exception {
+ @AfterEach
+ void teardown() throws Exception {
executorService.shutdownNow();
flinkKubeClient.deleteConfigMap(TEST_CONFIG_MAP_NAME).get();
}
@@ -99,7 +97,7 @@ public class Fabric8FlinkKubeClientITCase extends TestLogger {
* could work.
*/
@Test
- public void testCheckAndUpdateConfigMapConcurrently() throws Exception {
+ void testCheckAndUpdateConfigMapConcurrently() throws Exception {
// Start multiple instances to update ConfigMap concurrently
final List<CompletableFuture<Void>> futures = new ArrayList<>();
final int target = 10;
@@ -130,7 +128,7 @@ public class Fabric8FlinkKubeClientITCase extends TestLogger {
return Optional.of(configMap);
})
.join();
- assertThat(updated, is(true));
+ assertThat(updated).isTrue();
try {
// Simulate the update interval
Thread.sleep((long) (updateIntervalMs * Math.random()));
@@ -145,7 +143,7 @@ public class Fabric8FlinkKubeClientITCase extends TestLogger {
// All the value should be increased exactly to the target
final Optional<KubernetesConfigMap> configMapOpt =
flinkKubeClient.getConfigMap(TEST_CONFIG_MAP_NAME);
- assertThat(configMapOpt.isPresent(), is(true));
- assertThat(configMapOpt.get().getData().values(), everyItem(is(String.valueOf(target))));
+ assertThat(configMapOpt).isPresent();
+ assertThat(configMapOpt.get().getData().values()).containsOnly(String.valueOf(target));
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientTest.java
index da6b325f3a8..412e42efa27 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/Fabric8FlinkKubeClientTest.java
@@ -23,7 +23,6 @@ import org.apache.flink.configuration.BlobServerOptions;
import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.JobManagerOptions;
import org.apache.flink.configuration.RestOptions;
-import org.apache.flink.core.testutils.FlinkMatchers;
import org.apache.flink.kubernetes.KubernetesClientTestBase;
import org.apache.flink.kubernetes.KubernetesTestUtils;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
@@ -38,7 +37,6 @@ import org.apache.flink.kubernetes.kubeclient.resources.KubernetesPod;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesService;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.runtime.persistence.PossibleInconsistentStateException;
-import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.concurrent.ExecutorThreadFactory;
import io.fabric8.kubernetes.api.model.ConfigMap;
@@ -49,7 +47,7 @@ import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.apps.Deployment;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -57,24 +55,19 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
+import static org.apache.flink.core.testutils.FlinkAssertions.anyCauseMatches;
+import static org.apache.flink.core.testutils.FlinkAssertions.assertThatChainOfCauses;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOG4J_NAME;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOGBACK_NAME;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.isIn;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.fail;
/** Tests for Fabric implementation of {@link FlinkKubeClient}. */
public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
@@ -143,20 +136,20 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
}
@Test
- public void testCreateFlinkMasterComponent() throws Exception {
+ void testCreateFlinkMasterComponent() throws Exception {
flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);
final List<Deployment> resultedDeployments =
kubeClient.apps().deployments().inNamespace(NAMESPACE).list().getItems();
- assertEquals(1, resultedDeployments.size());
+ assertThat(resultedDeployments).hasSize(1);
final List<ConfigMap> resultedConfigMaps =
kubeClient.configMaps().inNamespace(NAMESPACE).list().getItems();
- assertEquals(1, resultedConfigMaps.size());
+ assertThat(resultedConfigMaps).hasSize(1);
final List<Service> resultedServices =
kubeClient.services().inNamespace(NAMESPACE).list().getItems();
- assertEquals(2, resultedServices.size());
+ assertThat(resultedServices).hasSize(2);
testOwnerReferenceSetting(resultedDeployments.get(0), resultedConfigMaps);
testOwnerReferenceSetting(resultedDeployments.get(0), resultedServices);
@@ -168,14 +161,14 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
resource -> {
List<OwnerReference> ownerReferences =
resource.getMetadata().getOwnerReferences();
- assertEquals(1, ownerReferences.size());
- assertEquals(
- ownerReference.getMetadata().getUid(), ownerReferences.get(0).getUid());
+ assertThat(ownerReferences).hasSize(1);
+ assertThat(ownerReferences.get(0).getUid())
+ .isEqualTo(ownerReference.getMetadata().getUid());
});
}
@Test
- public void testUpdateRestServicePort() throws Exception {
+ void testUpdateRestServicePort() throws Exception {
this.flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);
final int expectedRestPort = 9081;
@@ -189,11 +182,11 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
final int updatedRestPort =
getServiceTargetPort(
CLUSTER_ID + Constants.FLINK_REST_SERVICE_SUFFIX, Constants.REST_PORT_NAME);
- assertThat(updatedRestPort, is(expectedRestPort));
+ assertThat(updatedRestPort).isEqualTo(expectedRestPort);
}
@Test
- public void testUpdateInternalServicePort() throws Exception {
+ void testUpdateInternalServicePort() throws Exception {
this.flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);
final int expectedBlobPort = 9082;
@@ -206,7 +199,7 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
.get();
final int updatedBlobPort =
getServiceTargetPort(CLUSTER_ID, Constants.BLOB_SERVER_PORT_NAME);
- assertThat(updatedBlobPort, is(expectedBlobPort));
+ assertThat(updatedBlobPort).isEqualTo(expectedBlobPort);
}
private int getServiceTargetPort(String serviceName, String portName) {
@@ -215,12 +208,12 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
.filter(servicePort -> servicePort.getName().equalsIgnoreCase(portName))
.map(servicePort -> servicePort.getTargetPort().getIntVal())
.collect(Collectors.toList());
- assertThat(ports.size(), is(1));
+ assertThat(ports).hasSize(1);
return ports.get(0);
}
@Test
- public void testCreateFlinkTaskManagerPod() throws Exception {
+ void testCreateFlinkTaskManagerPod() throws Exception {
this.flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);
final KubernetesPod kubernetesPod = buildKubernetesPod("mock-task-manager-pod");
@@ -229,21 +222,21 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
final Pod resultTaskManagerPod =
this.kubeClient.pods().inNamespace(NAMESPACE).withName(TASKMANAGER_POD_NAME).get();
- assertEquals(
- this.kubeClient
- .apps()
- .deployments()
- .inNamespace(NAMESPACE)
- .list()
- .getItems()
- .get(0)
- .getMetadata()
- .getUid(),
- resultTaskManagerPod.getMetadata().getOwnerReferences().get(0).getUid());
+ assertThat(resultTaskManagerPod.getMetadata().getOwnerReferences().get(0).getUid())
+ .isEqualTo(
+ this.kubeClient
+ .apps()
+ .deployments()
+ .inNamespace(NAMESPACE)
+ .list()
+ .getItems()
+ .get(0)
+ .getMetadata()
+ .getUid());
}
@Test
- public void testCreateTwoTaskManagerPods() throws Exception {
+ void testCreateTwoTaskManagerPods() throws Exception {
flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);
flinkKubeClient.createTaskManagerPod(buildKubernetesPod("mock-task-manager-pod1")).get();
mockGetDeploymentWithError();
@@ -268,7 +261,7 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
}
@Test
- public void testStopPod() throws ExecutionException, InterruptedException {
+ void testStopPod() throws ExecutionException, InterruptedException {
final String podName = "pod-for-delete";
final Pod pod =
new PodBuilder()
@@ -280,47 +273,48 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
.build();
this.kubeClient.pods().inNamespace(NAMESPACE).create(pod);
- assertNotNull(this.kubeClient.pods().inNamespace(NAMESPACE).withName(podName).get());
+ assertThat(this.kubeClient.pods().inNamespace(NAMESPACE).withName(podName).get())
+ .isNotNull();
this.flinkKubeClient.stopPod(podName).get();
- assertNull(this.kubeClient.pods().inNamespace(NAMESPACE).withName(podName).get());
+ assertThat(this.kubeClient.pods().inNamespace(NAMESPACE).withName(podName).get()).isNull();
}
@Test
- public void testServiceLoadBalancerWithNoIP() {
+ void testServiceLoadBalancerWithNoIP() {
final String hostName = "test-host-name";
mockExpectedServiceFromServerSide(buildExternalServiceWithLoadBalancer(hostName, ""));
final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
- assertThat(resultEndpoint.isPresent(), is(true));
- assertThat(resultEndpoint.get().getAddress(), is(hostName));
- assertThat(resultEndpoint.get().getPort(), is(REST_PORT));
+ assertThat(resultEndpoint).isPresent();
+ assertThat(resultEndpoint.get().getAddress()).isEqualTo(hostName);
+ assertThat(resultEndpoint.get().getPort()).isEqualTo(REST_PORT);
}
@Test
- public void testServiceLoadBalancerEmptyHostAndIP() {
+ void testServiceLoadBalancerEmptyHostAndIP() {
mockExpectedServiceFromServerSide(buildExternalServiceWithLoadBalancer("", ""));
final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
- assertThat(resultEndpoint.isPresent(), is(false));
+ assertThat(resultEndpoint).isNotPresent();
}
@Test
- public void testServiceLoadBalancerNullHostAndIP() {
+ void testServiceLoadBalancerNullHostAndIP() {
mockExpectedServiceFromServerSide(buildExternalServiceWithLoadBalancer(null, null));
final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
- assertThat(resultEndpoint.isPresent(), is(false));
+ assertThat(resultEndpoint).isNotPresent();
}
@Test
- public void testNodePortServiceWithInternalIP() {
+ void testNodePortServiceWithInternalIP() {
testNodePortService(KubernetesConfigOptions.NodePortAddressType.InternalIP);
}
@Test
- public void testNodePortServiceWithExternalIP() {
+ void testNodePortServiceWithExternalIP() {
testNodePortService(KubernetesConfigOptions.NodePortAddressType.ExternalIP);
}
@@ -342,7 +336,7 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
kubeClient,
org.apache.flink.util.concurrent.Executors.newDirectExecutorService())) {
final Optional<Endpoint> resultEndpoint = localClient.getRestEndpoint(CLUSTER_ID);
- assertThat(resultEndpoint.isPresent(), is(true));
+ assertThat(resultEndpoint).isPresent();
final List<String> expectedIps;
switch (addressType) {
case InternalIP:
@@ -361,138 +355,124 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
throw new IllegalArgumentException(
String.format("Unexpected address type %s.", addressType));
}
- assertThat(resultEndpoint.get().getAddress(), isIn(expectedIps));
- assertThat(resultEndpoint.get().getPort(), is(NODE_PORT));
+ assertThat(resultEndpoint.get().getAddress()).isIn(expectedIps);
+ assertThat(resultEndpoint.get().getPort()).isEqualTo(NODE_PORT);
}
}
@Test
- public void testNodePortServiceWithNoMatchingIP() {
+ void testNodePortServiceWithNoMatchingIP() {
mockExpectedServiceFromServerSide(buildExternalServiceWithNodePort());
- assertFalse(flinkKubeClient.getRestEndpoint(CLUSTER_ID).isPresent());
+ assertThat(flinkKubeClient.getRestEndpoint(CLUSTER_ID)).isNotPresent();
}
@Test
- public void testClusterIPService() {
+ void testClusterIPService() {
mockExpectedServiceFromServerSide(buildExternalServiceWithClusterIP());
final Optional<Endpoint> resultEndpoint = flinkKubeClient.getRestEndpoint(CLUSTER_ID);
- assertThat(resultEndpoint.isPresent(), is(true));
- assertThat(
- resultEndpoint.get().getAddress(),
- is(
+ assertThat(resultEndpoint).isPresent();
+ assertThat(resultEndpoint.get().getAddress())
+ .isEqualTo(
ExternalServiceDecorator.getNamespacedExternalServiceName(
- CLUSTER_ID, NAMESPACE)));
- assertThat(resultEndpoint.get().getPort(), is(REST_PORT));
+ CLUSTER_ID, NAMESPACE));
+ assertThat(resultEndpoint.get().getPort()).isEqualTo(REST_PORT);
}
@Test
- public void testStopAndCleanupCluster() throws Exception {
+ void testStopAndCleanupCluster() throws Exception {
this.flinkKubeClient.createJobManagerComponent(this.kubernetesJobManagerSpecification);
final KubernetesPod kubernetesPod = buildKubernetesPod(TASKMANAGER_POD_NAME);
this.flinkKubeClient.createTaskManagerPod(kubernetesPod).get();
- assertEquals(
- 1,
- this.kubeClient
- .apps()
- .deployments()
- .inNamespace(NAMESPACE)
- .list()
- .getItems()
- .size());
- assertEquals(
- 1, this.kubeClient.configMaps().inNamespace(NAMESPACE).list().getItems().size());
- assertEquals(2, this.kubeClient.services().inNamespace(NAMESPACE).list().getItems().size());
- assertEquals(1, this.kubeClient.pods().inNamespace(NAMESPACE).list().getItems().size());
+ assertThat(
+ this.kubeClient
+ .apps()
+ .deployments()
+ .inNamespace(NAMESPACE)
+ .list()
+ .getItems()
+ .size())
+ .isEqualTo(1);
+ assertThat(this.kubeClient.configMaps().inNamespace(NAMESPACE).list().getItems().size())
+ .isEqualTo(1);
+ assertThat(this.kubeClient.services().inNamespace(NAMESPACE).list().getItems()).hasSize(2);
+ assertThat(this.kubeClient.pods().inNamespace(NAMESPACE).list().getItems()).hasSize(1);
this.flinkKubeClient.stopAndCleanupCluster(CLUSTER_ID);
- assertTrue(
- this.kubeClient
- .apps()
- .deployments()
- .inNamespace(NAMESPACE)
- .list()
- .getItems()
- .isEmpty());
+ assertThat(this.kubeClient.apps().deployments().inNamespace(NAMESPACE).list().getItems())
+ .isEmpty();
}
@Test
- public void testCreateConfigMap() throws Exception {
+ void testCreateConfigMap() throws Exception {
final KubernetesConfigMap configMap = buildTestingConfigMap();
this.flinkKubeClient.createConfigMap(configMap).get();
final Optional<KubernetesConfigMap> currentOpt =
this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
- assertThat(currentOpt.isPresent(), is(true));
- assertThat(
- currentOpt.get().getData().get(TESTING_CONFIG_MAP_KEY),
- is(TESTING_CONFIG_MAP_VALUE));
+ assertThat(currentOpt)
+ .hasValueSatisfying(
+ map ->
+ assertThat(map.getData())
+ .containsEntry(
+ TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_VALUE));
}
@Test
- public void testCreateConfigMapAlreadyExisting() throws Exception {
+ void testCreateConfigMapAlreadyExisting() throws Exception {
final KubernetesConfigMap configMap = buildTestingConfigMap();
this.flinkKubeClient.createConfigMap(configMap).get();
mockCreateConfigMapAlreadyExisting(configMap.getInternalResource());
configMap.getData().put(TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_NEW_VALUE);
- try {
- this.flinkKubeClient.createConfigMap(configMap).get();
- fail("Overwrite an already existing config map should fail with an exception.");
- } catch (Exception ex) {
- final String errorMsg = "Failed to create ConfigMap " + TESTING_CONFIG_MAP_NAME;
- assertThat(ex, FlinkMatchers.containsMessage(errorMsg));
- }
+
+ final String errorMsg = "Failed to create ConfigMap " + TESTING_CONFIG_MAP_NAME;
+ assertThatThrownBy(
+ () -> this.flinkKubeClient.createConfigMap(configMap).get(),
+ "Overwrite an already existing config map should fail with an exception.")
+ .satisfies(anyCauseMatches(errorMsg));
+
// Create failed we should still get the old value
final Optional<KubernetesConfigMap> currentOpt =
this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
- assertThat(currentOpt.isPresent(), is(true));
- assertThat(
- currentOpt.get().getData().get(TESTING_CONFIG_MAP_KEY),
- is(TESTING_CONFIG_MAP_VALUE));
+ assertThat(currentOpt).isPresent();
+ assertThat(currentOpt.get().getData())
+ .containsEntry(TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_VALUE);
}
@Test
- public void testDeleteConfigMapByLabels() throws Exception {
+ void testDeleteConfigMapByLabels() throws Exception {
this.flinkKubeClient.createConfigMap(buildTestingConfigMap()).get();
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(true));
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isPresent();
this.flinkKubeClient.deleteConfigMapsByLabels(TESTING_LABELS).get();
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isNotPresent();
}
@Test
- public void testDeleteNotExistingConfigMapByLabels() throws Exception {
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
+ void testDeleteNotExistingConfigMapByLabels() throws Exception {
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isNotPresent();
this.flinkKubeClient.deleteConfigMapsByLabels(TESTING_LABELS).get();
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isNotPresent();
}
@Test
- public void testDeleteConfigMapByName() throws Exception {
+ void testDeleteConfigMapByName() throws Exception {
this.flinkKubeClient.createConfigMap(buildTestingConfigMap()).get();
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(true));
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isPresent();
this.flinkKubeClient.deleteConfigMap(TESTING_CONFIG_MAP_NAME).get();
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isNotPresent();
}
@Test
- public void testDeleteNotExistingConfigMapByName() throws Exception {
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
+ void testDeleteNotExistingConfigMapByName() throws Exception {
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isNotPresent();
this.flinkKubeClient.deleteConfigMap(TESTING_CONFIG_MAP_NAME).get();
- assertThat(
- this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME).isPresent(), is(false));
+ assertThat(this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME)).isNotPresent();
}
@Test
- public void testCheckAndUpdateConfigMap() throws Exception {
+ void testCheckAndUpdateConfigMap() throws Exception {
this.flinkKubeClient.createConfigMap(buildTestingConfigMap());
// Checker pass
@@ -508,18 +488,17 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
return Optional.of(c);
})
.get();
- assertThat(updated, is(true));
+ assertThat(updated).isTrue();
final Optional<KubernetesConfigMap> configMapOpt =
this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
- assertThat(configMapOpt.isPresent(), is(true));
- assertThat(
- configMapOpt.get().getData().get(TESTING_CONFIG_MAP_KEY),
- is(TESTING_CONFIG_MAP_NEW_VALUE));
+ assertThat(configMapOpt).isPresent();
+ assertThat(configMapOpt.get().getData())
+ .containsEntry(TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_NEW_VALUE);
}
@Test
- public void testCheckAndUpdateConfigMapWithEmptyResult() throws Exception {
+ void testCheckAndUpdateConfigMapWithEmptyResult() throws Exception {
this.flinkKubeClient.createConfigMap(buildTestingConfigMap());
// Checker not pass and return empty result
@@ -527,41 +506,37 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
this.flinkKubeClient
.checkAndUpdateConfigMap(TESTING_CONFIG_MAP_NAME, c -> Optional.empty())
.get();
- assertThat(updated, is(false));
+ assertThat(updated).isFalse();
final Optional<KubernetesConfigMap> configMapOpt =
this.flinkKubeClient.getConfigMap(TESTING_CONFIG_MAP_NAME);
- assertThat(configMapOpt.isPresent(), is(true));
- assertThat(
- configMapOpt.get().getData().get(TESTING_CONFIG_MAP_KEY),
- is(TESTING_CONFIG_MAP_VALUE));
+ assertThat(configMapOpt).isPresent();
+ assertThat(configMapOpt.get().getData())
+ .containsEntry(TESTING_CONFIG_MAP_KEY, TESTING_CONFIG_MAP_VALUE);
}
@Test
- public void testCheckAndUpdateConfigMapWhenConfigMapNotExist() {
- try {
- final CompletableFuture<Boolean> future =
- this.flinkKubeClient.checkAndUpdateConfigMap(
- TESTING_CONFIG_MAP_NAME, c -> Optional.empty());
- future.get();
- fail(
- "CheckAndUpdateConfigMap should fail with an exception when the ConfigMap does not exist.");
- } catch (Exception ex) {
- final String errMsg =
- "Cannot retry checkAndUpdateConfigMap with configMap "
- + TESTING_CONFIG_MAP_NAME
- + " because it does not exist.";
- assertThat(ex, FlinkMatchers.containsMessage(errMsg));
- // Should not retry when ConfigMap does not exist.
- assertThat(
- ex,
- FlinkMatchers.containsMessage(
- "Stopped retrying the operation because the error is not retryable."));
- }
+ void testCheckAndUpdateConfigMapWhenConfigMapNotExist() {
+ final String errMsg =
+ "Cannot retry checkAndUpdateConfigMap with configMap "
+ + TESTING_CONFIG_MAP_NAME
+ + " because it does not exist.";
+ assertThatThrownBy(
+ () ->
+ this.flinkKubeClient
+ .checkAndUpdateConfigMap(
+ TESTING_CONFIG_MAP_NAME, c -> Optional.empty())
+ .get(),
+ "CheckAndUpdateConfigMap should fail with an exception when the ConfigMap does not exist.")
+ .satisfies(anyCauseMatches(errMsg))
+ .satisfies(
+ // Should not retry when ConfigMap does not exist.
+ anyCauseMatches(
+ "Stopped retrying the operation because the error is not retryable."));
}
@Test
- public void testCheckAndUpdateConfigMapWhenGetConfigMapFailed() throws Exception {
+ void testCheckAndUpdateConfigMapWhenGetConfigMapFailed() throws Exception {
final int configuredRetries =
flinkConfig.getInteger(
KubernetesConfigOptions.KUBERNETES_TRANSACTIONAL_OPERATION_MAX_RETRIES);
@@ -571,35 +546,33 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
mockGetConfigMapFailed(configMap.getInternalResource());
final int initialRequestCount = server.getRequestCount();
- try {
- this.flinkKubeClient
- .checkAndUpdateConfigMap(
- TESTING_CONFIG_MAP_NAME,
- c -> {
- throw new AssertionError(
- "The replace operation should have never been triggered.");
- })
- .get();
- fail(
- "checkAndUpdateConfigMap should fail without a PossibleInconsistentStateException being the cause when number of retries has been exhausted.");
- } catch (Exception ex) {
- assertThat(
- ex,
- FlinkMatchers.containsMessage(
- "Could not complete the "
- + "operation. Number of retries has been exhausted."));
- final int actualRetryCount = server.getRequestCount() - initialRequestCount;
- assertThat(actualRetryCount, is(configuredRetries + 1));
- assertThat(
- "An error while retrieving the ConfigMap should not cause a PossibleInconsistentStateException.",
- ExceptionUtils.findThrowable(ex, PossibleInconsistentStateException.class)
- .isPresent(),
- is(false));
- }
+ assertThatThrownBy(
+ () ->
+ this.flinkKubeClient
+ .checkAndUpdateConfigMap(
+ TESTING_CONFIG_MAP_NAME,
+ c -> {
+ throw new AssertionError(
+ "The replace operation should have never been triggered.");
+ })
+ .get(),
+ "checkAndUpdateConfigMap should fail without a PossibleInconsistentStateException being the cause when number of retries has been exhausted.")
+ .satisfies(
+ anyCauseMatches(
+ "Could not complete the operation. Number of retries has been exhausted."))
+ .satisfies(
+ cause ->
+ assertThatChainOfCauses(cause)
+ .withFailMessage(
+ "An error while retrieving the ConfigMap should not cause a PossibleInconsistentStateException.")
+ .isNotOfAnyClassIn(
+ PossibleInconsistentStateException.class));
+ final int actualRetryCount = server.getRequestCount() - initialRequestCount;
+ assertThat(actualRetryCount).isEqualTo(configuredRetries + 1);
}
@Test
- public void testCheckAndUpdateConfigMapWhenReplaceConfigMapFailed() throws Exception {
+ void testCheckAndUpdateConfigMapWhenReplaceConfigMapFailed() throws Exception {
final int configuredRetries =
flinkConfig.getInteger(
KubernetesConfigOptions.KUBERNETES_TRANSACTIONAL_OPERATION_MAX_RETRIES);
@@ -609,41 +582,33 @@ public class Fabric8FlinkKubeClientTest extends KubernetesClientTestBase {
mockReplaceConfigMapFailed(configMap.getInternalResource());
final AtomicInteger retries = new AtomicInteger(0);
- try {
- this.flinkKubeClient
- .checkAndUpdateConfigMap(
- TESTING_CONFIG_MAP_NAME,
- c -> {
- retries.incrementAndGet();
- return Optional.of(configMap);
- })
- .get();
- fail(
- "checkAndUpdateConfigMap should fail due to a PossibleInconsistentStateException when number of retries has been exhausted.");
- } catch (Exception ex) {
- assertThat(
- ex,
- FlinkMatchers.containsMessage(
- "Could not complete the "
- + "operation. Number of retries has been exhausted."));
- assertThat(retries.get(), is(configuredRetries + 1));
-
- assertThat(
- "An error while replacing the ConfigMap should cause an PossibleInconsistentStateException.",
- ExceptionUtils.findThrowable(ex, PossibleInconsistentStateException.class)
- .isPresent(),
- is(true));
- }
+ assertThatThrownBy(
+ () ->
+ this.flinkKubeClient
+ .checkAndUpdateConfigMap(
+ TESTING_CONFIG_MAP_NAME,
+ c -> {
+ retries.incrementAndGet();
+ return Optional.of(configMap);
+ })
+ .get(),
+ "checkAndUpdateConfigMap should fail due to a PossibleInconsistentStateException when number of retries has been exhausted.")
+ .satisfies(
+ anyCauseMatches(
+ "Could not complete the "
+ + "operation. Number of retries has been exhausted."))
+ .satisfies(anyCauseMatches(PossibleInconsistentStateException.class));
+ assertThat(retries.get()).isEqualTo(configuredRetries + 1);
}
@Test
- public void testIOExecutorShouldBeShutDownWhenFlinkKubeClientClosed() {
+ void testIOExecutorShouldBeShutDownWhenFlinkKubeClientClosed() {
final ExecutorService executorService =
Executors.newFixedThreadPool(2, new ExecutorThreadFactory("Testing-IO"));
final FlinkKubeClient flinkKubeClient =
new Fabric8FlinkKubeClient(flinkConfig, kubeClient, executorService);
flinkKubeClient.close();
- assertThat(executorService.isShutdown(), is(true));
+ assertThat(executorService.isShutdown()).isTrue();
}
private KubernetesConfigMap buildTestingConfigMap() {
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdJobManagerDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdJobManagerDecoratorTest.java
index 94f56c52d81..21d6a121617 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdJobManagerDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdJobManagerDecoratorTest.java
@@ -26,19 +26,15 @@ import org.apache.flink.kubernetes.kubeclient.KubernetesJobManagerTestBase;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.kubernetes.utils.KubernetesUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** General tests for the {@link CmdJobManagerDecorator}. */
-public class CmdJobManagerDecoratorTest extends KubernetesJobManagerTestBase {
+class CmdJobManagerDecoratorTest extends KubernetesJobManagerTestBase {
private CmdJobManagerDecorator cmdJobManagerDecorator;
@@ -50,40 +46,40 @@ public class CmdJobManagerDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testContainerIsDecorated() {
+ void testContainerIsDecorated() {
flinkConfig.set(DeploymentOptions.TARGET, KubernetesDeploymentTarget.SESSION.getName());
final FlinkPod resultFlinkPod = cmdJobManagerDecorator.decorateFlinkPod(baseFlinkPod);
- assertThat(
- resultFlinkPod.getPodWithoutMainContainer(),
- is(equalTo(baseFlinkPod.getPodWithoutMainContainer())));
- assertThat(
- resultFlinkPod.getMainContainer(), not(equalTo(baseFlinkPod.getMainContainer())));
+ assertThat(resultFlinkPod.getPodWithoutMainContainer())
+ .isEqualTo(baseFlinkPod.getPodWithoutMainContainer());
+ assertThat(resultFlinkPod.getMainContainer()).isNotEqualTo(baseFlinkPod.getMainContainer());
}
@Test
- public void testSessionClusterCommandsAndArgs() {
+ void testSessionClusterCommandsAndArgs() {
testJobManagerCommandsAndArgs(KubernetesDeploymentTarget.SESSION.getName());
}
@Test
- public void testApplicationClusterCommandsAndArgs() {
+ void testApplicationClusterCommandsAndArgs() {
testJobManagerCommandsAndArgs(KubernetesDeploymentTarget.APPLICATION.getName());
}
- @Test(expected = IllegalArgumentException.class)
+ @Test
public void testUnsupportedDeploymentTargetShouldFail() {
- testJobManagerCommandsAndArgs("unsupported-deployment-target");
+ assertThatThrownBy(() -> testJobManagerCommandsAndArgs("unsupported-deployment-target"))
+ .isInstanceOf(IllegalArgumentException.class);
}
private void testJobManagerCommandsAndArgs(String target) {
flinkConfig.set(DeploymentOptions.TARGET, target);
final FlinkPod resultFlinkPod = cmdJobManagerDecorator.decorateFlinkPod(baseFlinkPod);
final String entryCommand = flinkConfig.get(KubernetesConfigOptions.KUBERNETES_ENTRY_PATH);
- assertThat(
- resultFlinkPod.getMainContainer().getCommand(), containsInAnyOrder(entryCommand));
+ assertThat(resultFlinkPod.getMainContainer().getCommand())
+ .containsExactlyInAnyOrder(entryCommand);
List<String> flinkCommands =
KubernetesUtils.getStartCommandWithBashWrapper(
Constants.KUBERNETES_JOB_MANAGER_SCRIPT_PATH + " " + target);
- assertThat(resultFlinkPod.getMainContainer().getArgs(), contains(flinkCommands.toArray()));
+ assertThat(resultFlinkPod.getMainContainer().getArgs())
+ .containsExactlyElementsOf(flinkCommands);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdTaskManagerDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdTaskManagerDecoratorTest.java
index 77ac65ddc2b..91b60563faa 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdTaskManagerDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/CmdTaskManagerDecoratorTest.java
@@ -30,15 +30,10 @@ import org.junit.Test;
import java.util.List;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the{@link CmdTaskManagerDecorator}. */
-public class CmdTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase {
+class CmdTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase {
private String mainClassArgs;
@@ -56,21 +51,19 @@ public class CmdTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase {
}
@Test
- public void testContainerIsDecorated() {
+ void testContainerIsDecorated() {
final FlinkPod resultFlinkPod = cmdTaskManagerDecorator.decorateFlinkPod(this.baseFlinkPod);
- assertThat(
- resultFlinkPod.getPodWithoutMainContainer(),
- is(equalTo(baseFlinkPod.getPodWithoutMainContainer())));
- assertThat(
- resultFlinkPod.getMainContainer(), not(equalTo(baseFlinkPod.getMainContainer())));
+ assertThat(resultFlinkPod.getPodWithoutMainContainer())
+ .isEqualTo(baseFlinkPod.getPodWithoutMainContainer());
+ assertThat(resultFlinkPod.getMainContainer()).isNotEqualTo(baseFlinkPod.getMainContainer());
}
@Test
- public void testTaskManagerStartCommandsAndArgs() {
+ void testTaskManagerStartCommandsAndArgs() {
final FlinkPod resultFlinkPod = cmdTaskManagerDecorator.decorateFlinkPod(baseFlinkPod);
final String entryCommand = flinkConfig.get(KubernetesConfigOptions.KUBERNETES_ENTRY_PATH);
- assertThat(
- resultFlinkPod.getMainContainer().getCommand(), containsInAnyOrder(entryCommand));
+ assertThat(resultFlinkPod.getMainContainer().getCommand())
+ .containsExactlyInAnyOrder(entryCommand);
List<String> flinkCommands =
KubernetesUtils.getStartCommandWithBashWrapper(
Constants.KUBERNETES_TASK_MANAGER_SCRIPT_PATH
@@ -78,18 +71,18 @@ public class CmdTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase {
+ DYNAMIC_PROPERTIES
+ " "
+ mainClassArgs);
- assertThat(resultFlinkPod.getMainContainer().getArgs(), contains(flinkCommands.toArray()));
+ assertThat(resultFlinkPod.getMainContainer().getArgs())
+ .containsExactlyElementsOf(flinkCommands);
}
@Test
- public void testTaskManagerJvmMemOptsEnv() {
+ void testTaskManagerJvmMemOptsEnv() {
final FlinkPod resultFlinkPod = cmdTaskManagerDecorator.decorateFlinkPod(baseFlinkPod);
- assertThat(
- resultFlinkPod.getMainContainer().getEnv(),
- contains(
+ assertThat(resultFlinkPod.getMainContainer().getEnv())
+ .containsExactly(
new EnvVarBuilder()
.withName(Constants.ENV_TM_JVM_MEM_OPTS)
.withValue(JVM_MEM_OPTS_ENV)
- .build()));
+ .build());
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/DecoratorWithPodTemplateTestBase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/DecoratorWithPodTemplateTestBase.java
index 549d826728a..9cd4d6e1b48 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/DecoratorWithPodTemplateTestBase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/DecoratorWithPodTemplateTestBase.java
@@ -35,8 +35,7 @@ import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.api.model.Toleration;
-import org.hamcrest.Matchers;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -45,11 +44,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.hasItems;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* Test base of merging and overwriting Kubernetes fields from {@link KubernetesConfigOptions} and
@@ -119,35 +114,28 @@ public abstract class DecoratorWithPodTemplateTestBase extends KubernetesPodTest
protected abstract FlinkPod getResultPod(FlinkPod podTemplate) throws Exception;
@Test
- public void testPodLabelsMerging() {
+ void testPodLabelsMerging() {
final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
expectedLabels.putAll(userLabels);
// The label from pod template
expectedLabels.put("label-key-of-pod-template", "label-value-of-pod-template");
- assertThat(
- new ArrayList<>(
- this.resultPod
- .getPodWithoutMainContainer()
- .getMetadata()
- .getLabels()
- .entrySet()),
- hasItems(expectedLabels.entrySet().toArray()));
+ assertThat(this.resultPod.getPodWithoutMainContainer().getMetadata().getLabels())
+ .containsAllEntriesOf(expectedLabels);
}
@Test
- public void testPodAnnotationsMerging() {
+ void testPodAnnotationsMerging() {
final Map<String, String> expectedAnnotations = new HashMap<>(ANNOTATIONS);
// The annotations from pod template
expectedAnnotations.put(
"annotation-key-of-pod-template", "annotation-value-of-pod-template");
- assertThat(
- this.resultPod.getPodWithoutMainContainer().getMetadata().getAnnotations(),
- is(equalTo(expectedAnnotations)));
+ assertThat(this.resultPod.getPodWithoutMainContainer().getMetadata().getAnnotations())
+ .isEqualTo(expectedAnnotations);
}
@Test
- public void testImagePullSecretsMerging() {
+ void testImagePullSecretsMerging() {
final List<String> expectedPullSecrets = new ArrayList<>(IMAGE_PULL_SECRETS);
// The image pull secret from pod template
expectedPullSecrets.add("image-pull-secret-of-pod-template");
@@ -156,34 +144,32 @@ public abstract class DecoratorWithPodTemplateTestBase extends KubernetesPodTest
.map(LocalObjectReference::getName)
.collect(Collectors.toList());
- assertThat(resultSecrets, containsInAnyOrder(expectedPullSecrets.toArray()));
+ assertThat(resultSecrets).containsExactlyInAnyOrderElementsOf(expectedPullSecrets);
}
@Test
- public void testNodeSelectorMerging() {
+ void testNodeSelectorMerging() {
final Map<String, String> expectedNodeSelectors = new HashMap<>(nodeSelector);
// The node selector from pod template
expectedNodeSelectors.put(
"node-selector-key-of-pod-template", "node-selector-value-of-pod-template");
- assertThat(
- this.resultPod.getPodWithoutMainContainer().getSpec().getNodeSelector(),
- is(equalTo(expectedNodeSelectors)));
+ assertThat(this.resultPod.getPodWithoutMainContainer().getSpec().getNodeSelector())
+ .isEqualTo(expectedNodeSelectors);
}
@Test
- public void testPodTolerationsMerging() {
+ void testPodTolerationsMerging() {
final List<Toleration> expectedTolerations =
Arrays.asList(
new Toleration("NoSchedule", "key1", "Equal", null, "value1"),
// The toleration from pod template
new Toleration("NoExecute", "key2-of-pod-template", "Exists", 6000L, null));
- assertThat(
- this.resultPod.getPodWithoutMainContainer().getSpec().getTolerations(),
- Matchers.containsInAnyOrder(expectedTolerations.toArray()));
+ assertThat(this.resultPod.getPodWithoutMainContainer().getSpec().getTolerations())
+ .containsExactlyInAnyOrderElementsOf(expectedTolerations);
}
@Test
- public void testMainContainerEnvMerging() {
+ void testMainContainerEnvMerging() {
final List<EnvVar> envVars = this.resultPod.getMainContainer().getEnv();
final Map<String, String> actualEnvs = new HashMap<>();
envVars.forEach(env -> actualEnvs.put(env.getName(), env.getValue()));
@@ -192,44 +178,41 @@ public abstract class DecoratorWithPodTemplateTestBase extends KubernetesPodTest
// The envs from pod template
expectedEnvs.put("ENV_OF_POD_TEMPLATE", "env-value-of-pod-template");
- assertThat(
- new ArrayList<>(actualEnvs.entrySet()),
- hasItems(expectedEnvs.entrySet().toArray()));
+ assertThat(actualEnvs).containsAllEntriesOf(expectedEnvs);
}
@Test
- public void testMainContainerResourceRequirementsMerging() {
+ void testMainContainerResourceRequirementsMerging() {
final ResourceRequirements resourceRequirements =
this.resultPod.getMainContainer().getResources();
final Map<String, Quantity> requests = resourceRequirements.getRequests();
- assertThat(requests.get("cpu").getAmount(), is(String.valueOf(RESOURCE_CPU)));
- assertThat(requests.get("memory").getAmount(), is(String.valueOf(RESOURCE_MEMORY)));
- assertThat(requests.get("ephemeral-storage").getAmount(), is("256"));
+ assertThat(requests.get("cpu").getAmount()).isEqualTo(String.valueOf(RESOURCE_CPU));
+ assertThat(requests.get("memory").getAmount()).isEqualTo(String.valueOf(RESOURCE_MEMORY));
+ assertThat(requests.get("ephemeral-storage").getAmount()).isEqualTo("256");
final Map<String, Quantity> limits = resourceRequirements.getLimits();
- assertThat(limits.get("cpu").getAmount(), is(String.valueOf(RESOURCE_CPU)));
- assertThat(limits.get("memory").getAmount(), is(String.valueOf(RESOURCE_MEMORY)));
- assertThat(limits.get("ephemeral-storage").getAmount(), is("256"));
+ assertThat(limits.get("cpu").getAmount()).isEqualTo(String.valueOf(RESOURCE_CPU));
+ assertThat(limits.get("memory").getAmount()).isEqualTo(String.valueOf(RESOURCE_MEMORY));
+ assertThat(limits.get("ephemeral-storage").getAmount()).isEqualTo("256");
}
@Test
- public void testServiceAccountOverwritten() {
- assertThat(
- this.resultPod.getPodWithoutMainContainer().getSpec().getServiceAccountName(),
- is(TESTING_SERVICE_ACCOUNT));
- assertThat(
- this.resultPod.getPodWithoutMainContainer().getSpec().getServiceAccount(),
- is(TESTING_SERVICE_ACCOUNT));
+ void testServiceAccountOverwritten() {
+ assertThat(this.resultPod.getPodWithoutMainContainer().getSpec().getServiceAccountName())
+ .isEqualTo(TESTING_SERVICE_ACCOUNT);
+ assertThat(this.resultPod.getPodWithoutMainContainer().getSpec().getServiceAccount())
+ .isEqualTo(TESTING_SERVICE_ACCOUNT);
}
@Test
- public void testMainContainerImageOverwritten() {
- assertThat(this.resultPod.getMainContainer().getImage(), is(IMAGE));
+ void testMainContainerImageOverwritten() {
+ assertThat(this.resultPod.getMainContainer().getImage()).isEqualTo(IMAGE);
}
@Test
- public void testMainContainerImagePullPolicyOverwritten() {
- assertThat(this.resultPod.getMainContainer().getImagePullPolicy(), is(IMAGE_PULL_POLICY));
+ void testMainContainerImagePullPolicyOverwritten() {
+ assertThat(this.resultPod.getMainContainer().getImagePullPolicy())
+ .isEqualTo(IMAGE_PULL_POLICY);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/EnvSecretsDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/EnvSecretsDecoratorTest.java
index d6261ea3242..3e7faea4eab 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/EnvSecretsDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/EnvSecretsDecoratorTest.java
@@ -23,14 +23,14 @@ import org.apache.flink.kubernetes.kubeclient.FlinkPod;
import org.apache.flink.kubernetes.kubeclient.KubernetesJobManagerTestBase;
import io.fabric8.kubernetes.api.model.EnvVar;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link EnvSecretsDecorator}. */
-public class EnvSecretsDecoratorTest extends KubernetesJobManagerTestBase {
+class EnvSecretsDecoratorTest extends KubernetesJobManagerTestBase {
private static final String ENV_NAME = "MY_FOO";
private static final String ENV_SERCET_KEY = "env:MY_FOO,secret:foo,key:key_foo";
@@ -52,11 +52,10 @@ public class EnvSecretsDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testWhetherPodOrContainerIsDecorated() {
+ void testWhetherPodOrContainerIsDecorated() {
final FlinkPod resultFlinkPod = envSecretsDecorator.decorateFlinkPod(baseFlinkPod);
List<EnvVar> envVarList = resultFlinkPod.getMainContainer().getEnv();
- assertEquals(1, envVarList.size());
- assertEquals(ENV_NAME, envVarList.get(0).getName());
+ assertThat(envVarList).extracting(EnvVar::getName).containsExactly(ENV_NAME);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/ExternalServiceDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/ExternalServiceDecoratorTest.java
index 92628467df9..a3bc516f62a 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/ExternalServiceDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/ExternalServiceDecoratorTest.java
@@ -27,7 +27,7 @@ import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServicePort;
import io.fabric8.kubernetes.api.model.ServicePortBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Collections;
@@ -35,13 +35,10 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link ExternalServiceDecorator}. */
-public class ExternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
+class ExternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
private ExternalServiceDecorator externalServiceDecorator;
@@ -64,25 +61,23 @@ public class ExternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testBuildAccompanyingKubernetesResources() throws IOException {
+ void testBuildAccompanyingKubernetesResources() throws IOException {
final List<HasMetadata> resources =
this.externalServiceDecorator.buildAccompanyingKubernetesResources();
- assertEquals(1, resources.size());
+ assertThat(resources).hasSize(1);
final Service restService = (Service) resources.get(0);
- assertEquals(Constants.API_VERSION, restService.getApiVersion());
+ assertThat(restService.getApiVersion()).isEqualTo(Constants.API_VERSION);
- assertEquals(
- ExternalServiceDecorator.getExternalServiceName(CLUSTER_ID),
- restService.getMetadata().getName());
+ assertThat(restService.getMetadata().getName())
+ .isEqualTo(ExternalServiceDecorator.getExternalServiceName(CLUSTER_ID));
final Map<String, String> expectedLabels = getCommonLabels();
- assertEquals(expectedLabels, restService.getMetadata().getLabels());
+ assertThat(restService.getMetadata().getLabels()).isEqualTo(expectedLabels);
- assertEquals(
- KubernetesConfigOptions.ServiceExposedType.ClusterIP.name(),
- restService.getSpec().getType());
+ assertThat(restService.getSpec().getType())
+ .isEqualTo(KubernetesConfigOptions.ServiceExposedType.ClusterIP.name());
final List<ServicePort> expectedServicePorts =
Collections.singletonList(
@@ -91,49 +86,45 @@ public class ExternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
.withPort(REST_PORT)
.withNewTargetPort(Integer.valueOf(REST_BIND_PORT))
.build());
- assertEquals(expectedServicePorts, restService.getSpec().getPorts());
+ assertThat(restService.getSpec().getPorts()).isEqualTo(expectedServicePorts);
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
- assertEquals(expectedLabels, restService.getSpec().getSelector());
+ assertThat(restService.getSpec().getSelector()).isEqualTo(expectedLabels);
final Map<String, String> resultAnnotations = restService.getMetadata().getAnnotations();
- assertThat(resultAnnotations, is(equalTo(customizedAnnotations)));
+ assertThat(resultAnnotations).isEqualTo(customizedAnnotations);
}
@Test
- public void testSetServiceExposedType() throws IOException {
+ void testSetServiceExposedType() throws IOException {
this.flinkConfig.set(
KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE,
KubernetesConfigOptions.ServiceExposedType.NodePort);
final List<HasMetadata> resources =
this.externalServiceDecorator.buildAccompanyingKubernetesResources();
- assertEquals(
- KubernetesConfigOptions.ServiceExposedType.NodePort.name(),
- ((Service) resources.get(0)).getSpec().getType());
+ assertThat(((Service) resources.get(0)).getSpec().getType())
+ .isEqualTo(KubernetesConfigOptions.ServiceExposedType.NodePort.name());
this.flinkConfig.set(
KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE,
KubernetesConfigOptions.ServiceExposedType.ClusterIP);
final List<HasMetadata> servicesWithClusterIP =
this.externalServiceDecorator.buildAccompanyingKubernetesResources();
- assertEquals(
- KubernetesConfigOptions.ServiceExposedType.ClusterIP.name(),
- ((Service) servicesWithClusterIP.get(0)).getSpec().getType());
+ assertThat(((Service) servicesWithClusterIP.get(0)).getSpec().getType())
+ .isEqualTo(KubernetesConfigOptions.ServiceExposedType.ClusterIP.name());
}
@Test
- public void testSetServiceExposedTypeWithHeadless() throws IOException {
+ void testSetServiceExposedTypeWithHeadless() throws IOException {
this.flinkConfig.set(
KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE,
KubernetesConfigOptions.ServiceExposedType.Headless_ClusterIP);
final List<HasMetadata> servicesWithHeadlessClusterIP =
this.externalServiceDecorator.buildAccompanyingKubernetesResources();
- assertThat(
- ((Service) servicesWithHeadlessClusterIP.get(0)).getSpec().getType(),
- is(KubernetesConfigOptions.ServiceExposedType.ClusterIP.name()));
- assertThat(
- ((Service) servicesWithHeadlessClusterIP.get(0)).getSpec().getClusterIP(),
- is(HeadlessClusterIPService.HEADLESS_CLUSTER_IP));
+ assertThat(((Service) servicesWithHeadlessClusterIP.get(0)).getSpec().getType())
+ .isEqualTo(KubernetesConfigOptions.ServiceExposedType.ClusterIP.name());
+ assertThat(((Service) servicesWithHeadlessClusterIP.get(0)).getSpec().getClusterIP())
+ .isEqualTo(HeadlessClusterIPService.HEADLESS_CLUSTER_IP);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/FlinkConfMountDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/FlinkConfMountDecoratorTest.java
index 9badbc5434d..6ed09a75498 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/FlinkConfMountDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/FlinkConfMountDecoratorTest.java
@@ -35,7 +35,7 @@ import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeBuilder;
import io.fabric8.kubernetes.api.model.VolumeMount;
import io.fabric8.kubernetes.api.model.VolumeMountBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
@@ -47,14 +47,10 @@ import static org.apache.flink.configuration.GlobalConfiguration.FLINK_CONF_FILE
import static org.apache.flink.kubernetes.kubeclient.decorators.FlinkConfMountDecorator.getFlinkConfConfigMapName;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOG4J_NAME;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOGBACK_NAME;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link FlinkConfMountDecorator}. */
-public class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
+class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
private static final String FLINK_CONF_DIR_IN_POD = "/opt/flink/flink-conf-";
@@ -75,49 +71,46 @@ public class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testWhetherPodOrContainerIsDecorated() {
+ void testWhetherPodOrContainerIsDecorated() {
final FlinkPod resultFlinkPod = flinkConfMountDecorator.decorateFlinkPod(baseFlinkPod);
- assertNotEquals(
- baseFlinkPod.getPodWithoutMainContainer(),
- resultFlinkPod.getPodWithoutMainContainer());
- assertNotEquals(baseFlinkPod.getMainContainer(), resultFlinkPod.getMainContainer());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer())
+ .isNotEqualTo(baseFlinkPod.getPodWithoutMainContainer());
+ assertThat(resultFlinkPod.getMainContainer()).isNotEqualTo(baseFlinkPod.getMainContainer());
}
@Test
- public void testConfigMap() throws IOException {
+ void testConfigMap() throws IOException {
KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOG4J_NAME);
KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOGBACK_NAME);
final List<HasMetadata> additionalResources =
flinkConfMountDecorator.buildAccompanyingKubernetesResources();
- assertEquals(1, additionalResources.size());
+ assertThat(additionalResources).hasSize(1);
final ConfigMap resultConfigMap = (ConfigMap) additionalResources.get(0);
- assertEquals(Constants.API_VERSION, resultConfigMap.getApiVersion());
+ assertThat(resultConfigMap.getApiVersion()).isEqualTo(Constants.API_VERSION);
- assertEquals(
- getFlinkConfConfigMapName(CLUSTER_ID), resultConfigMap.getMetadata().getName());
- assertEquals(getCommonLabels(), resultConfigMap.getMetadata().getLabels());
+ assertThat(resultConfigMap.getMetadata().getName())
+ .isEqualTo(getFlinkConfConfigMapName(CLUSTER_ID));
+ assertThat(resultConfigMap.getMetadata().getLabels()).isEqualTo(getCommonLabels());
Map<String, String> resultDatas = resultConfigMap.getData();
- assertEquals("some data", resultDatas.get(CONFIG_FILE_LOGBACK_NAME));
- assertEquals("some data", resultDatas.get(CONFIG_FILE_LOG4J_NAME));
+ assertThat(resultDatas.get(CONFIG_FILE_LOGBACK_NAME)).isEqualTo("some data");
+ assertThat(resultDatas.get(CONFIG_FILE_LOG4J_NAME)).isEqualTo("some data");
final Configuration resultFlinkConfig =
KubernetesTestUtils.loadConfigurationFromString(
resultDatas.get(FLINK_CONF_FILENAME));
- assertThat(
- resultFlinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR),
- is(FLINK_CONF_DIR_IN_POD));
+ assertThat(resultFlinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR))
+ .isEqualTo(FLINK_CONF_DIR_IN_POD);
// The following config options should not be added to config map
- assertThat(
- resultFlinkConfig.get(KubernetesConfigOptions.KUBE_CONFIG_FILE), is(nullValue()));
- assertThat(resultFlinkConfig.get(DeploymentOptionsInternal.CONF_DIR), is(nullValue()));
+ assertThat(resultFlinkConfig.get(KubernetesConfigOptions.KUBE_CONFIG_FILE)).isNull();
+ assertThat(resultFlinkConfig.get(DeploymentOptionsInternal.CONF_DIR)).isNull();
}
@Test
- public void testDecoratedFlinkPodWithoutLog4jAndLogback() {
+ void testDecoratedFlinkPodWithoutLog4jAndLogback() {
final FlinkPod resultFlinkPod = flinkConfMountDecorator.decorateFlinkPod(baseFlinkPod);
final List<KeyToPath> expectedKeyToPaths =
@@ -135,9 +128,8 @@ public class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
.withItems(expectedKeyToPaths)
.endConfigMap()
.build());
- assertEquals(
- expectedVolumes,
- resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes())
+ .isEqualTo(expectedVolumes);
final List<VolumeMount> expectedVolumeMounts =
Collections.singletonList(
@@ -145,11 +137,12 @@ public class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
.withName(Constants.FLINK_CONF_VOLUME)
.withMountPath(FLINK_CONF_DIR_IN_POD)
.build());
- assertEquals(expectedVolumeMounts, resultFlinkPod.getMainContainer().getVolumeMounts());
+ assertThat(resultFlinkPod.getMainContainer().getVolumeMounts())
+ .isEqualTo(expectedVolumeMounts);
}
@Test
- public void testDecoratedFlinkPodWithLog4j() throws IOException {
+ void testDecoratedFlinkPodWithLog4j() throws IOException {
KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOG4J_NAME);
final FlinkPod resultFlinkPod = flinkConfMountDecorator.decorateFlinkPod(baseFlinkPod);
@@ -173,13 +166,12 @@ public class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
.withItems(expectedKeyToPaths)
.endConfigMap()
.build());
- assertEquals(
- expectedVolumes,
- resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes())
+ .isEqualTo(expectedVolumes);
}
@Test
- public void testDecoratedFlinkPodWithLogback() throws IOException {
+ void testDecoratedFlinkPodWithLogback() throws IOException {
KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOGBACK_NAME);
final FlinkPod resultFlinkPod = flinkConfMountDecorator.decorateFlinkPod(baseFlinkPod);
@@ -203,13 +195,12 @@ public class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
.withItems(expectedKeyToPaths)
.endConfigMap()
.build());
- assertEquals(
- expectedVolumes,
- resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes())
+ .isEqualTo(expectedVolumes);
}
@Test
- public void testDecoratedFlinkPodWithLog4jAndLogback() throws IOException {
+ void testDecoratedFlinkPodWithLog4jAndLogback() throws IOException {
KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOG4J_NAME);
KubernetesTestUtils.createTemporyFile("some data", flinkConfDir, CONFIG_FILE_LOGBACK_NAME);
@@ -238,19 +229,18 @@ public class FlinkConfMountDecoratorTest extends KubernetesJobManagerTestBase {
.withItems(expectedKeyToPaths)
.endConfigMap()
.build());
- assertEquals(
- expectedVolumes,
- resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes())
+ .isEqualTo(expectedVolumes);
}
@Test
- public void testDecoratedFlinkContainer() {
+ void testDecoratedFlinkContainer() {
final Container resultMainContainer =
flinkConfMountDecorator.decorateFlinkPod(baseFlinkPod).getMainContainer();
- assertEquals(1, resultMainContainer.getVolumeMounts().size());
+ assertThat(resultMainContainer.getVolumeMounts()).hasSize(1);
final VolumeMount volumeMount = resultMainContainer.getVolumeMounts().get(0);
- assertEquals(Constants.FLINK_CONF_VOLUME, volumeMount.getName());
- assertEquals(FLINK_CONF_DIR_IN_POD, volumeMount.getMountPath());
+ assertThat(volumeMount.getName()).isEqualTo(Constants.FLINK_CONF_VOLUME);
+ assertThat(volumeMount.getMountPath()).isEqualTo(FLINK_CONF_DIR_IN_POD);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/HadoopConfMountDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/HadoopConfMountDecoratorTest.java
index 293a43113b1..a0a0648e31d 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/HadoopConfMountDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/HadoopConfMountDecoratorTest.java
@@ -30,7 +30,7 @@ import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KeyToPath;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeMount;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.HashMap;
@@ -38,12 +38,10 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link HadoopConfMountDecorator}. */
-public class HadoopConfMountDecoratorTest extends KubernetesJobManagerTestBase {
+class HadoopConfMountDecoratorTest extends KubernetesJobManagerTestBase {
private static final String EXISTING_HADOOP_CONF_CONFIG_MAP = "hadoop-conf";
@@ -58,25 +56,24 @@ public class HadoopConfMountDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testExistingHadoopConfigMap() throws IOException {
+ void testExistingHadoopConfigMap() throws IOException {
flinkConfig.set(
KubernetesConfigOptions.HADOOP_CONF_CONFIG_MAP, EXISTING_HADOOP_CONF_CONFIG_MAP);
- assertEquals(0, hadoopConfMountDecorator.buildAccompanyingKubernetesResources().size());
+ assertThat(hadoopConfMountDecorator.buildAccompanyingKubernetesResources()).isEmpty();
final FlinkPod resultFlinkPod = hadoopConfMountDecorator.decorateFlinkPod(baseFlinkPod);
final List<Volume> volumes =
resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes();
- assertTrue(
- volumes.stream()
- .anyMatch(
- volume ->
- volume.getConfigMap()
- .getName()
- .equals(EXISTING_HADOOP_CONF_CONFIG_MAP)));
+ assertThat(volumes)
+ .anyMatch(
+ volume ->
+ volume.getConfigMap()
+ .getName()
+ .equals(EXISTING_HADOOP_CONF_CONFIG_MAP));
}
@Test
- public void testExistingConfigMapPrecedeOverHadoopConfEnv() throws IOException {
+ void testExistingConfigMapPrecedeOverHadoopConfEnv() throws IOException {
// set existing ConfigMap
flinkConfig.set(
KubernetesConfigOptions.HADOOP_CONF_CONFIG_MAP, EXISTING_HADOOP_CONF_CONFIG_MAP);
@@ -85,93 +82,86 @@ public class HadoopConfMountDecoratorTest extends KubernetesJobManagerTestBase {
setHadoopConfDirEnv();
generateHadoopConfFileItems();
- assertEquals(0, hadoopConfMountDecorator.buildAccompanyingKubernetesResources().size());
+ assertThat(hadoopConfMountDecorator.buildAccompanyingKubernetesResources()).isEmpty();
final FlinkPod resultFlinkPod = hadoopConfMountDecorator.decorateFlinkPod(baseFlinkPod);
final List<Volume> volumes =
resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes();
- assertTrue(
- volumes.stream()
- .anyMatch(
- volume ->
- volume.getConfigMap()
- .getName()
- .equals(EXISTING_HADOOP_CONF_CONFIG_MAP)));
- assertFalse(
- volumes.stream()
- .anyMatch(
- volume ->
- volume.getConfigMap()
- .getName()
- .equals(
- HadoopConfMountDecorator
- .getHadoopConfConfigMapName(
- CLUSTER_ID))));
+ assertThat(volumes)
+ .anyMatch(
+ volume ->
+ volume.getConfigMap()
+ .getName()
+ .equals(EXISTING_HADOOP_CONF_CONFIG_MAP));
+ assertThat(volumes)
+ .noneMatch(
+ volume ->
+ volume.getConfigMap()
+ .getName()
+ .equals(
+ HadoopConfMountDecorator.getHadoopConfConfigMapName(
+ CLUSTER_ID)));
}
@Test
- public void testHadoopConfDirectoryUnset() throws IOException {
- assertEquals(0, hadoopConfMountDecorator.buildAccompanyingKubernetesResources().size());
+ void testHadoopConfDirectoryUnset() throws IOException {
+ assertThat(hadoopConfMountDecorator.buildAccompanyingKubernetesResources()).isEmpty();
final FlinkPod resultFlinkPod = hadoopConfMountDecorator.decorateFlinkPod(baseFlinkPod);
- assertEquals(
- baseFlinkPod.getPodWithoutMainContainer(),
- resultFlinkPod.getPodWithoutMainContainer());
- assertEquals(baseFlinkPod.getMainContainer(), resultFlinkPod.getMainContainer());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer())
+ .isEqualTo(baseFlinkPod.getPodWithoutMainContainer());
+ assertThat(resultFlinkPod.getMainContainer()).isEqualTo(baseFlinkPod.getMainContainer());
}
@Test
- public void testEmptyHadoopConfDirectory() throws IOException {
+ void testEmptyHadoopConfDirectory() throws IOException {
setHadoopConfDirEnv();
- assertEquals(0, hadoopConfMountDecorator.buildAccompanyingKubernetesResources().size());
+ assertThat(hadoopConfMountDecorator.buildAccompanyingKubernetesResources()).isEmpty();
final FlinkPod resultFlinkPod = hadoopConfMountDecorator.decorateFlinkPod(baseFlinkPod);
- assertEquals(
- baseFlinkPod.getPodWithoutMainContainer(),
- resultFlinkPod.getPodWithoutMainContainer());
- assertEquals(baseFlinkPod.getMainContainer(), resultFlinkPod.getMainContainer());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer())
+ .isEqualTo(baseFlinkPod.getPodWithoutMainContainer());
+ assertThat(resultFlinkPod.getMainContainer()).isEqualTo(baseFlinkPod.getMainContainer());
}
@Test
- public void testHadoopConfConfigMap() throws IOException {
+ void testHadoopConfConfigMap() throws IOException {
setHadoopConfDirEnv();
generateHadoopConfFileItems();
final List<HasMetadata> additionalResources =
hadoopConfMountDecorator.buildAccompanyingKubernetesResources();
- assertEquals(1, additionalResources.size());
+ assertThat(additionalResources).hasSize(1);
final ConfigMap resultConfigMap = (ConfigMap) additionalResources.get(0);
- assertEquals(Constants.API_VERSION, resultConfigMap.getApiVersion());
- assertEquals(
- HadoopConfMountDecorator.getHadoopConfConfigMapName(CLUSTER_ID),
- resultConfigMap.getMetadata().getName());
- assertEquals(getCommonLabels(), resultConfigMap.getMetadata().getLabels());
+ assertThat(resultConfigMap.getApiVersion()).isEqualTo(Constants.API_VERSION);
+ assertThat(resultConfigMap.getMetadata().getName())
+ .isEqualTo(HadoopConfMountDecorator.getHadoopConfConfigMapName(CLUSTER_ID));
+ assertThat(resultConfigMap.getMetadata().getLabels()).isEqualTo(getCommonLabels());
Map<String, String> resultDatas = resultConfigMap.getData();
- assertEquals("some data", resultDatas.get("core-site.xml"));
- assertEquals("some data", resultDatas.get("hdfs-site.xml"));
+ assertThat(resultDatas.get("core-site.xml")).isEqualTo("some data");
+ assertThat(resultDatas.get("hdfs-site.xml")).isEqualTo("some data");
}
@Test
- public void testPodWithHadoopConfVolume() throws IOException {
+ void testPodWithHadoopConfVolume() throws IOException {
setHadoopConfDirEnv();
generateHadoopConfFileItems();
final FlinkPod resultFlinkPod = hadoopConfMountDecorator.decorateFlinkPod(baseFlinkPod);
final List<Volume> resultVolumes =
resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes();
- assertEquals(1, resultVolumes.size());
+ assertThat(resultVolumes).hasSize(1);
final Volume resultVolume = resultVolumes.get(0);
- assertEquals(Constants.HADOOP_CONF_VOLUME, resultVolume.getName());
+ assertThat(resultVolume.getName()).isEqualTo(Constants.HADOOP_CONF_VOLUME);
final ConfigMapVolumeSource resultVolumeConfigMap = resultVolume.getConfigMap();
- assertEquals(
- HadoopConfMountDecorator.getHadoopConfConfigMapName(CLUSTER_ID),
- resultVolumeConfigMap.getName());
+ assertThat(resultVolumeConfigMap.getName())
+ .isEqualTo(HadoopConfMountDecorator.getHadoopConfConfigMapName(CLUSTER_ID));
final Map<String, String> expectedKeyToPaths =
new HashMap<String, String>() {
@@ -183,21 +173,21 @@ public class HadoopConfMountDecoratorTest extends KubernetesJobManagerTestBase {
final Map<String, String> resultKeyToPaths =
resultVolumeConfigMap.getItems().stream()
.collect(Collectors.toMap(KeyToPath::getKey, KeyToPath::getPath));
- assertEquals(expectedKeyToPaths, resultKeyToPaths);
+ assertThat(resultKeyToPaths).isEqualTo(expectedKeyToPaths);
}
@Test
- public void testMainContainerWithHadoopConfVolumeMount() throws IOException {
+ void testMainContainerWithHadoopConfVolumeMount() throws IOException {
setHadoopConfDirEnv();
generateHadoopConfFileItems();
final FlinkPod resultFlinkPod = hadoopConfMountDecorator.decorateFlinkPod(baseFlinkPod);
final List<VolumeMount> resultVolumeMounts =
resultFlinkPod.getMainContainer().getVolumeMounts();
- assertEquals(1, resultVolumeMounts.size());
+ assertThat(resultVolumeMounts).hasSize(1);
final VolumeMount resultVolumeMount = resultVolumeMounts.get(0);
- assertEquals(Constants.HADOOP_CONF_VOLUME, resultVolumeMount.getName());
- assertEquals(Constants.HADOOP_CONF_DIR_IN_POD, resultVolumeMount.getMountPath());
+ assertThat(resultVolumeMount.getName()).isEqualTo(Constants.HADOOP_CONF_VOLUME);
+ assertThat(resultVolumeMount.getMountPath()).isEqualTo(Constants.HADOOP_CONF_DIR_IN_POD);
final Map<String, String> expectedEnvs =
new HashMap<String, String>() {
@@ -208,6 +198,6 @@ public class HadoopConfMountDecoratorTest extends KubernetesJobManagerTestBase {
final Map<String, String> resultEnvs =
resultFlinkPod.getMainContainer().getEnv().stream()
.collect(Collectors.toMap(EnvVar::getName, EnvVar::getValue));
- assertEquals(expectedEnvs, resultEnvs);
+ assertThat(resultEnvs).isEqualTo(expectedEnvs);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorAccountTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorAccountTest.java
index a1232260731..4c5881ec36a 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorAccountTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorAccountTest.java
@@ -23,13 +23,12 @@ import org.apache.flink.kubernetes.kubeclient.FlinkPod;
import org.apache.flink.kubernetes.kubeclient.KubernetesJobManagerTestBase;
import io.fabric8.kubernetes.api.model.Pod;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for {@link InitJobManagerDecorator} decorating service account. */
-public class InitJobManagerDecoratorAccountTest extends KubernetesJobManagerTestBase {
+class InitJobManagerDecoratorAccountTest extends KubernetesJobManagerTestBase {
private static final String SERVICE_ACCOUNT_NAME = "service-test";
private static final String JOB_MANAGER_SERVICE_ACCOUNT_NAME = "jm-service-test";
@@ -59,9 +58,8 @@ public class InitJobManagerDecoratorAccountTest extends KubernetesJobManagerTest
}
@Test
- public void testPodServiceAccountName() {
- assertThat(
- this.resultPod.getSpec().getServiceAccountName(),
- is(JOB_MANAGER_SERVICE_ACCOUNT_NAME));
+ void testPodServiceAccountName() {
+ assertThat(this.resultPod.getSpec().getServiceAccountName())
+ .isEqualTo(JOB_MANAGER_SERVICE_ACCOUNT_NAME);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorTest.java
index 428d5005484..104e15de011 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorTest.java
@@ -32,8 +32,7 @@ import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.api.model.Toleration;
-import org.hamcrest.Matchers;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@@ -41,14 +40,10 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link InitJobManagerDecorator}. */
-public class InitJobManagerDecoratorTest extends KubernetesJobManagerTestBase {
+class InitJobManagerDecoratorTest extends KubernetesJobManagerTestBase {
private static final String SERVICE_ACCOUNT_NAME = "service-test";
private static final List<String> IMAGE_PULL_SECRETS = Arrays.asList("s1", "s2", "s3");
@@ -99,41 +94,42 @@ public class InitJobManagerDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testApiVersion() {
- assertEquals(Constants.API_VERSION, this.resultPod.getApiVersion());
+ void testApiVersion() {
+ assertThat(this.resultPod.getApiVersion()).isEqualTo(Constants.API_VERSION);
}
@Test
- public void testMainContainerName() {
- assertEquals(Constants.MAIN_CONTAINER_NAME, this.resultMainContainer.getName());
+ void testMainContainerName() {
+ assertThat(this.resultMainContainer.getName()).isEqualTo(Constants.MAIN_CONTAINER_NAME);
}
@Test
- public void testMainContainerImage() {
- assertEquals(CONTAINER_IMAGE, this.resultMainContainer.getImage());
- assertEquals(
- CONTAINER_IMAGE_PULL_POLICY.name(), this.resultMainContainer.getImagePullPolicy());
+ void testMainContainerImage() {
+ assertThat(this.resultMainContainer.getImage()).isEqualTo(CONTAINER_IMAGE);
+ assertThat(this.resultMainContainer.getImagePullPolicy())
+ .isEqualTo(CONTAINER_IMAGE_PULL_POLICY.name());
}
@Test
- public void testMainContainerResourceRequirements() {
+ void testMainContainerResourceRequirements() {
final ResourceRequirements resourceRequirements = this.resultMainContainer.getResources();
final Map<String, Quantity> requests = resourceRequirements.getRequests();
- assertEquals(Double.toString(JOB_MANAGER_CPU), requests.get("cpu").getAmount());
- assertEquals(String.valueOf(JOB_MANAGER_MEMORY), requests.get("memory").getAmount());
+ assertThat(requests.get("cpu").getAmount()).isEqualTo(Double.toString(JOB_MANAGER_CPU));
+ assertThat(requests.get("memory").getAmount())
+ .isEqualTo(String.valueOf(JOB_MANAGER_MEMORY));
final Map<String, Quantity> limits = resourceRequirements.getLimits();
- assertEquals(
- Double.toString(JOB_MANAGER_CPU * JOB_MANAGER_CPU_LIMIT_FACTOR),
- limits.get("cpu").getAmount());
- assertEquals(
- Integer.toString((int) (JOB_MANAGER_MEMORY * JOB_MANAGER_MEMORY_LIMIT_FACTOR)),
- limits.get("memory").getAmount());
+ assertThat(limits.get("cpu").getAmount())
+ .isEqualTo(Double.toString(JOB_MANAGER_CPU * JOB_MANAGER_CPU_LIMIT_FACTOR));
+ assertThat(limits.get("memory").getAmount())
+ .isEqualTo(
+ Integer.toString(
+ (int) (JOB_MANAGER_MEMORY * JOB_MANAGER_MEMORY_LIMIT_FACTOR)));
}
@Test
- public void testMainContainerPorts() {
+ void testMainContainerPorts() {
final List<ContainerPort> expectedContainerPorts =
Arrays.asList(
new ContainerPortBuilder()
@@ -149,85 +145,81 @@ public class InitJobManagerDecoratorTest extends KubernetesJobManagerTestBase {
.withContainerPort(BLOB_SERVER_PORT)
.build());
- assertEquals(expectedContainerPorts, this.resultMainContainer.getPorts());
+ assertThat(this.resultMainContainer.getPorts()).isEqualTo(expectedContainerPorts);
}
@Test
- public void testMainContainerEnv() {
+ void testMainContainerEnv() {
final List<EnvVar> envVars = this.resultMainContainer.getEnv();
final Map<String, String> envs = new HashMap<>();
envVars.forEach(env -> envs.put(env.getName(), env.getValue()));
- this.customizedEnvs.forEach((k, v) -> assertEquals(envs.get(k), v));
-
- assertTrue(
- envVars.stream()
- .anyMatch(
- env ->
- env.getName().equals(Constants.ENV_FLINK_POD_IP_ADDRESS)
- && env.getValueFrom()
- .getFieldRef()
- .getApiVersion()
- .equals(Constants.API_VERSION)
- && env.getValueFrom()
- .getFieldRef()
- .getFieldPath()
- .equals(Constants.POD_IP_FIELD_PATH)));
+ this.customizedEnvs.forEach((k, v) -> assertThat(v).isEqualTo(envs.get(k)));
+
+ assertThat(envVars)
+ .anyMatch(
+ env ->
+ env.getName().equals(Constants.ENV_FLINK_POD_IP_ADDRESS)
+ && env.getValueFrom()
+ .getFieldRef()
+ .getApiVersion()
+ .equals(Constants.API_VERSION)
+ && env.getValueFrom()
+ .getFieldRef()
+ .getFieldPath()
+ .equals(Constants.POD_IP_FIELD_PATH));
}
@Test
- public void testPodLabels() {
+ void testPodLabels() {
final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
expectedLabels.putAll(userLabels);
- assertEquals(expectedLabels, this.resultPod.getMetadata().getLabels());
+ assertThat(this.resultPod.getMetadata().getLabels()).isEqualTo(expectedLabels);
}
@Test
- public void testPodAnnotations() {
+ void testPodAnnotations() {
final Map<String, String> resultAnnotations =
kubernetesJobManagerParameters.getAnnotations();
- assertThat(resultAnnotations, is(equalTo(ANNOTATIONS)));
+ assertThat(resultAnnotations).isEqualTo(ANNOTATIONS);
}
@Test
- public void testPodServiceAccountName() {
- assertEquals(SERVICE_ACCOUNT_NAME, this.resultPod.getSpec().getServiceAccountName());
+ void testPodServiceAccountName() {
+ assertThat(this.resultPod.getSpec().getServiceAccountName())
+ .isEqualTo(SERVICE_ACCOUNT_NAME);
}
@Test
- public void testImagePullSecrets() {
+ void testImagePullSecrets() {
final List<String> resultSecrets =
this.resultPod.getSpec().getImagePullSecrets().stream()
.map(LocalObjectReference::getName)
.collect(Collectors.toList());
- assertEquals(IMAGE_PULL_SECRETS, resultSecrets);
+ assertThat(resultSecrets).isEqualTo(IMAGE_PULL_SECRETS);
}
@Test
- public void testNodeSelector() {
- assertThat(this.resultPod.getSpec().getNodeSelector(), is(equalTo(nodeSelector)));
+ void testNodeSelector() {
+ assertThat(this.resultPod.getSpec().getNodeSelector()).isEqualTo(nodeSelector);
}
@Test
- public void testPodTolerations() {
- assertThat(
- this.resultPod.getSpec().getTolerations(),
- Matchers.containsInAnyOrder(TOLERATION.toArray()));
+ void testPodTolerations() {
+ assertThat(this.resultPod.getSpec().getTolerations())
+ .containsExactlyInAnyOrderElementsOf(TOLERATION);
}
@Test
- public void testFlinkLogDirEnvShouldBeSetIfConfiguredViaOptions() {
+ void testFlinkLogDirEnvShouldBeSetIfConfiguredViaOptions() {
final List<EnvVar> envVars = this.resultMainContainer.getEnv();
- assertThat(
- envVars.stream()
- .anyMatch(
- envVar ->
- envVar.getName().equals(Constants.ENV_FLINK_LOG_DIR)
- && envVar.getValue()
- .equals(USER_DEFINED_FLINK_LOG_DIR)),
- is(true));
+ assertThat(envVars)
+ .anyMatch(
+ envVar ->
+ envVar.getName().equals(Constants.ENV_FLINK_LOG_DIR)
+ && envVar.getValue().equals(USER_DEFINED_FLINK_LOG_DIR));
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorWithPodTemplateTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorWithPodTemplateTest.java
index 6f75a4768e7..6ebda8b8b6a 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorWithPodTemplateTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitJobManagerDecoratorWithPodTemplateTest.java
@@ -26,17 +26,15 @@ import org.apache.flink.kubernetes.kubeclient.parameters.KubernetesJobManagerPar
import org.apache.flink.kubernetes.utils.Constants;
import io.fabric8.kubernetes.api.model.ContainerPort;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
-import java.util.stream.Collectors;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link InitJobManagerDecorator} with pod template. */
-public class InitJobManagerDecoratorWithPodTemplateTest extends DecoratorWithPodTemplateTestBase {
+class InitJobManagerDecoratorWithPodTemplateTest extends DecoratorWithPodTemplateTestBase {
@Override
protected void setupFlinkConfig() {
@@ -64,7 +62,7 @@ public class InitJobManagerDecoratorWithPodTemplateTest extends DecoratorWithPod
}
@Test
- public void testJobManagerManagerMainContainerPortsMerging() {
+ void testJobManagerManagerMainContainerPortsMerging() {
final List<String> expectedContainerPorts = new ArrayList<>();
expectedContainerPorts.add(Constants.REST_PORT_NAME);
expectedContainerPorts.add(Constants.JOB_MANAGER_RPC_PORT_NAME);
@@ -72,9 +70,8 @@ public class InitJobManagerDecoratorWithPodTemplateTest extends DecoratorWithPod
// Add port from pod template
expectedContainerPorts.add("testing-port");
assertThat(
- this.resultPod.getMainContainer().getPorts().stream()
- .map(ContainerPort::getName)
- .collect(Collectors.toList()),
- containsInAnyOrder(expectedContainerPorts.toArray()));
+ this.resultPod.getMainContainer().getPorts().stream()
+ .map(ContainerPort::getName))
+ .containsExactlyInAnyOrderElementsOf(expectedContainerPorts);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorAccountTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorAccountTest.java
index 747c5811ff0..76311d80625 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorAccountTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorAccountTest.java
@@ -23,13 +23,12 @@ import org.apache.flink.kubernetes.kubeclient.FlinkPod;
import org.apache.flink.kubernetes.kubeclient.KubernetesTaskManagerTestBase;
import io.fabric8.kubernetes.api.model.Pod;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for {@link InitTaskManagerDecorator} decorating service account. */
-public class InitTaskManagerDecoratorAccountTest extends KubernetesTaskManagerTestBase {
+class InitTaskManagerDecoratorAccountTest extends KubernetesTaskManagerTestBase {
private static final String SERVICE_ACCOUNT_NAME = "service-test";
private static final String TASK_MANAGER_SERVICE_ACCOUNT_NAME = "tm-service-test";
@@ -60,9 +59,8 @@ public class InitTaskManagerDecoratorAccountTest extends KubernetesTaskManagerTe
}
@Test
- public void testPodServiceAccountName() {
- assertThat(
- this.resultPod.getSpec().getServiceAccountName(),
- is(TASK_MANAGER_SERVICE_ACCOUNT_NAME));
+ void testPodServiceAccountName() {
+ assertThat(this.resultPod.getSpec().getServiceAccountName())
+ .isEqualTo(TASK_MANAGER_SERVICE_ACCOUNT_NAME);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorTest.java
index 7db86915c77..d4acbb4e30e 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorTest.java
@@ -33,8 +33,7 @@ import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Quantity;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.fabric8.kubernetes.api.model.Toleration;
-import org.hamcrest.Matchers;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -43,13 +42,10 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link InitJobManagerDecorator}. */
-public class InitTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase {
+class InitTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase {
private static final String SERVICE_ACCOUNT_NAME = "service-test";
private static final List<String> IMAGE_PULL_SECRETS = Arrays.asList("s1", "s2", "s3");
@@ -117,56 +113,59 @@ public class InitTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase
}
@Test
- public void testApiVersion() {
- assertEquals(Constants.API_VERSION, this.resultPod.getApiVersion());
+ void testApiVersion() {
+ assertThat(this.resultPod.getApiVersion()).isEqualTo(Constants.API_VERSION);
}
@Test
- public void testMainContainerName() {
- assertEquals(Constants.MAIN_CONTAINER_NAME, this.resultMainContainer.getName());
+ void testMainContainerName() {
+ assertThat(this.resultMainContainer.getName()).isEqualTo(Constants.MAIN_CONTAINER_NAME);
}
@Test
- public void testMainContainerImage() {
- assertEquals(CONTAINER_IMAGE, this.resultMainContainer.getImage());
+ void testMainContainerImage() {
+ assertThat(this.resultMainContainer.getImage()).isEqualTo(CONTAINER_IMAGE);
}
@Test
- public void testMainContainerImagePullPolicy() {
- assertEquals(
- CONTAINER_IMAGE_PULL_POLICY.name(), this.resultMainContainer.getImagePullPolicy());
+ void testMainContainerImagePullPolicy() {
+ assertThat(this.resultMainContainer.getImagePullPolicy())
+ .isEqualTo(CONTAINER_IMAGE_PULL_POLICY.name());
}
@Test
- public void testMainContainerResourceRequirements() {
+ void testMainContainerResourceRequirements() {
final ResourceRequirements resourceRequirements = this.resultMainContainer.getResources();
final Map<String, Quantity> requests = resourceRequirements.getRequests();
- assertEquals(Double.toString(TASK_MANAGER_CPU), requests.get("cpu").getAmount());
- assertEquals(String.valueOf(TOTAL_PROCESS_MEMORY), requests.get("memory").getAmount());
+ assertThat(requests.get("cpu").getAmount()).isEqualTo(Double.toString(TASK_MANAGER_CPU));
+ assertThat(requests.get("memory").getAmount())
+ .isEqualTo(String.valueOf(TOTAL_PROCESS_MEMORY));
final Map<String, Quantity> limits = resourceRequirements.getLimits();
- assertEquals(
- Double.toString(TASK_MANAGER_CPU * TASK_MANAGER_CPU_LIMIT_FACTOR),
- limits.get("cpu").getAmount());
- assertEquals(
- Integer.toString((int) (TOTAL_PROCESS_MEMORY * TASK_MANAGER_MEMORY_LIMIT_FACTOR)),
- limits.get("memory").getAmount());
+ assertThat(limits.get("cpu").getAmount())
+ .isEqualTo(Double.toString(TASK_MANAGER_CPU * TASK_MANAGER_CPU_LIMIT_FACTOR));
+ assertThat(limits.get("memory").getAmount())
+ .isEqualTo(
+ Integer.toString(
+ (int) (TOTAL_PROCESS_MEMORY * TASK_MANAGER_MEMORY_LIMIT_FACTOR)));
}
@Test
- public void testExternalResourceInResourceRequirements() {
+ void testExternalResourceInResourceRequirements() {
final ResourceRequirements resourceRequirements = this.resultMainContainer.getResources();
final Map<String, Quantity> requests = resourceRequirements.getRequests();
- assertEquals(Long.toString(RESOURCE_AMOUNT), requests.get(RESOURCE_CONFIG_KEY).getAmount());
+ assertThat(requests.get(RESOURCE_CONFIG_KEY).getAmount())
+ .isEqualTo(Long.toString(RESOURCE_AMOUNT));
final Map<String, Quantity> limits = resourceRequirements.getLimits();
- assertEquals(Long.toString(RESOURCE_AMOUNT), limits.get(RESOURCE_CONFIG_KEY).getAmount());
+ assertThat(limits.get(RESOURCE_CONFIG_KEY).getAmount())
+ .isEqualTo(Long.toString(RESOURCE_AMOUNT));
}
@Test
- public void testMainContainerPorts() {
+ void testMainContainerPorts() {
final List<ContainerPort> expectedContainerPorts =
Collections.singletonList(
new ContainerPortBuilder()
@@ -174,84 +173,81 @@ public class InitTaskManagerDecoratorTest extends KubernetesTaskManagerTestBase
.withContainerPort(RPC_PORT)
.build());
- assertEquals(expectedContainerPorts, this.resultMainContainer.getPorts());
+ assertThat(this.resultMainContainer.getPorts()).isEqualTo(expectedContainerPorts);
}
@Test
- public void testMainContainerEnv() {
+ void testMainContainerEnv() {
final Map<String, String> expectedEnvVars = new HashMap<>(customizedEnvs);
final Map<String, String> resultEnvVars =
this.resultMainContainer.getEnv().stream()
.collect(Collectors.toMap(EnvVar::getName, EnvVar::getValue));
- expectedEnvVars.forEach((k, v) -> assertThat(resultEnvVars.get(k), is(v)));
+ expectedEnvVars.forEach((k, v) -> assertThat(resultEnvVars.get(k)).isEqualTo(v));
}
@Test
- public void testPodName() {
- assertEquals(POD_NAME, this.resultPod.getMetadata().getName());
+ void testPodName() {
+ assertThat(this.resultPod.getMetadata().getName()).isEqualTo(POD_NAME);
}
@Test
- public void testPodLabels() {
+ void testPodLabels() {
final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_TASK_MANAGER);
expectedLabels.putAll(userLabels);
- assertEquals(expectedLabels, this.resultPod.getMetadata().getLabels());
+ assertThat(this.resultPod.getMetadata().getLabels()).isEqualTo(expectedLabels);
}
@Test
- public void testPodAnnotations() {
+ void testPodAnnotations() {
final Map<String, String> resultAnnotations =
kubernetesTaskManagerParameters.getAnnotations();
- assertThat(resultAnnotations, is(equalTo(ANNOTATIONS)));
+ assertThat(resultAnnotations).isEqualTo(ANNOTATIONS);
}
@Test
- public void testPodServiceAccountName() {
- assertThat(this.resultPod.getSpec().getServiceAccountName(), is(SERVICE_ACCOUNT_NAME));
+ void testPodServiceAccountName() {
+ assertThat(this.resultPod.getSpec().getServiceAccountName())
+ .isEqualTo(SERVICE_ACCOUNT_NAME);
}
@Test
- public void testRestartPolicy() {
+ void testRestartPolicy() {
final String resultRestartPolicy = this.resultPod.getSpec().getRestartPolicy();
- assertThat(resultRestartPolicy, is(Constants.RESTART_POLICY_OF_NEVER));
+ assertThat(resultRestartPolicy).isEqualTo(Constants.RESTART_POLICY_OF_NEVER);
}
@Test
- public void testImagePullSecrets() {
+ void testImagePullSecrets() {
final List<String> resultSecrets =
this.resultPod.getSpec().getImagePullSecrets().stream()
.map(LocalObjectReference::getName)
.collect(Collectors.toList());
- assertEquals(IMAGE_PULL_SECRETS, resultSecrets);
+ assertThat(resultSecrets).isEqualTo(IMAGE_PULL_SECRETS);
}
@Test
- public void testNodeSelector() {
- assertThat(this.resultPod.getSpec().getNodeSelector(), is(equalTo(nodeSelector)));
+ void testNodeSelector() {
+ assertThat(this.resultPod.getSpec().getNodeSelector()).isEqualTo(nodeSelector);
}
@Test
- public void testPodTolerations() {
- assertThat(
- this.resultPod.getSpec().getTolerations(),
- Matchers.containsInAnyOrder(TOLERATION.toArray()));
+ void testPodTolerations() {
+ assertThat(this.resultPod.getSpec().getTolerations())
+ .containsExactlyInAnyOrderElementsOf(TOLERATION);
}
@Test
- public void testFlinkLogDirEnvShouldBeSetIfConfiguredViaOptions() {
+ void testFlinkLogDirEnvShouldBeSetIfConfiguredViaOptions() {
final List<EnvVar> envVars = this.resultMainContainer.getEnv();
- assertThat(
- envVars.stream()
- .anyMatch(
- envVar ->
- envVar.getName().equals(Constants.ENV_FLINK_LOG_DIR)
- && envVar.getValue()
- .equals(USER_DEFINED_FLINK_LOG_DIR)),
- is(true));
+ assertThat(envVars)
+ .anyMatch(
+ envVar ->
+ envVar.getName().equals(Constants.ENV_FLINK_LOG_DIR)
+ && envVar.getValue().equals(USER_DEFINED_FLINK_LOG_DIR));
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorWithPodTemplateTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorWithPodTemplateTest.java
index 420e498e046..6288545566b 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorWithPodTemplateTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InitTaskManagerDecoratorWithPodTemplateTest.java
@@ -26,20 +26,17 @@ import org.apache.flink.kubernetes.kubeclient.parameters.KubernetesTaskManagerPa
import org.apache.flink.kubernetes.utils.Constants;
import io.fabric8.kubernetes.api.model.ContainerPort;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.equalToIgnoringCase;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link InitTaskManagerDecorator} with pod template. */
-public class InitTaskManagerDecoratorWithPodTemplateTest extends DecoratorWithPodTemplateTestBase {
+class InitTaskManagerDecoratorWithPodTemplateTest extends DecoratorWithPodTemplateTestBase {
private static final String POD_NAME = "taskmanager-" + UUID.randomUUID().toString();
@@ -68,27 +65,27 @@ public class InitTaskManagerDecoratorWithPodTemplateTest extends DecoratorWithPo
}
@Test
- public void testTaskManagerMainContainerPortsMerging() {
+ void testTaskManagerMainContainerPortsMerging() {
final List<String> expectedContainerPorts = new ArrayList<>();
expectedContainerPorts.add(Constants.TASK_MANAGER_RPC_PORT_NAME);
// Add port from pod template
expectedContainerPorts.add("testing-port");
assertThat(
- this.resultPod.getMainContainer().getPorts().stream()
- .map(ContainerPort::getName)
- .collect(Collectors.toList()),
- containsInAnyOrder(expectedContainerPorts.toArray()));
+ this.resultPod.getMainContainer().getPorts().stream()
+ .map(ContainerPort::getName)
+ .collect(Collectors.toList()))
+ .containsExactlyInAnyOrderElementsOf(expectedContainerPorts);
}
@Test
- public void testTaskManagerPodRestartPolicyOverwritten() {
- assertThat(
- resultPod.getPodWithoutMainContainer().getSpec().getRestartPolicy(),
- is(equalToIgnoringCase(Constants.RESTART_POLICY_OF_NEVER)));
+ void testTaskManagerPodRestartPolicyOverwritten() {
+ assertThat(resultPod.getPodWithoutMainContainer().getSpec().getRestartPolicy())
+ .isEqualToIgnoringCase(Constants.RESTART_POLICY_OF_NEVER);
}
@Test
- public void testTaskManagerPodNameOverwritten() {
- assertThat(resultPod.getPodWithoutMainContainer().getMetadata().getName(), is(POD_NAME));
+ void testTaskManagerPodNameOverwritten() {
+ assertThat(resultPod.getPodWithoutMainContainer().getMetadata().getName())
+ .isEqualTo(POD_NAME);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InternalServiceDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InternalServiceDecoratorTest.java
index 0d9fee2ad3e..a6fe3252a99 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InternalServiceDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/InternalServiceDecoratorTest.java
@@ -28,18 +28,17 @@ import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServicePort;
import io.fabric8.kubernetes.api.model.ServicePortBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link InternalServiceDecorator}. */
-public class InternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
+class InternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
private InternalServiceDecorator internalServiceDecorator;
@@ -52,28 +51,26 @@ public class InternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testBuildAccompanyingKubernetesResources() throws IOException {
+ void testBuildAccompanyingKubernetesResources() throws IOException {
final List<HasMetadata> resources =
this.internalServiceDecorator.buildAccompanyingKubernetesResources();
- assertEquals(1, resources.size());
+ assertThat(resources).hasSize(1);
- assertEquals(
- InternalServiceDecorator.getNamespacedInternalServiceName(CLUSTER_ID, NAMESPACE),
- this.flinkConfig.getString(JobManagerOptions.ADDRESS));
+ assertThat(InternalServiceDecorator.getNamespacedInternalServiceName(CLUSTER_ID, NAMESPACE))
+ .isEqualTo(this.flinkConfig.getString(JobManagerOptions.ADDRESS));
final Service internalService = (Service) resources.get(0);
- assertEquals(Constants.API_VERSION, internalService.getApiVersion());
+ assertThat(internalService.getApiVersion()).isEqualTo(Constants.API_VERSION);
- assertEquals(
- InternalServiceDecorator.getInternalServiceName(CLUSTER_ID),
- internalService.getMetadata().getName());
+ assertThat(internalService.getMetadata().getName())
+ .isEqualTo(InternalServiceDecorator.getInternalServiceName(CLUSTER_ID));
final Map<String, String> expectedLabels = getCommonLabels();
- assertEquals(expectedLabels, internalService.getMetadata().getLabels());
+ assertThat(internalService.getMetadata().getLabels()).isEqualTo(expectedLabels);
- assertNull(internalService.getSpec().getType());
- assertEquals("None", internalService.getSpec().getClusterIP());
+ assertThat(internalService.getSpec().getType()).isNull();
+ assertThat(internalService.getSpec().getClusterIP()).isEqualTo("None");
List<ServicePort> expectedServicePorts =
Arrays.asList(
@@ -85,19 +82,19 @@ public class InternalServiceDecoratorTest extends KubernetesJobManagerTestBase {
.withName(Constants.BLOB_SERVER_PORT_NAME)
.withPort(BLOB_SERVER_PORT)
.build());
- assertEquals(expectedServicePorts, internalService.getSpec().getPorts());
+ assertThat(internalService.getSpec().getPorts()).isEqualTo(expectedServicePorts);
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
- assertEquals(expectedLabels, internalService.getSpec().getSelector());
+ assertThat(internalService.getSpec().getSelector()).isEqualTo(expectedLabels);
}
@Test
- public void testDisableInternalService() throws IOException {
+ void testDisableInternalService() throws IOException {
this.flinkConfig.setString(
HighAvailabilityOptions.HA_MODE, HighAvailabilityMode.ZOOKEEPER.name());
final List<HasMetadata> resources =
this.internalServiceDecorator.buildAccompanyingKubernetesResources();
- assertEquals(0, resources.size());
+ assertThat(resources).isEmpty();
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/KerberosMountDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/KerberosMountDecoratorTest.java
index d1680a25cc6..fcc3947a0df 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/KerberosMountDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/KerberosMountDecoratorTest.java
@@ -28,18 +28,16 @@ import org.apache.flink.kubernetes.utils.Constants;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeMount;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link KerberosMountDecoratorTest}. */
-public class KerberosMountDecoratorTest extends KubernetesPodTestBase {
+class KerberosMountDecoratorTest extends KubernetesPodTestBase {
private KerberosMountDecorator kerberosMountDecorator;
@@ -78,30 +76,30 @@ public class KerberosMountDecoratorTest extends KubernetesPodTestBase {
}
@Test
- public void testWhetherPodOrContainerIsDecorated() {
+ void testWhetherPodOrContainerIsDecorated() {
final FlinkPod resultFlinkPod = kerberosMountDecorator.decorateFlinkPod(baseFlinkPod);
- assertNotEquals(
- baseFlinkPod.getPodWithoutMainContainer(),
- resultFlinkPod.getPodWithoutMainContainer());
- assertNotEquals(baseFlinkPod.getMainContainer(), resultFlinkPod.getMainContainer());
+ assertThat(resultFlinkPod.getPodWithoutMainContainer())
+ .isNotEqualTo(baseFlinkPod.getPodWithoutMainContainer());
+ assertThat(resultFlinkPod.getMainContainer()).isNotEqualTo(baseFlinkPod.getMainContainer());
}
@Test
- public void testConfEditWhenBuildAccompanyingKubernetesResources() throws IOException {
+ void testConfEditWhenBuildAccompanyingKubernetesResources() throws IOException {
kerberosMountDecorator.buildAccompanyingKubernetesResources();
- assertEquals(
- String.format("%s/%s", Constants.KERBEROS_KEYTAB_MOUNT_POINT, KEYTAB_FILE),
- this.testingKubernetesParameters
- .getFlinkConfiguration()
- .get(SecurityOptions.KERBEROS_LOGIN_KEYTAB));
+ assertThat(
+ this.testingKubernetesParameters
+ .getFlinkConfiguration()
+ .get(SecurityOptions.KERBEROS_LOGIN_KEYTAB))
+ .isEqualTo(
+ String.format("%s/%s", Constants.KERBEROS_KEYTAB_MOUNT_POINT, KEYTAB_FILE));
}
@Test
- public void testDecoratedFlinkContainer() {
+ void testDecoratedFlinkContainer() {
final Container resultMainContainer =
kerberosMountDecorator.decorateFlinkPod(baseFlinkPod).getMainContainer();
- assertEquals(2, resultMainContainer.getVolumeMounts().size());
+ assertThat(resultMainContainer.getVolumeMounts()).hasSize(2);
final VolumeMount keytabVolumeMount =
resultMainContainer.getVolumeMounts().stream()
@@ -113,19 +111,19 @@ public class KerberosMountDecoratorTest extends KubernetesPodTestBase {
.filter(x -> x.getName().equals(Constants.KERBEROS_KRB5CONF_VOLUME))
.collect(Collectors.toList())
.get(0);
- assertNotNull(keytabVolumeMount);
- assertNotNull(krb5ConfVolumeMount);
- assertEquals(Constants.KERBEROS_KEYTAB_MOUNT_POINT, keytabVolumeMount.getMountPath());
- assertEquals(
- Constants.KERBEROS_KRB5CONF_MOUNT_DIR + "/krb5.conf",
- krb5ConfVolumeMount.getMountPath());
+ assertThat(keytabVolumeMount).isNotNull();
+ assertThat(krb5ConfVolumeMount).isNotNull();
+ assertThat(keytabVolumeMount.getMountPath())
+ .isEqualTo(Constants.KERBEROS_KEYTAB_MOUNT_POINT);
+ assertThat(krb5ConfVolumeMount.getMountPath())
+ .isEqualTo(Constants.KERBEROS_KRB5CONF_MOUNT_DIR + "/krb5.conf");
}
@Test
- public void testDecoratedFlinkPodVolumes() {
+ void testDecoratedFlinkPodVolumes() {
final FlinkPod resultFlinkPod = kerberosMountDecorator.decorateFlinkPod(baseFlinkPod);
List<Volume> volumes = resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes();
- assertEquals(2, volumes.size());
+ assertThat(volumes).hasSize(2);
final Volume keytabVolume =
volumes.stream()
@@ -137,20 +135,21 @@ public class KerberosMountDecoratorTest extends KubernetesPodTestBase {
.filter(x -> x.getName().equals(Constants.KERBEROS_KRB5CONF_VOLUME))
.collect(Collectors.toList())
.get(0);
- assertNotNull(keytabVolume.getSecret());
- assertEquals(
- KerberosMountDecorator.getKerberosKeytabSecretName(
- testingKubernetesParameters.getClusterId()),
- keytabVolume.getSecret().getSecretName());
-
- assertNotNull(krb5ConfVolume.getConfigMap());
- assertEquals(
- KerberosMountDecorator.getKerberosKrb5confConfigMapName(
- testingKubernetesParameters.getClusterId()),
- krb5ConfVolume.getConfigMap().getName());
- assertEquals(1, krb5ConfVolume.getConfigMap().getItems().size());
- assertEquals(
- CUSTOM_KRB5_CONF_FILE, krb5ConfVolume.getConfigMap().getItems().get(0).getKey());
- assertEquals(KRB5_CONF_FILE, krb5ConfVolume.getConfigMap().getItems().get(0).getPath());
+ assertThat(keytabVolume.getSecret()).isNotNull();
+ assertThat(keytabVolume.getSecret().getSecretName())
+ .isEqualTo(
+ KerberosMountDecorator.getKerberosKeytabSecretName(
+ testingKubernetesParameters.getClusterId()));
+
+ assertThat(krb5ConfVolume.getConfigMap()).isNotNull();
+ assertThat(krb5ConfVolume.getConfigMap().getName())
+ .isEqualTo(
+ KerberosMountDecorator.getKerberosKrb5confConfigMapName(
+ testingKubernetesParameters.getClusterId()));
+ assertThat(krb5ConfVolume.getConfigMap().getItems()).hasSize(1);
+ assertThat(krb5ConfVolume.getConfigMap().getItems().get(0).getKey())
+ .isEqualTo(CUSTOM_KRB5_CONF_FILE);
+ assertThat(krb5ConfVolume.getConfigMap().getItems().get(0).getPath())
+ .isEqualTo(KRB5_CONF_FILE);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/MountSecretsDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/MountSecretsDecoratorTest.java
index f8db9ad94da..fac5a5acfc6 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/MountSecretsDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/MountSecretsDecoratorTest.java
@@ -23,13 +23,12 @@ import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkPod;
import org.apache.flink.kubernetes.kubeclient.KubernetesJobManagerTestBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link MountSecretsDecorator}. */
-public class MountSecretsDecoratorTest extends KubernetesJobManagerTestBase {
+class MountSecretsDecoratorTest extends KubernetesJobManagerTestBase {
private static final String SECRET_NAME = "test";
private static final String SECRET_MOUNT_PATH = "/opt/flink/secret";
@@ -53,25 +52,30 @@ public class MountSecretsDecoratorTest extends KubernetesJobManagerTestBase {
}
@Test
- public void testWhetherPodOrContainerIsDecorated() {
+ void testWhetherPodOrContainerIsDecorated() {
final FlinkPod resultFlinkPod = mountSecretsDecorator.decorateFlinkPod(baseFlinkPod);
- assertFalse(
- VolumeTestUtils.podHasVolume(
- baseFlinkPod.getPodWithoutMainContainer(), SECRET_NAME + "-volume"));
- assertTrue(
- VolumeTestUtils.podHasVolume(
- resultFlinkPod.getPodWithoutMainContainer(), SECRET_NAME + "-volume"));
+ assertThat(
+ VolumeTestUtils.podHasVolume(
+ baseFlinkPod.getPodWithoutMainContainer(), SECRET_NAME + "-volume"))
+ .isFalse();
+ assertThat(
+ VolumeTestUtils.podHasVolume(
+ resultFlinkPod.getPodWithoutMainContainer(),
+ SECRET_NAME + "-volume"))
+ .isTrue();
- assertFalse(
- VolumeTestUtils.containerHasVolume(
- baseFlinkPod.getMainContainer(),
- SECRET_NAME + "-volume",
- SECRET_MOUNT_PATH));
- assertTrue(
- VolumeTestUtils.containerHasVolume(
- resultFlinkPod.getMainContainer(),
- SECRET_NAME + "-volume",
- SECRET_MOUNT_PATH));
+ assertThat(
+ VolumeTestUtils.containerHasVolume(
+ baseFlinkPod.getMainContainer(),
+ SECRET_NAME + "-volume",
+ SECRET_MOUNT_PATH))
+ .isFalse();
+ assertThat(
+ VolumeTestUtils.containerHasVolume(
+ resultFlinkPod.getMainContainer(),
+ SECRET_NAME + "-volume",
+ SECRET_MOUNT_PATH))
+ .isTrue();
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/PodTemplateMountDecoratorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/PodTemplateMountDecoratorTest.java
index 7fe960a808c..018705bfb67 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/PodTemplateMountDecoratorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/PodTemplateMountDecoratorTest.java
@@ -18,7 +18,7 @@
package org.apache.flink.kubernetes.kubeclient.decorators;
-import org.apache.flink.core.testutils.FlinkMatchers;
+import org.apache.flink.core.testutils.FlinkAssertions;
import org.apache.flink.kubernetes.KubernetesTestUtils;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkPod;
@@ -33,7 +33,7 @@ import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeBuilder;
import io.fabric8.kubernetes.api.model.VolumeMount;
import io.fabric8.kubernetes.api.model.VolumeMountBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -42,13 +42,11 @@ import java.util.List;
import java.util.Map;
import static org.apache.flink.kubernetes.utils.Constants.TASK_MANAGER_POD_TEMPLATE_FILE_NAME;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** General tests for the {@link PodTemplateMountDecorator}. */
-public class PodTemplateMountDecoratorTest extends KubernetesJobManagerTestBase {
+class PodTemplateMountDecoratorTest extends KubernetesJobManagerTestBase {
private static final String POD_TEMPLATE_FILE_NAME = "testing-pod-template.yaml";
private static final String POD_TEMPLATE_DATA = "taskmanager pod template data";
@@ -73,37 +71,35 @@ public class PodTemplateMountDecoratorTest extends KubernetesJobManagerTestBase
}
@Test
- public void testBuildAccompanyingKubernetesResourcesAddsPodTemplateAsConfigMap()
- throws IOException {
+ void testBuildAccompanyingKubernetesResourcesAddsPodTemplateAsConfigMap() throws IOException {
KubernetesTestUtils.createTemporyFile(
POD_TEMPLATE_DATA, flinkConfDir, POD_TEMPLATE_FILE_NAME);
final List<HasMetadata> additionalResources =
podTemplateMountDecorator.buildAccompanyingKubernetesResources();
- assertThat(additionalResources.size(), is(1));
+ assertThat(additionalResources).hasSize(1);
final ConfigMap resultConfigMap = (ConfigMap) additionalResources.get(0);
final Map<String, String> resultData = resultConfigMap.getData();
- assertThat(resultData.get(TASK_MANAGER_POD_TEMPLATE_FILE_NAME), is(POD_TEMPLATE_DATA));
+ assertThat(resultData.get(TASK_MANAGER_POD_TEMPLATE_FILE_NAME))
+ .isEqualTo(POD_TEMPLATE_DATA);
}
@Test
- public void testDecoratorShouldFailWhenPodTemplateFileNotExist() {
- try {
- podTemplateMountDecorator.buildAccompanyingKubernetesResources();
- fail("Decorator should fail when the pod template file does not exist.");
- } catch (Exception ex) {
- final String msg =
- String.format(
- "Pod template file %s does not exist.",
- new File(flinkConfDir, POD_TEMPLATE_FILE_NAME));
- assertThat(ex, FlinkMatchers.containsMessage(msg));
- }
+ void testDecoratorShouldFailWhenPodTemplateFileNotExist() {
+ final String msg =
+ String.format(
+ "Pod template file %s does not exist.",
+ new File(flinkConfDir, POD_TEMPLATE_FILE_NAME));
+ assertThatThrownBy(
+ () -> podTemplateMountDecorator.buildAccompanyingKubernetesResources(),
+ "Decorator should fail when the pod template file does not exist.")
+ .satisfies(FlinkAssertions.anyCauseMatches(msg));
}
@Test
- public void testDecoratedFlinkPodWithTaskManagerPodTemplate() throws Exception {
+ void testDecoratedFlinkPodWithTaskManagerPodTemplate() throws Exception {
KubernetesTestUtils.createTemporyFile(
POD_TEMPLATE_DATA, flinkConfDir, POD_TEMPLATE_FILE_NAME);
@@ -116,9 +112,8 @@ public class PodTemplateMountDecoratorTest extends KubernetesJobManagerTestBase
.withPath(TASK_MANAGER_POD_TEMPLATE_FILE_NAME)
.build());
final List<Volume> expectedVolumes = getExpectedVolumes(expectedKeyToPaths);
- assertThat(
- resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes(),
- containsInAnyOrder(expectedVolumes.toArray()));
+ assertThat(resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes())
+ .containsExactlyInAnyOrderElementsOf(expectedVolumes);
final List<VolumeMount> expectedVolumeMounts =
Collections.singletonList(
@@ -126,9 +121,8 @@ public class PodTemplateMountDecoratorTest extends KubernetesJobManagerTestBase
.withName(Constants.POD_TEMPLATE_VOLUME)
.withMountPath(Constants.POD_TEMPLATE_DIR_IN_POD)
.build());
- assertThat(
- resultFlinkPod.getMainContainer().getVolumeMounts(),
- containsInAnyOrder(expectedVolumeMounts.toArray()));
+ assertThat(resultFlinkPod.getMainContainer().getVolumeMounts())
+ .containsExactlyInAnyOrderElementsOf(expectedVolumeMounts);
}
private List<Volume> getExpectedVolumes(List<KeyToPath> keyToPaths) {
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesFactoryWithPodTemplateTestBase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesFactoryWithPodTemplateTestBase.java
index 995900bac60..7deadb17a22 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesFactoryWithPodTemplateTestBase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesFactoryWithPodTemplateTestBase.java
@@ -37,14 +37,9 @@ import io.fabric8.kubernetes.api.model.EnvVarBuilder;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.Toleration;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import java.util.stream.Collectors;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.hasEntry;
-import static org.hamcrest.Matchers.hasItems;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* Test base for the {@link KubernetesJobManagerFactory} and {@link KubernetesTaskManagerFactory}
@@ -89,107 +84,105 @@ public abstract class KubernetesFactoryWithPodTemplateTestBase extends Kubernete
protected abstract Pod getResultPod(FlinkPod podTemplate) throws Exception;
@Test
- public void testInitContainerFromPodTemplate() {
- assertThat(resultPod.getSpec().getInitContainers().size(), is(1));
- assertThat(
- resultPod.getSpec().getInitContainers().get(0),
- // The expected init container is defined in the
- // test/resources/testing-pod-template.yaml.
- is(KubernetesPodTemplateTestUtils.createInitContainer()));
+ void testInitContainerFromPodTemplate() {
+ assertThat(resultPod.getSpec().getInitContainers())
+ .containsExactly(
+ // The expected init container is defined in the
+ // test/resources/testing-pod-template.yaml.
+ KubernetesPodTemplateTestUtils.createInitContainer());
}
@Test
- public void testSideCarContainerFromPodTemplate() {
+ void testSideCarContainerFromPodTemplate() {
final Container sideCarContainer =
KubernetesPodTemplateTestUtils.getContainerWithName(
resultPod.getSpec(),
KubernetesPodTemplateTestUtils.TESTING_SIDE_CAR_CONTAINER_NAME);
// The expected sidecar is defined in the test/resources/testing-pod-template.yaml.
- assertThat(sideCarContainer, is(KubernetesPodTemplateTestUtils.createSideCarContainer()));
+ assertThat(sideCarContainer)
+ .isEqualTo(KubernetesPodTemplateTestUtils.createSideCarContainer());
}
@Test
- public void testVolumesFromPodTemplate() {
- assertThat(
- resultPod.getSpec().getVolumes(),
- // The expected volume is defined in the test/resources/testing-pod-template.yaml.
- hasItems(KubernetesPodTemplateTestUtils.createVolumes()));
+ void testVolumesFromPodTemplate() {
+ assertThat(resultPod.getSpec().getVolumes())
+ .contains(
+ // The expected volume is defined in the
+ // test/resources/testing-pod-template.yaml.
+ KubernetesPodTemplateTestUtils.createVolumes());
}
@Test
- public void testMainContainerVolumeMountsFromPodTemplate() {
+ void testMainContainerVolumeMountsFromPodTemplate() {
final Container mainContainer =
KubernetesPodTemplateTestUtils.getContainerWithName(
resultPod.getSpec(), Constants.MAIN_CONTAINER_NAME);
- assertThat(
- mainContainer.getVolumeMounts(),
- // The expected volume mount is defined in the
- // test/resources/testing-pod-template.yaml.
- hasItems(KubernetesPodTemplateTestUtils.createVolumeMount()));
+ assertThat(mainContainer.getVolumeMounts())
+ .contains(
+ // The expected volume mount is defined in the
+ // test/resources/testing-pod-template.yaml.
+ KubernetesPodTemplateTestUtils.createVolumeMount());
}
@Test
- public void testAnnotationsFromPodTemplate() {
- assertThat(
- resultPod.getMetadata().getAnnotations(),
- // The expected annotation is defined in the
- // test/resources/testing-pod-template.yaml.
- hasEntry("annotation-key-of-pod-template", "annotation-value-of-pod-template"));
+ void testAnnotationsFromPodTemplate() {
+ assertThat(resultPod.getMetadata().getAnnotations())
+ .containsEntry(
+ // The expected annotation is defined in the
+ // test/resources/testing-pod-template.yaml.
+ "annotation-key-of-pod-template", "annotation-value-of-pod-template");
}
@Test
- public void testLabelsFromPodTemplate() {
- assertThat(
- resultPod.getMetadata().getLabels(),
- // The expected label is defined in the test/resources/testing-pod-template.yaml.
- hasEntry("label-key-of-pod-template", "label-value-of-pod-template"));
+ void testLabelsFromPodTemplate() {
+ assertThat(resultPod.getMetadata().getLabels())
+ .containsEntry(
+ // The expected label is defined in the
+ // test/resources/testing-pod-template.yaml.
+ "label-key-of-pod-template", "label-value-of-pod-template");
}
@Test
- public void testImagePullSecretsFromPodTemplate() {
+ void testImagePullSecretsFromPodTemplate() {
assertThat(
- resultPod.getSpec().getImagePullSecrets().stream()
- .map(LocalObjectReference::getName)
- .collect(Collectors.toList()),
- // The expected image pull secret is defined in the
- // test/resources/testing-pod-template.yaml.
- hasItems("image-pull-secret-of-pod-template"));
+ resultPod.getSpec().getImagePullSecrets().stream()
+ .map(LocalObjectReference::getName))
+ .contains(
+ // The expected image pull secret is defined in the
+ // test/resources/testing-pod-template.yaml.
+ "image-pull-secret-of-pod-template");
}
@Test
- public void testNodeSelectorsFromPodTemplate() {
- assertThat(
- resultPod.getSpec().getNodeSelector(),
- // The expected node selector is defined in the
- // test/resources/testing-pod-template.yaml.
- hasEntry(
- "node-selector-key-of-pod-template",
- "node-selector-value-of-pod-template"));
+ void testNodeSelectorsFromPodTemplate() {
+ assertThat(resultPod.getSpec().getNodeSelector())
+ .containsEntry(
+ // The expected node selector is defined in the
+ // test/resources/testing-pod-template.yaml.
+ "node-selector-key-of-pod-template", "node-selector-value-of-pod-template");
}
@Test
- public void testTolerationsFromPodTemplate() {
- assertThat(
- resultPod.getSpec().getTolerations().stream()
- .map(Toleration::getKey)
- .collect(Collectors.toList()),
- // The expected toleration is defined in the
- // test/resources/testing-pod-template.yaml.
- hasItems("key2-of-pod-template"));
+ void testTolerationsFromPodTemplate() {
+ assertThat(resultPod.getSpec().getTolerations().stream().map(Toleration::getKey))
+ .contains(
+ // The expected toleration is defined in the
+ // test/resources/testing-pod-template.yaml.
+ "key2-of-pod-template");
}
@Test
- public void testEnvFromPodTemplate() {
+ void testEnvFromPodTemplate() {
final Container mainContainer =
KubernetesPodTemplateTestUtils.getContainerWithName(
resultPod.getSpec(), Constants.MAIN_CONTAINER_NAME);
- assertThat(
- mainContainer.getEnv(),
- // The expected env is defined in the test/resources/testing-pod-template.yaml.
- hasItems(
+ assertThat(mainContainer.getEnv())
+ .contains(
+ // The expected env is defined in the
+ // test/resources/testing-pod-template.yaml.
new EnvVarBuilder()
.withName("ENV_OF_POD_TEMPLATE")
.withValue("env-value-of-pod-template")
- .build()));
+ .build());
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryTest.java
index bbf020fc070..be6f6357346 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryTest.java
@@ -49,8 +49,7 @@ import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentSpec;
-import org.hamcrest.Matchers;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Base64;
@@ -63,17 +62,10 @@ import java.util.stream.Collectors;
import static org.apache.flink.configuration.GlobalConfiguration.FLINK_CONF_FILENAME;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOG4J_NAME;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOGBACK_NAME;
-import static org.hamcrest.MatcherAssert.assertThat;
-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.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link KubernetesJobManagerFactory}. */
-public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBase {
+class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBase {
private static final String SERVICE_ACCOUNT_NAME = "service-test";
private static final String ENTRY_POINT_CLASS =
@@ -127,54 +119,52 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
}
@Test
- public void testDeploymentMetadata() throws IOException {
+ void testDeploymentMetadata() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
final Deployment resultDeployment = this.kubernetesJobManagerSpecification.getDeployment();
- assertEquals(Constants.APPS_API_VERSION, resultDeployment.getApiVersion());
- assertEquals(
- KubernetesUtils.getDeploymentName(CLUSTER_ID),
- resultDeployment.getMetadata().getName());
+ assertThat(resultDeployment.getApiVersion()).isEqualTo(Constants.APPS_API_VERSION);
+ assertThat(resultDeployment.getMetadata().getName())
+ .isEqualTo(KubernetesUtils.getDeploymentName(CLUSTER_ID));
final Map<String, String> expectedLabels = getCommonLabels();
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
expectedLabels.putAll(userLabels);
- assertEquals(expectedLabels, resultDeployment.getMetadata().getLabels());
+ assertThat(resultDeployment.getMetadata().getLabels()).isEqualTo(expectedLabels);
- assertThat(resultDeployment.getMetadata().getAnnotations(), equalTo(userAnnotations));
+ assertThat(resultDeployment.getMetadata().getAnnotations()).isEqualTo(userAnnotations);
- assertThat(
- resultDeployment.getMetadata().getOwnerReferences(),
- Matchers.containsInAnyOrder(OWNER_REFERENCES.toArray()));
+ assertThat(resultDeployment.getMetadata().getOwnerReferences())
+ .contains(OWNER_REFERENCES.toArray(new OwnerReference[0]));
}
@Test
- public void testDeploymentSpec() throws IOException {
+ void testDeploymentSpec() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
final DeploymentSpec resultDeploymentSpec =
this.kubernetesJobManagerSpecification.getDeployment().getSpec();
- assertEquals(1, resultDeploymentSpec.getReplicas().intValue());
+ assertThat(resultDeploymentSpec.getReplicas().intValue()).isEqualTo(1);
final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
- assertEquals(expectedLabels, resultDeploymentSpec.getSelector().getMatchLabels());
+ assertThat(resultDeploymentSpec.getSelector().getMatchLabels()).isEqualTo(expectedLabels);
expectedLabels.putAll(userLabels);
- assertEquals(expectedLabels, resultDeploymentSpec.getTemplate().getMetadata().getLabels());
+ assertThat(resultDeploymentSpec.getTemplate().getMetadata().getLabels())
+ .isEqualTo(expectedLabels);
- assertThat(
- resultDeploymentSpec.getTemplate().getMetadata().getAnnotations(),
- equalTo(userAnnotations));
+ assertThat(resultDeploymentSpec.getTemplate().getMetadata().getAnnotations())
+ .isEqualTo(userAnnotations);
- assertNotNull(resultDeploymentSpec.getTemplate().getSpec());
+ assertThat(resultDeploymentSpec.getTemplate().getSpec()).isNotNull();
}
@Test
- public void testPodSpec() throws IOException {
+ void testPodSpec() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
@@ -186,65 +176,65 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.getTemplate()
.getSpec();
- assertEquals(1, resultPodSpec.getContainers().size());
- assertEquals(SERVICE_ACCOUNT_NAME, resultPodSpec.getServiceAccountName());
- assertEquals(3, resultPodSpec.getVolumes().size());
+ assertThat(resultPodSpec.getContainers()).hasSize(1);
+ assertThat(resultPodSpec.getServiceAccountName()).isEqualTo(SERVICE_ACCOUNT_NAME);
+ assertThat(resultPodSpec.getVolumes()).hasSize(3);
final Container resultedMainContainer = resultPodSpec.getContainers().get(0);
- assertEquals(Constants.MAIN_CONTAINER_NAME, resultedMainContainer.getName());
- assertEquals(CONTAINER_IMAGE, resultedMainContainer.getImage());
- assertEquals(
- CONTAINER_IMAGE_PULL_POLICY.name(), resultedMainContainer.getImagePullPolicy());
+ assertThat(resultedMainContainer.getName()).isEqualTo(Constants.MAIN_CONTAINER_NAME);
+ assertThat(resultedMainContainer.getImage()).isEqualTo(CONTAINER_IMAGE);
+ assertThat(resultedMainContainer.getImagePullPolicy())
+ .isEqualTo(CONTAINER_IMAGE_PULL_POLICY.name());
- assertEquals(3, resultedMainContainer.getEnv().size());
- assertTrue(
- resultedMainContainer.getEnv().stream()
- .anyMatch(envVar -> envVar.getName().equals("key1")));
+ assertThat(resultedMainContainer.getEnv()).hasSize(3);
+ assertThat(resultedMainContainer.getEnv().stream())
+ .anyMatch(envVar -> envVar.getName().equals("key1"));
- assertEquals(3, resultedMainContainer.getPorts().size());
+ assertThat(resultedMainContainer.getPorts()).hasSize(3);
final Map<String, Quantity> requests = resultedMainContainer.getResources().getRequests();
- assertEquals(Double.toString(JOB_MANAGER_CPU), requests.get("cpu").getAmount());
- assertEquals(String.valueOf(JOB_MANAGER_MEMORY), requests.get("memory").getAmount());
+ assertThat(requests.get("cpu").getAmount()).isEqualTo(Double.toString(JOB_MANAGER_CPU));
+ assertThat(requests.get("memory").getAmount())
+ .isEqualTo(String.valueOf(JOB_MANAGER_MEMORY));
- assertEquals(1, resultedMainContainer.getCommand().size());
+ assertThat(resultedMainContainer.getCommand()).hasSize(1);
// The args list is [bash, -c, 'java -classpath $FLINK_CLASSPATH ...'].
- assertEquals(3, resultedMainContainer.getArgs().size());
+ assertThat(resultedMainContainer.getArgs()).hasSize(3);
- assertEquals(3, resultedMainContainer.getVolumeMounts().size());
+ assertThat(resultedMainContainer.getVolumeMounts()).hasSize(3);
}
@Test
- public void testAdditionalResourcesSize() throws IOException {
+ void testAdditionalResourcesSize() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
final List<HasMetadata> resultAdditionalResources =
this.kubernetesJobManagerSpecification.getAccompanyingResources();
- assertEquals(5, resultAdditionalResources.size());
+ assertThat(resultAdditionalResources).hasSize(5);
final List<HasMetadata> resultServices =
resultAdditionalResources.stream()
.filter(x -> x instanceof Service)
.collect(Collectors.toList());
- assertEquals(2, resultServices.size());
+ assertThat(resultServices).hasSize(2);
final List<HasMetadata> resultConfigMaps =
resultAdditionalResources.stream()
.filter(x -> x instanceof ConfigMap)
.collect(Collectors.toList());
- assertEquals(2, resultConfigMaps.size());
+ assertThat(resultConfigMaps).hasSize(2);
final List<HasMetadata> resultSecrets =
resultAdditionalResources.stream()
.filter(x -> x instanceof Secret)
.collect(Collectors.toList());
- assertEquals(1, resultSecrets.size());
+ assertThat(resultSecrets).hasSize(1);
}
@Test
- public void testServices() throws IOException {
+ void testServices() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
@@ -255,7 +245,7 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.map(x -> (Service) x)
.collect(Collectors.toList());
- assertEquals(2, resultServices.size());
+ assertThat(resultServices).hasSize(2);
final List<Service> internalServiceCandidates =
resultServices.stream()
@@ -268,7 +258,7 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.getInternalServiceName(
CLUSTER_ID)))
.collect(Collectors.toList());
- assertEquals(1, internalServiceCandidates.size());
+ assertThat(internalServiceCandidates).hasSize(1);
final List<Service> restServiceCandidates =
resultServices.stream()
@@ -281,28 +271,27 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.getExternalServiceName(
CLUSTER_ID)))
.collect(Collectors.toList());
- assertEquals(1, restServiceCandidates.size());
+ assertThat(restServiceCandidates).hasSize(1);
final Service resultInternalService = internalServiceCandidates.get(0);
- assertEquals(2, resultInternalService.getMetadata().getLabels().size());
+ assertThat(resultInternalService.getMetadata().getLabels()).hasSize(2);
- assertNull(resultInternalService.getSpec().getType());
- assertEquals(
- HeadlessClusterIPService.HEADLESS_CLUSTER_IP,
- resultInternalService.getSpec().getClusterIP());
- assertEquals(2, resultInternalService.getSpec().getPorts().size());
- assertEquals(3, resultInternalService.getSpec().getSelector().size());
+ assertThat(resultInternalService.getSpec().getType()).isNull();
+ assertThat(resultInternalService.getSpec().getClusterIP())
+ .isEqualTo(HeadlessClusterIPService.HEADLESS_CLUSTER_IP);
+ assertThat(resultInternalService.getSpec().getPorts()).hasSize(2);
+ assertThat(resultInternalService.getSpec().getSelector()).hasSize(3);
final Service resultRestService = restServiceCandidates.get(0);
- assertEquals(2, resultRestService.getMetadata().getLabels().size());
+ assertThat(resultRestService.getMetadata().getLabels()).hasSize(2);
- assertEquals("ClusterIP", resultRestService.getSpec().getType());
- assertEquals(1, resultRestService.getSpec().getPorts().size());
- assertEquals(3, resultRestService.getSpec().getSelector().size());
+ assertThat(resultRestService.getSpec().getType()).isEqualTo("ClusterIP");
+ assertThat(resultRestService.getSpec().getPorts()).hasSize(1);
+ assertThat(resultRestService.getSpec().getSelector()).hasSize(3);
}
@Test
- public void testKerberosConfConfigMap() throws IOException {
+ void testKerberosConfConfigMap() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
@@ -322,19 +311,18 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.collect(Collectors.toList())
.get(0);
- assertEquals(Constants.API_VERSION, resultConfigMap.getApiVersion());
+ assertThat(resultConfigMap.getApiVersion()).isEqualTo(Constants.API_VERSION);
- assertEquals(
- KerberosMountDecorator.getKerberosKrb5confConfigMapName(CLUSTER_ID),
- resultConfigMap.getMetadata().getName());
+ assertThat(resultConfigMap.getMetadata().getName())
+ .isEqualTo(KerberosMountDecorator.getKerberosKrb5confConfigMapName(CLUSTER_ID));
final Map<String, String> resultDatas = resultConfigMap.getData();
- assertEquals(1, resultDatas.size());
- assertEquals("some conf", resultDatas.get(KRB5_CONF_FILE));
+ assertThat(resultDatas).hasSize(1);
+ assertThat(resultDatas.get(KRB5_CONF_FILE)).isEqualTo("some conf");
}
@Test
- public void testKerberosKeytabSecret() throws IOException {
+ void testKerberosKeytabSecret() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
@@ -355,14 +343,13 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.get(0);
final Map<String, String> resultDatas = resultSecret.getData();
- assertEquals(1, resultDatas.size());
- assertEquals(
- Base64.getEncoder().encodeToString("some keytab".getBytes()),
- resultDatas.get(KEYTAB_FILE));
+ assertThat(resultDatas).hasSize(1);
+ assertThat(resultDatas.get(KEYTAB_FILE))
+ .isEqualTo(Base64.getEncoder().encodeToString("some keytab".getBytes()));
}
@Test
- public void testFlinkConfConfigMap() throws IOException {
+ void testFlinkConfConfigMap() throws IOException {
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
@@ -382,53 +369,48 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.collect(Collectors.toList())
.get(0);
- assertEquals(2, resultConfigMap.getMetadata().getLabels().size());
+ assertThat(resultConfigMap.getMetadata().getLabels()).hasSize(2);
final Map<String, String> resultDatas = resultConfigMap.getData();
- assertEquals(3, resultDatas.size());
- assertEquals("some data", resultDatas.get(CONFIG_FILE_LOG4J_NAME));
- assertEquals("some data", resultDatas.get(CONFIG_FILE_LOGBACK_NAME));
- assertTrue(
- resultDatas
- .get(FLINK_CONF_FILENAME)
- .contains(
- KubernetesConfigOptionsInternal.ENTRY_POINT_CLASS.key()
- + ": "
- + ENTRY_POINT_CLASS));
+ assertThat(resultDatas).hasSize(3);
+ assertThat(resultDatas.get(CONFIG_FILE_LOG4J_NAME)).isEqualTo("some data");
+ assertThat(resultDatas.get(CONFIG_FILE_LOGBACK_NAME)).isEqualTo("some data");
+ assertThat(resultDatas.get(FLINK_CONF_FILENAME))
+ .contains(
+ KubernetesConfigOptionsInternal.ENTRY_POINT_CLASS.key()
+ + ": "
+ + ENTRY_POINT_CLASS);
}
@Test
- public void testExistingHadoopConfigMap() throws IOException {
+ void testExistingHadoopConfigMap() throws IOException {
flinkConfig.set(
KubernetesConfigOptions.HADOOP_CONF_CONFIG_MAP, EXISTING_HADOOP_CONF_CONFIG_MAP);
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
- assertFalse(
- kubernetesJobManagerSpecification.getAccompanyingResources().stream()
- .anyMatch(
- resource ->
- resource.getMetadata()
- .getName()
- .equals(
- HadoopConfMountDecorator
- .getHadoopConfConfigMapName(
- CLUSTER_ID))));
+ assertThat(kubernetesJobManagerSpecification.getAccompanyingResources())
+ .noneMatch(
+ resource ->
+ resource.getMetadata()
+ .getName()
+ .equals(
+ HadoopConfMountDecorator.getHadoopConfConfigMapName(
+ CLUSTER_ID)));
final PodSpec podSpec =
kubernetesJobManagerSpecification.getDeployment().getSpec().getTemplate().getSpec();
- assertTrue(
- podSpec.getVolumes().stream()
- .anyMatch(
- volume ->
- volume.getConfigMap()
- .getName()
- .equals(EXISTING_HADOOP_CONF_CONFIG_MAP)));
+ assertThat(podSpec.getVolumes())
+ .anyMatch(
+ volume ->
+ volume.getConfigMap()
+ .getName()
+ .equals(EXISTING_HADOOP_CONF_CONFIG_MAP));
}
@Test
- public void testHadoopConfConfigMap() throws IOException {
+ void testHadoopConfConfigMap() throws IOException {
setHadoopConfDirEnv();
generateHadoopConfFileItems();
kubernetesJobManagerSpecification =
@@ -450,35 +432,33 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
.collect(Collectors.toList())
.get(0);
- assertEquals(2, resultConfigMap.getMetadata().getLabels().size());
+ assertThat(resultConfigMap.getMetadata().getLabels()).hasSize(2);
final Map<String, String> resultDatas = resultConfigMap.getData();
- assertEquals(2, resultDatas.size());
- assertEquals("some data", resultDatas.get("core-site.xml"));
- assertEquals("some data", resultDatas.get("hdfs-site.xml"));
+ assertThat(resultDatas).hasSize(2);
+ assertThat(resultDatas.get("core-site.xml")).isEqualTo("some data");
+ assertThat(resultDatas.get("hdfs-site.xml")).isEqualTo("some data");
}
@Test
- public void testEmptyHadoopConfDirectory() throws IOException {
+ void testEmptyHadoopConfDirectory() throws IOException {
setHadoopConfDirEnv();
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
- assertFalse(
- kubernetesJobManagerSpecification.getAccompanyingResources().stream()
- .anyMatch(
- resource ->
- resource.getMetadata()
- .getName()
- .equals(
- HadoopConfMountDecorator
- .getHadoopConfConfigMapName(
- CLUSTER_ID))));
+ assertThat(kubernetesJobManagerSpecification.getAccompanyingResources())
+ .noneMatch(
+ resource ->
+ resource.getMetadata()
+ .getName()
+ .equals(
+ HadoopConfMountDecorator.getHadoopConfConfigMapName(
+ CLUSTER_ID)));
}
@Test
- public void testSetJobManagerDeploymentReplicas() throws Exception {
+ void testSetJobManagerDeploymentReplicas() throws Exception {
flinkConfig.set(
HighAvailabilityOptions.HA_MODE,
KubernetesHaServicesFactory.class.getCanonicalName());
@@ -487,8 +467,7 @@ public class KubernetesJobManagerFactoryTest extends KubernetesJobManagerTestBas
kubernetesJobManagerSpecification =
KubernetesJobManagerFactory.buildKubernetesJobManagerSpecification(
flinkPod, kubernetesJobManagerParameters);
- assertThat(
- kubernetesJobManagerSpecification.getDeployment().getSpec().getReplicas(),
- is(JOBMANAGER_REPLICAS));
+ assertThat(kubernetesJobManagerSpecification.getDeployment().getSpec().getReplicas())
+ .isEqualTo(JOBMANAGER_REPLICAS);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryWithPodTemplateTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryWithPodTemplateTest.java
index e6937ede54c..b6fc8ffa1c4 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryWithPodTemplateTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesJobManagerFactoryWithPodTemplateTest.java
@@ -28,7 +28,7 @@ import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
/** General tests for the {@link KubernetesJobManagerFactory} with pod template. */
-public class KubernetesJobManagerFactoryWithPodTemplateTest
+class KubernetesJobManagerFactoryWithPodTemplateTest
extends KubernetesFactoryWithPodTemplateTestBase {
@Override
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryTest.java
index a01cb619b69..42f58e21717 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryTest.java
@@ -32,11 +32,10 @@ import java.util.List;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOG4J_NAME;
import static org.apache.flink.kubernetes.utils.Constants.CONFIG_FILE_LOGBACK_NAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** General tests for the {@link KubernetesTaskManagerFactory}. */
-public class KubernetesTaskManagerFactoryTest extends KubernetesTaskManagerTestBase {
+class KubernetesTaskManagerFactoryTest extends KubernetesTaskManagerTestBase {
private Pod resultPod;
@@ -70,31 +69,33 @@ public class KubernetesTaskManagerFactoryTest extends KubernetesTaskManagerTestB
}
@Test
- public void testPod() {
- assertEquals(POD_NAME, this.resultPod.getMetadata().getName());
- assertEquals(5, this.resultPod.getMetadata().getLabels().size());
- assertEquals(4, this.resultPod.getSpec().getVolumes().size());
+ void testPod() {
+ assertThat(this.resultPod.getMetadata().getName()).isEqualTo(POD_NAME);
+ assertThat(this.resultPod.getMetadata().getLabels()).hasSize(5);
+ assertThat(this.resultPod.getSpec().getVolumes()).hasSize(4);
}
@Test
- public void testContainer() {
+ void testContainer() {
final List<Container> resultContainers = this.resultPod.getSpec().getContainers();
- assertEquals(1, resultContainers.size());
+ assertThat(resultContainers).hasSize(1);
final Container resultMainContainer = resultContainers.get(0);
- assertEquals(Constants.MAIN_CONTAINER_NAME, resultMainContainer.getName());
- assertEquals(CONTAINER_IMAGE, resultMainContainer.getImage());
- assertEquals(CONTAINER_IMAGE_PULL_POLICY.name(), resultMainContainer.getImagePullPolicy());
-
- assertEquals(4, resultMainContainer.getEnv().size());
- assertTrue(
- resultMainContainer.getEnv().stream()
- .anyMatch(envVar -> envVar.getName().equals("key1")));
-
- assertEquals(1, resultMainContainer.getPorts().size());
- assertEquals(1, resultMainContainer.getCommand().size());
+ assertThat(resultMainContainer.getName()).isEqualTo(Constants.MAIN_CONTAINER_NAME);
+ assertThat(resultMainContainer.getImage()).isEqualTo(CONTAINER_IMAGE);
+ assertThat(resultMainContainer.getImagePullPolicy())
+ .isEqualTo(CONTAINER_IMAGE_PULL_POLICY.name());
+
+ assertThat(resultMainContainer.getEnv()).hasSize(4);
+ assertThat(
+ resultMainContainer.getEnv().stream()
+ .anyMatch(envVar -> envVar.getName().equals("key1")))
+ .isTrue();
+
+ assertThat(resultMainContainer.getPorts()).hasSize(1);
+ assertThat(resultMainContainer.getCommand()).hasSize(1);
// The args list is [bash, -c, 'java -classpath $FLINK_CLASSPATH ...'].
- assertEquals(3, resultMainContainer.getArgs().size());
- assertEquals(4, resultMainContainer.getVolumeMounts().size());
+ assertThat(resultMainContainer.getArgs()).hasSize(3);
+ assertThat(resultMainContainer.getVolumeMounts()).hasSize(4);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryWithPodTemplateTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryWithPodTemplateTest.java
index e0d10d3942e..dc50a3f3059 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryWithPodTemplateTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/factory/KubernetesTaskManagerFactoryWithPodTemplateTest.java
@@ -26,7 +26,7 @@ import io.fabric8.kubernetes.api.model.Pod;
import java.util.UUID;
/** General tests for the {@link KubernetesTaskManagerFactory} with pod template. */
-public class KubernetesTaskManagerFactoryWithPodTemplateTest
+class KubernetesTaskManagerFactoryWithPodTemplateTest
extends KubernetesFactoryWithPodTemplateTestBase {
@Override
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/AbstractKubernetesParametersTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/AbstractKubernetesParametersTest.java
index bbb019d0258..77dd53c7761 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/AbstractKubernetesParametersTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/AbstractKubernetesParametersTest.java
@@ -24,13 +24,14 @@ import org.apache.flink.core.testutils.CommonTestUtils;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.util.StringUtils;
-import org.apache.flink.util.TestLogger;
import org.apache.flink.util.function.RunnableWithException;
-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.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
@@ -38,68 +39,65 @@ import java.util.Map;
import java.util.Optional;
import java.util.Random;
-import static org.apache.flink.core.testutils.CommonTestUtils.assertThrows;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
+import static org.apache.flink.core.testutils.FlinkAssertions.anyCauseMatches;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** General tests for the {@link AbstractKubernetesParameters}. */
-public class AbstractKubernetesParametersTest extends TestLogger {
+public class AbstractKubernetesParametersTest {
private final Configuration flinkConfig = new Configuration();
private final TestingKubernetesParameters testingKubernetesParameters =
new TestingKubernetesParameters(flinkConfig);
- @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
@Test
- public void testClusterIdMustNotBeBlank() {
+ void testClusterIdMustNotBeBlank() {
flinkConfig.set(KubernetesConfigOptions.CLUSTER_ID, " ");
- assertThrows(
- "must not be blank",
- IllegalArgumentException.class,
- testingKubernetesParameters::getClusterId);
+ assertThatThrownBy(testingKubernetesParameters::getClusterId)
+ .satisfies(anyCauseMatches(IllegalArgumentException.class, "must not be blank"));
}
@Test
- public void testClusterIdLengthLimitation() {
+ void testClusterIdLengthLimitation() {
final String stringWithIllegalLength =
StringUtils.generateRandomAlphanumericString(
new Random(), Constants.MAXIMUM_CHARACTERS_OF_CLUSTER_ID + 1);
flinkConfig.set(KubernetesConfigOptions.CLUSTER_ID, stringWithIllegalLength);
- assertThrows(
- "must be no more than "
- + Constants.MAXIMUM_CHARACTERS_OF_CLUSTER_ID
- + " characters",
- IllegalArgumentException.class,
- testingKubernetesParameters::getClusterId);
+ assertThatThrownBy(testingKubernetesParameters::getClusterId)
+ .satisfies(
+ anyCauseMatches(
+ IllegalArgumentException.class,
+ "must be no more than "
+ + Constants.MAXIMUM_CHARACTERS_OF_CLUSTER_ID
+ + " characters"));
}
@Test
- public void getConfigDirectory() {
+ void getConfigDirectory() {
final String confDir = "/path/of/flink-conf";
flinkConfig.set(DeploymentOptionsInternal.CONF_DIR, confDir);
- assertThat(testingKubernetesParameters.getConfigDirectory(), is(confDir));
+ assertThat(testingKubernetesParameters.getConfigDirectory()).isEqualTo(confDir);
}
@Test
- public void getConfigDirectoryFallbackToPodConfDir() {
+ void getConfigDirectoryFallbackToPodConfDir() {
final String confDirInPod = flinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR);
- assertThat(testingKubernetesParameters.getConfigDirectory(), is(confDirInPod));
+ assertThat(testingKubernetesParameters.getConfigDirectory()).isEqualTo(confDirInPod);
}
@Test
- public void testGetLocalHadoopConfigurationDirectoryReturnEmptyWhenHadoopEnvIsNotSet()
+ void testGetLocalHadoopConfigurationDirectoryReturnEmptyWhenHadoopEnvIsNotSet()
throws Exception {
runTestWithEmptyEnv(
() -> {
final Optional<String> optional =
testingKubernetesParameters.getLocalHadoopConfigurationDirectory();
- assertThat(optional.isPresent(), is(false));
+ assertThat(optional).isNotPresent();
});
}
@Test
- public void testGetLocalHadoopConfigurationDirectoryFromHadoopConfDirEnv() throws Exception {
+ void testGetLocalHadoopConfigurationDirectoryFromHadoopConfDirEnv() throws Exception {
runTestWithEmptyEnv(
() -> {
final String hadoopConfDir = "/etc/hadoop/conf";
@@ -107,38 +105,40 @@ public class AbstractKubernetesParametersTest extends TestLogger {
final Optional<String> optional =
testingKubernetesParameters.getLocalHadoopConfigurationDirectory();
- assertThat(optional.isPresent(), is(true));
- assertThat(optional.get(), is(hadoopConfDir));
+ assertThat(optional).isPresent();
+ assertThat(optional.get()).isEqualTo(hadoopConfDir);
});
}
@Test
- public void testGetLocalHadoopConfigurationDirectoryFromHadoop2HomeEnv() throws Exception {
+ void testGetLocalHadoopConfigurationDirectoryFromHadoop2HomeEnv(@TempDir Path temporaryFolder)
+ throws Exception {
runTestWithEmptyEnv(
() -> {
- final String hadoopHome = temporaryFolder.getRoot().getAbsolutePath();
- temporaryFolder.newFolder("etc", "hadoop");
+ final String hadoopHome = temporaryFolder.toAbsolutePath().toString();
+ Files.createDirectories(temporaryFolder.resolve(Paths.get("etc", "hadoop")));
setEnv(Constants.ENV_HADOOP_HOME, hadoopHome);
final Optional<String> optional =
testingKubernetesParameters.getLocalHadoopConfigurationDirectory();
- assertThat(optional.isPresent(), is(true));
- assertThat(optional.get(), is(hadoopHome + "/etc/hadoop"));
+ assertThat(optional).isPresent();
+ assertThat(optional.get()).isEqualTo(hadoopHome + "/etc/hadoop");
});
}
@Test
- public void testGetLocalHadoopConfigurationDirectoryFromHadoop1HomeEnv() throws Exception {
+ void testGetLocalHadoopConfigurationDirectoryFromHadoop1HomeEnv(@TempDir Path temporaryFolder)
+ throws Exception {
runTestWithEmptyEnv(
() -> {
- final String hadoopHome = temporaryFolder.getRoot().getAbsolutePath();
- temporaryFolder.newFolder("conf");
+ final String hadoopHome = temporaryFolder.toAbsolutePath().toString();
+ Files.createDirectory(temporaryFolder.resolve("conf"));
setEnv(Constants.ENV_HADOOP_HOME, hadoopHome);
final Optional<String> optional =
testingKubernetesParameters.getLocalHadoopConfigurationDirectory();
- assertThat(optional.isPresent(), is(true));
- assertThat(optional.get(), is(hadoopHome + "/conf"));
+ assertThat(optional).isPresent();
+ assertThat(optional.get()).isEqualTo(hadoopHome + "/conf");
});
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesJobManagerParametersTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesJobManagerParametersTest.java
index 14ddd21dd57..0a44f015b9c 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesJobManagerParametersTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesJobManagerParametersTest.java
@@ -32,21 +32,17 @@ import org.apache.flink.kubernetes.highavailability.KubernetesHaServicesFactory;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.util.FlinkRuntimeException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-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.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.within;
/** General tests for the {@link KubernetesJobManagerParameters}. */
-public class KubernetesJobManagerParametersTest extends KubernetesTestBase {
+class KubernetesJobManagerParametersTest extends KubernetesTestBase {
private static final double JOB_MANAGER_CPU = 2.0;
private static final double JOB_MANAGER_CPU_LIMIT_FACTOR = 2.5;
@@ -63,7 +59,7 @@ public class KubernetesJobManagerParametersTest extends KubernetesTestBase {
new KubernetesJobManagerParameters(flinkConfig, clusterSpecification);
@Test
- public void testGetEnvironments() {
+ void testGetEnvironments() {
final Map<String, String> expectedEnvironments = new HashMap<>();
expectedEnvironments.put("k1", "v1");
expectedEnvironments.put("k2", "v2");
@@ -76,16 +72,16 @@ public class KubernetesJobManagerParametersTest extends KubernetesTestBase {
final Map<String, String> resultEnvironments =
kubernetesJobManagerParameters.getEnvironments();
- assertEquals(expectedEnvironments, resultEnvironments);
+ assertThat(resultEnvironments).isEqualTo(expectedEnvironments);
}
@Test
- public void testGetEmptyAnnotations() {
- assertTrue(kubernetesJobManagerParameters.getAnnotations().isEmpty());
+ void testGetEmptyAnnotations() {
+ assertThat(kubernetesJobManagerParameters.getAnnotations()).isEmpty();
}
@Test
- public void testGetJobManagerAnnotations() {
+ void testGetJobManagerAnnotations() {
final Map<String, String> expectedAnnotations = new HashMap<>();
expectedAnnotations.put("a1", "v1");
expectedAnnotations.put("a2", "v2");
@@ -95,11 +91,11 @@ public class KubernetesJobManagerParametersTest extends KubernetesTestBase {
final Map<String, String> resultAnnotations =
kubernetesJobManagerParameters.getAnnotations();
- assertThat(resultAnnotations, is(equalTo(expectedAnnotations)));
+ assertThat(resultAnnotations).isEqualTo(expectedAnnotations);
}
@Test
- public void testGetServiceAnnotations() {
+ void testGetServiceAnnotations() {
final Map<String, String> expectedAnnotations = new HashMap<>();
expectedAnnotations.put("a1", "v1");
expectedAnnotations.put("a2", "v2");
@@ -109,125 +105,123 @@ public class KubernetesJobManagerParametersTest extends KubernetesTestBase {
final Map<String, String> resultAnnotations =
kubernetesJobManagerParameters.getRestServiceAnnotations();
- assertThat(resultAnnotations, is(equalTo(expectedAnnotations)));
+ assertThat(resultAnnotations).isEqualTo(expectedAnnotations);
}
@Test
- public void testGetJobManagerMemoryMB() {
- assertEquals(JOB_MANAGER_MEMORY, kubernetesJobManagerParameters.getJobManagerMemoryMB());
+ void testGetJobManagerMemoryMB() {
+ assertThat(kubernetesJobManagerParameters.getJobManagerMemoryMB())
+ .isEqualTo(JOB_MANAGER_MEMORY);
}
@Test
- public void testGetJobManagerCPU() {
+ void testGetJobManagerCPU() {
flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_CPU, JOB_MANAGER_CPU);
- assertEquals(JOB_MANAGER_CPU, kubernetesJobManagerParameters.getJobManagerCPU(), 0.00001);
+ assertThat(kubernetesJobManagerParameters.getJobManagerCPU())
+ .isEqualTo(JOB_MANAGER_CPU, within(0.00001));
}
@Test
- public void testGetJobManagerCPULimitFactor() {
+ void testGetJobManagerCPULimitFactor() {
flinkConfig.set(
KubernetesConfigOptions.JOB_MANAGER_CPU_LIMIT_FACTOR, JOB_MANAGER_CPU_LIMIT_FACTOR);
- assertEquals(
- JOB_MANAGER_CPU_LIMIT_FACTOR,
- kubernetesJobManagerParameters.getJobManagerCPULimitFactor(),
- 0.00001);
+ assertThat(kubernetesJobManagerParameters.getJobManagerCPULimitFactor())
+ .isEqualTo(JOB_MANAGER_CPU_LIMIT_FACTOR, within(0.00001));
}
@Test
- public void testGetJobManagerMemoryLimitFactor() {
+ void testGetJobManagerMemoryLimitFactor() {
flinkConfig.set(
KubernetesConfigOptions.JOB_MANAGER_MEMORY_LIMIT_FACTOR,
JOB_MANAGER_MEMORY_LIMIT_FACTOR);
- assertEquals(
- JOB_MANAGER_MEMORY_LIMIT_FACTOR,
- kubernetesJobManagerParameters.getJobManagerMemoryLimitFactor(),
- 0.00001);
+ assertThat(kubernetesJobManagerParameters.getJobManagerMemoryLimitFactor())
+ .isEqualTo(JOB_MANAGER_MEMORY_LIMIT_FACTOR, within(0.00001));
}
@Test
- public void testGetRestPort() {
+ void testGetRestPort() {
flinkConfig.set(RestOptions.PORT, 12345);
- assertEquals(12345, kubernetesJobManagerParameters.getRestPort());
+ assertThat(kubernetesJobManagerParameters.getRestPort()).isEqualTo(12345);
}
@Test
- public void testGetRpcPort() {
+ void testGetRpcPort() {
flinkConfig.set(JobManagerOptions.PORT, 1234);
- assertEquals(1234, kubernetesJobManagerParameters.getRPCPort());
+ assertThat(kubernetesJobManagerParameters.getRPCPort()).isEqualTo(1234);
}
@Test
- public void testGetBlobServerPort() {
+ void testGetBlobServerPort() {
flinkConfig.set(BlobServerOptions.PORT, "2345");
- assertEquals(2345, kubernetesJobManagerParameters.getBlobServerPort());
+ assertThat(kubernetesJobManagerParameters.getBlobServerPort()).isEqualTo(2345);
}
@Test
- public void testGetBlobServerPortException1() {
+ void testGetBlobServerPortException1() {
flinkConfig.set(BlobServerOptions.PORT, "1000-2000");
-
- try {
- kubernetesJobManagerParameters.getBlobServerPort();
- fail("Should fail with an exception.");
- } catch (FlinkRuntimeException e) {
- assertThat(
- e.getMessage(),
- containsString(
- BlobServerOptions.PORT.key()
- + " should be specified to a fixed port. Do not support a range of ports."));
- }
+ String errMsg =
+ BlobServerOptions.PORT.key()
+ + " should be specified to a fixed port. Do not support a range of ports.";
+ assertThatThrownBy(
+ () -> kubernetesJobManagerParameters.getBlobServerPort(),
+ "Should fail with an exception.")
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(FlinkRuntimeException.class)
+ .hasMessageMatching(errMsg));
}
@Test
- public void testGetBlobServerPortException2() {
+ void testGetBlobServerPortException2() {
flinkConfig.set(BlobServerOptions.PORT, "0");
-
- try {
- kubernetesJobManagerParameters.getBlobServerPort();
- fail("Should fail with an exception.");
- } catch (IllegalArgumentException e) {
- assertThat(
- e.getMessage(),
- containsString(BlobServerOptions.PORT.key() + " should not be 0."));
- }
+ assertThatThrownBy(
+ () -> kubernetesJobManagerParameters.getBlobServerPort(),
+ "Should fail with an exception.")
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageMatching(
+ BlobServerOptions.PORT.key()
+ + " should not be 0."));
}
@Test
- public void testGetServiceAccount() {
+ void testGetServiceAccount() {
flinkConfig.set(KubernetesConfigOptions.JOB_MANAGER_SERVICE_ACCOUNT, "flink");
- assertThat(kubernetesJobManagerParameters.getServiceAccount(), is("flink"));
+ assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("flink");
}
@Test
- public void testGetServiceAccountFallback() {
+ void testGetServiceAccountFallback() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_SERVICE_ACCOUNT, "flink-fallback");
- assertThat(kubernetesJobManagerParameters.getServiceAccount(), is("flink-fallback"));
+ assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("flink-fallback");
}
@Test
- public void testGetServiceAccountShouldReturnDefaultIfNotExplicitlySet() {
- assertThat(kubernetesJobManagerParameters.getServiceAccount(), is("default"));
+ void testGetServiceAccountShouldReturnDefaultIfNotExplicitlySet() {
+ assertThat(kubernetesJobManagerParameters.getServiceAccount()).isEqualTo("default");
}
@Test
- public void testGetEntrypointMainClass() {
+ void testGetEntrypointMainClass() {
final String entrypointClass = "org.flink.kubernetes.Entrypoint";
flinkConfig.set(KubernetesConfigOptionsInternal.ENTRY_POINT_CLASS, entrypointClass);
- assertEquals(entrypointClass, kubernetesJobManagerParameters.getEntrypointClass());
+ assertThat(kubernetesJobManagerParameters.getEntrypointClass()).isEqualTo(entrypointClass);
}
@Test
- public void testGetRestServiceExposedType() {
+ void testGetRestServiceExposedType() {
flinkConfig.set(
KubernetesConfigOptions.REST_SERVICE_EXPOSED_TYPE,
KubernetesConfigOptions.ServiceExposedType.NodePort);
- assertEquals(
- KubernetesConfigOptions.ServiceExposedType.NodePort,
- kubernetesJobManagerParameters.getRestServiceExposedType());
+ assertThat(kubernetesJobManagerParameters.getRestServiceExposedType())
+ .isEqualByComparingTo(KubernetesConfigOptions.ServiceExposedType.NodePort);
}
@Test
- public void testPrioritizeBuiltInLabels() {
+ void testPrioritizeBuiltInLabels() {
final Map<String, String> userLabels = new HashMap<>();
userLabels.put(Constants.LABEL_TYPE_KEY, "user-label-type");
userLabels.put(Constants.LABEL_APP_KEY, "user-label-app");
@@ -237,27 +231,29 @@ public class KubernetesJobManagerParametersTest extends KubernetesTestBase {
final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_JOB_MANAGER);
- assertThat(kubernetesJobManagerParameters.getLabels(), is(equalTo(expectedLabels)));
+ assertThat(kubernetesJobManagerParameters.getLabels()).isEqualTo(expectedLabels);
}
- @Test(expected = IllegalConfigurationException.class)
+ @Test
public void testGetReplicasWithTwoShouldFailWhenHAIsNotEnabled() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_JOBMANAGER_REPLICAS, 2);
- kubernetesJobManagerParameters.getReplicas();
+ assertThatThrownBy(() -> kubernetesJobManagerParameters.getReplicas())
+ .isInstanceOf(IllegalConfigurationException.class);
}
- @Test(expected = IllegalConfigurationException.class)
+ @Test
public void testGetReplicasWithInvalidValue() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_JOBMANAGER_REPLICAS, 0);
- kubernetesJobManagerParameters.getReplicas();
+ assertThatThrownBy(() -> kubernetesJobManagerParameters.getReplicas())
+ .isInstanceOf(IllegalConfigurationException.class);
}
@Test
- public void testGetReplicas() {
+ void testGetReplicas() {
flinkConfig.set(
HighAvailabilityOptions.HA_MODE,
KubernetesHaServicesFactory.class.getCanonicalName());
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_JOBMANAGER_REPLICAS, 2);
- assertThat(kubernetesJobManagerParameters.getReplicas(), is(2));
+ assertThat(kubernetesJobManagerParameters.getReplicas()).isEqualTo(2);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesTaskManagerParametersTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesTaskManagerParametersTest.java
index ab5c0759acd..9f25517d721 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesTaskManagerParametersTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/parameters/KubernetesTaskManagerParametersTest.java
@@ -28,20 +28,17 @@ import org.apache.flink.runtime.clusterframework.ContaineredTaskManagerParameter
import org.apache.flink.runtime.clusterframework.TaskExecutorProcessSpec;
import org.apache.flink.runtime.clusterframework.TaskExecutorProcessUtils;
-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.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.within;
/** General tests for the {@link KubernetesTaskManagerParameters}. */
-public class KubernetesTaskManagerParametersTest extends KubernetesTestBase {
+class KubernetesTaskManagerParametersTest extends KubernetesTestBase {
private static final int TASK_MANAGER_MEMORY = 1024;
private static final double TASK_MANAGER_CPU = 1.2;
@@ -106,17 +103,17 @@ public class KubernetesTaskManagerParametersTest extends KubernetesTestBase {
}
@Test
- public void testGetEnvironments() {
- assertEquals(customizedEnvs, kubernetesTaskManagerParameters.getEnvironments());
+ void testGetEnvironments() {
+ assertThat(kubernetesTaskManagerParameters.getEnvironments()).isEqualTo(customizedEnvs);
}
@Test
- public void testGetEmptyAnnotations() {
- assertTrue(kubernetesTaskManagerParameters.getAnnotations().isEmpty());
+ void testGetEmptyAnnotations() {
+ assertThat(kubernetesTaskManagerParameters.getAnnotations()).isEmpty();
}
@Test
- public void testGetAnnotations() {
+ void testGetAnnotations() {
final Map<String, String> expectedAnnotations = new HashMap<>();
expectedAnnotations.put("a1", "v1");
expectedAnnotations.put("a2", "v2");
@@ -126,58 +123,56 @@ public class KubernetesTaskManagerParametersTest extends KubernetesTestBase {
final Map<String, String> resultAnnotations =
kubernetesTaskManagerParameters.getAnnotations();
- assertThat(resultAnnotations, is(equalTo(expectedAnnotations)));
+ assertThat(resultAnnotations).isEqualTo(expectedAnnotations);
}
@Test
- public void testGetPodName() {
- assertEquals(POD_NAME, kubernetesTaskManagerParameters.getPodName());
+ void testGetPodName() {
+ assertThat(kubernetesTaskManagerParameters.getPodName()).isEqualTo(POD_NAME);
}
@Test
- public void testGetTaskManagerMemoryMB() {
- assertEquals(TASK_MANAGER_MEMORY, kubernetesTaskManagerParameters.getTaskManagerMemoryMB());
+ void testGetTaskManagerMemoryMB() {
+ assertThat(kubernetesTaskManagerParameters.getTaskManagerMemoryMB())
+ .isEqualTo(TASK_MANAGER_MEMORY);
}
@Test
- public void testGetTaskManagerCPU() {
- assertEquals(
- TASK_MANAGER_CPU, kubernetesTaskManagerParameters.getTaskManagerCPU(), 0.00001);
+ void testGetTaskManagerCPU() {
+ assertThat(kubernetesTaskManagerParameters.getTaskManagerCPU())
+ .isEqualTo(TASK_MANAGER_CPU, within(0.00001));
}
@Test
- public void testGetTaskManagerCPULimitFactor() {
- assertEquals(
- TASK_MANAGER_CPU_LIMIT_FACTOR,
- kubernetesTaskManagerParameters.getTaskManagerCPULimitFactor(),
- 0.00001);
+ void testGetTaskManagerCPULimitFactor() {
+ assertThat(kubernetesTaskManagerParameters.getTaskManagerCPULimitFactor())
+ .isEqualTo(TASK_MANAGER_CPU_LIMIT_FACTOR, within(0.00001));
}
@Test
- public void testGetTaskManagerMemoryLimitFactor() {
- assertEquals(
- TASK_MANAGER_MEMORY_LIMIT_FACTOR,
- kubernetesTaskManagerParameters.getTaskManagerMemoryLimitFactor(),
- 0.00001);
+ void testGetTaskManagerMemoryLimitFactor() {
+ assertThat(kubernetesTaskManagerParameters.getTaskManagerMemoryLimitFactor())
+ .isEqualTo(TASK_MANAGER_MEMORY_LIMIT_FACTOR, within(0.00001));
}
@Test
- public void testGetRpcPort() {
- assertEquals(RPC_PORT, kubernetesTaskManagerParameters.getRPCPort());
+ void testGetRpcPort() {
+ assertThat(kubernetesTaskManagerParameters.getRPCPort()).isEqualTo(RPC_PORT);
}
@Test
- public void testGetDynamicProperties() {
- assertEquals(DYNAMIC_PROPERTIES, kubernetesTaskManagerParameters.getDynamicProperties());
+ void testGetDynamicProperties() {
+ assertThat(kubernetesTaskManagerParameters.getDynamicProperties())
+ .isEqualTo(DYNAMIC_PROPERTIES);
}
@Test
- public void testGetJvmMemOptsEnv() {
- assertThat(kubernetesTaskManagerParameters.getJvmMemOptsEnv(), is(JVM_MEM_OPTS_ENV));
+ void testGetJvmMemOptsEnv() {
+ assertThat(kubernetesTaskManagerParameters.getJvmMemOptsEnv()).isEqualTo(JVM_MEM_OPTS_ENV);
}
@Test
- public void testPrioritizeBuiltInLabels() {
+ void testPrioritizeBuiltInLabels() {
final Map<String, String> userLabels = new HashMap<>();
userLabels.put(Constants.LABEL_TYPE_KEY, "user-label-type");
userLabels.put(Constants.LABEL_APP_KEY, "user-label-app");
@@ -187,23 +182,23 @@ public class KubernetesTaskManagerParametersTest extends KubernetesTestBase {
final Map<String, String> expectedLabels = new HashMap<>(getCommonLabels());
expectedLabels.put(Constants.LABEL_COMPONENT_KEY, Constants.LABEL_COMPONENT_TASK_MANAGER);
- assertThat(kubernetesTaskManagerParameters.getLabels(), is(equalTo(expectedLabels)));
+ assertThat(kubernetesTaskManagerParameters.getLabels()).isEqualTo(expectedLabels);
}
@Test
- public void testGetServiceAccount() {
+ void testGetServiceAccount() {
flinkConfig.set(KubernetesConfigOptions.TASK_MANAGER_SERVICE_ACCOUNT, "flink");
- assertThat(kubernetesTaskManagerParameters.getServiceAccount(), is("flink"));
+ assertThat(kubernetesTaskManagerParameters.getServiceAccount()).isEqualTo("flink");
}
@Test
- public void testGetServiceAccountFallback() {
+ void testGetServiceAccountFallback() {
flinkConfig.set(KubernetesConfigOptions.KUBERNETES_SERVICE_ACCOUNT, "flink-fallback");
- assertThat(kubernetesTaskManagerParameters.getServiceAccount(), is("flink-fallback"));
+ assertThat(kubernetesTaskManagerParameters.getServiceAccount()).isEqualTo("flink-fallback");
}
@Test
- public void testGetServiceAccountShouldReturnDefaultIfNotExplicitlySet() {
- assertThat(kubernetesTaskManagerParameters.getServiceAccount(), is("default"));
+ void testGetServiceAccountShouldReturnDefaultIfNotExplicitlySet() {
+ assertThat(kubernetesTaskManagerParameters.getServiceAccount()).isEqualTo("default");
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/FlinkPodTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/FlinkPodTest.java
index a27ea8f2758..d632a82d1c1 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/FlinkPodTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/FlinkPodTest.java
@@ -23,32 +23,27 @@ import org.apache.flink.kubernetes.KubernetesTestBase;
import org.apache.flink.kubernetes.kubeclient.FlinkPod;
import org.apache.flink.kubernetes.utils.KubernetesUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for {@link FlinkPod}. */
-public class FlinkPodTest extends KubernetesTestBase {
+class FlinkPodTest extends KubernetesTestBase {
@Test
- public void testCopyFlinkPod() {
+ void testCopyFlinkPod() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
final FlinkPod copiedFlinkPod = flinkPod.copy();
- assertThat(flinkPod == copiedFlinkPod, is(false));
- assertThat(
- flinkPod.getPodWithoutMainContainer()
- == copiedFlinkPod.getPodWithoutMainContainer(),
- is(false));
- assertThat(
- flinkPod.getPodWithoutMainContainer(),
- is(equalTo(copiedFlinkPod.getPodWithoutMainContainer())));
- assertThat(flinkPod.getMainContainer() == copiedFlinkPod.getMainContainer(), is(false));
- assertThat(flinkPod.getMainContainer(), is(equalTo(copiedFlinkPod.getMainContainer())));
+ assertThat(flinkPod).isNotSameAs(copiedFlinkPod);
+ assertThat(flinkPod.getPodWithoutMainContainer())
+ .isNotSameAs(copiedFlinkPod.getPodWithoutMainContainer());
+ assertThat(flinkPod.getPodWithoutMainContainer())
+ .isEqualTo(copiedFlinkPod.getPodWithoutMainContainer());
+ assertThat(flinkPod.getMainContainer()).isNotSameAs(copiedFlinkPod.getMainContainer());
+ assertThat(flinkPod.getMainContainer()).isEqualTo(copiedFlinkPod.getMainContainer());
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorITCase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorITCase.java
index bce30694226..e97d23c6d54 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorITCase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorITCase.java
@@ -19,36 +19,33 @@
package org.apache.flink.kubernetes.kubeclient.resources;
import org.apache.flink.configuration.Configuration;
-import org.apache.flink.kubernetes.KubernetesResource;
+import org.apache.flink.kubernetes.KubernetesExtension;
import org.apache.flink.kubernetes.configuration.KubernetesLeaderElectionConfiguration;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
-import org.apache.flink.util.TestLogger;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.UUID;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
+import static org.assertj.core.api.Assertions.assertThat;
/**
* IT Tests for the {@link KubernetesLeaderElector}. Start multiple leader contenders currently, one
* should elect successfully. And if current leader dies, a new one could take over.
*/
-public class KubernetesLeaderElectorITCase extends TestLogger {
-
- @ClassRule public static KubernetesResource kubernetesResource = new KubernetesResource();
+class KubernetesLeaderElectorITCase {
+ @RegisterExtension
+ private static final KubernetesExtension kubernetesExtension = new KubernetesExtension();
private final FlinkKubeClientFactory kubeClientFactory = new FlinkKubeClientFactory();
private static final String LEADER_CONFIGMAP_NAME_PREFIX = "leader-test-cluster";
@Test
- public void testMultipleKubernetesLeaderElectors() throws Exception {
- final Configuration configuration = kubernetesResource.getConfiguration();
+ void testMultipleKubernetesLeaderElectors() throws Exception {
+ final Configuration configuration = kubernetesExtension.getConfiguration();
final String leaderConfigMapName =
LEADER_CONFIGMAP_NAME_PREFIX + System.currentTimeMillis();
@@ -85,21 +82,21 @@ public class KubernetesLeaderElectorITCase extends TestLogger {
if (leaderCallbackHandlers[i].getLockIdentity().equals(firstLockIdentity)) {
// Check the callback isLeader is called.
leaderCallbackHandlers[i].waitForNewLeader();
- assertThat(leaderCallbackHandlers[i].hasLeadership(), is(true));
+ assertThat(leaderCallbackHandlers[i].hasLeadership()).isTrue();
// Current leader died
leaderElectors[i].stop();
// Check the callback notLeader is called.
leaderCallbackHandlers[i].waitForRevokeLeader();
- assertThat(leaderCallbackHandlers[i].hasLeadership(), is(false));
+ assertThat(leaderCallbackHandlers[i].hasLeadership()).isFalse();
} else {
- assertThat(leaderCallbackHandlers[i].hasLeadership(), is(false));
+ assertThat(leaderCallbackHandlers[i].hasLeadership()).isFalse();
}
}
// Another leader should be elected successfully and update the lock identity
final String anotherLockIdentity =
TestingLeaderCallbackHandler.waitUntilNewLeaderAppears();
- assertThat(anotherLockIdentity, is(not(firstLockIdentity)));
+ assertThat(anotherLockIdentity).isNotEqualTo(firstLockIdentity);
} finally {
// Cleanup the resources
for (int i = 0; i < leaderNum; i++) {
@@ -110,7 +107,7 @@ public class KubernetesLeaderElectorITCase extends TestLogger {
kubeClients[i].close();
}
}
- kubernetesResource.getFlinkKubeClient().deleteConfigMap(leaderConfigMapName).get();
+ kubernetesExtension.getFlinkKubeClient().deleteConfigMap(leaderConfigMapName).get();
}
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorTest.java
index 7f0cd0cbdbc..9c6f9d2e544 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesLeaderElectorTest.java
@@ -21,16 +21,15 @@ package org.apache.flink.kubernetes.kubeclient.resources;
import org.apache.flink.kubernetes.KubernetesTestBase;
import org.apache.flink.kubernetes.kubeclient.TestingFlinkKubeClient;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.apache.flink.kubernetes.kubeclient.resources.KubernetesLeaderElector.LEADER_ANNOTATION_KEY;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for {@link KubernetesLeaderElector}. */
-public class KubernetesLeaderElectorTest extends KubernetesTestBase {
+class KubernetesLeaderElectorTest extends KubernetesTestBase {
private String lockIdentity;
private KubernetesConfigMap leaderConfigMap;
@@ -43,21 +42,21 @@ public class KubernetesLeaderElectorTest extends KubernetesTestBase {
}
@Test
- public void testNoAnnotation() {
- assertThat(KubernetesLeaderElector.hasLeadership(leaderConfigMap, lockIdentity), is(false));
+ void testNoAnnotation() {
+ assertThat(KubernetesLeaderElector.hasLeadership(leaderConfigMap, lockIdentity)).isFalse();
}
@Test
- public void testAnnotationNotMatch() {
+ void testAnnotationNotMatch() {
leaderConfigMap.getAnnotations().put(LEADER_ANNOTATION_KEY, "wrong lock");
- assertThat(KubernetesLeaderElector.hasLeadership(leaderConfigMap, lockIdentity), is(false));
+ assertThat(KubernetesLeaderElector.hasLeadership(leaderConfigMap, lockIdentity)).isFalse();
}
@Test
- public void testAnnotationMatched() {
+ void testAnnotationMatched() {
leaderConfigMap
.getAnnotations()
.put(LEADER_ANNOTATION_KEY, "other information " + lockIdentity);
- assertThat(KubernetesLeaderElector.hasLeadership(leaderConfigMap, lockIdentity), is(true));
+ assertThat(KubernetesLeaderElector.hasLeadership(leaderConfigMap, lockIdentity)).isTrue();
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodTest.java
index 0c4bdd2e9eb..0c35e1b3f5c 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodTest.java
@@ -18,21 +18,18 @@
package org.apache.flink.kubernetes.kubeclient.resources;
-import org.apache.flink.util.TestLogger;
-
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodStatusBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for {@link KubernetesPod}. */
-public class KubernetesPodTest extends TestLogger {
+class KubernetesPodTest {
@Test
- public void testIsTerminatedShouldReturnTrueWhenPodFailed() {
+ void testIsTerminatedShouldReturnTrueWhenPodFailed() {
final Pod pod = new PodBuilder().build();
pod.setStatus(
new PodStatusBuilder()
@@ -40,6 +37,6 @@ public class KubernetesPodTest extends TestLogger {
.withMessage("Pod Node didn't have enough resource")
.withReason("OutOfMemory")
.build());
- assertThat(new KubernetesPod(pod).isTerminated(), is(true));
+ assertThat(new KubernetesPod(pod).isTerminated()).isTrue();
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodsWatcherTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodsWatcherTest.java
index 2ec757d892d..f94caf85a04 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodsWatcherTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesPodsWatcherTest.java
@@ -18,18 +18,14 @@
package org.apache.flink.kubernetes.kubeclient.resources;
-import org.apache.flink.core.testutils.FlinkMatchers;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkPod;
-import org.apache.flink.util.TestLogger;
import io.fabric8.kubernetes.api.model.StatusBuilder;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
-import org.hamcrest.Matchers;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -37,11 +33,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import static java.net.HttpURLConnection.HTTP_GONE;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
/** Tests for {@link KubernetesPodsWatcher}. */
-public class KubernetesPodsWatcherTest extends TestLogger {
+class KubernetesPodsWatcherTest {
private final List<KubernetesPod> podAddedList = new ArrayList<>();
private final List<KubernetesPod> podModifiedList = new ArrayList<>();
@@ -49,24 +45,24 @@ public class KubernetesPodsWatcherTest extends TestLogger {
private final List<KubernetesPod> podErrorList = new ArrayList<>();
@Test
- public void testClosingWithNullException() {
+ void testClosingWithNullException() {
final KubernetesPodsWatcher podsWatcher =
new KubernetesPodsWatcher(
- new TestingCallbackHandler(e -> Assert.fail("Should not reach here.")));
+ new TestingCallbackHandler(e -> fail("Should not reach here.")));
podsWatcher.onClose(null);
}
@Test
- public void testClosingWithException() {
+ void testClosingWithException() {
final AtomicBoolean called = new AtomicBoolean(false);
final KubernetesPodsWatcher podsWatcher =
new KubernetesPodsWatcher(new TestingCallbackHandler(e -> called.set(true)));
podsWatcher.onClose(new WatcherException("exception"));
- assertThat(called.get(), is(true));
+ assertThat(called.get()).isTrue();
}
@Test
- public void testCallbackHandler() {
+ void testCallbackHandler() {
FlinkPod pod = new FlinkPod.Builder().build();
final KubernetesPodsWatcher podsWatcher =
new KubernetesPodsWatcher(new TestingCallbackHandler(e -> {}));
@@ -75,25 +71,23 @@ public class KubernetesPodsWatcherTest extends TestLogger {
podsWatcher.eventReceived(Watcher.Action.DELETED, pod.getPodWithoutMainContainer());
podsWatcher.eventReceived(Watcher.Action.ERROR, pod.getPodWithoutMainContainer());
- assertThat(podAddedList.size(), is(1));
- assertThat(podModifiedList.size(), is(1));
- assertThat(podDeletedList.size(), is(1));
- assertThat(podErrorList.size(), is(1));
+ assertThat(podAddedList).hasSize(1);
+ assertThat(podModifiedList).hasSize(1);
+ assertThat(podDeletedList).hasSize(1);
+ assertThat(podErrorList).hasSize(1);
}
@Test
- public void testClosingWithTooOldResourceVersion() {
+ void testClosingWithTooOldResourceVersion() {
final String errMsg = "too old resource version";
final KubernetesPodsWatcher podsWatcher =
new KubernetesPodsWatcher(
new TestingCallbackHandler(
e -> {
- assertThat(
- e,
- Matchers.instanceOf(
- KubernetesTooOldResourceVersionException
- .class));
- assertThat(e, FlinkMatchers.containsMessage(errMsg));
+ assertThat(e)
+ .isInstanceOf(
+ KubernetesTooOldResourceVersionException.class)
+ .hasMessageContaining(errMsg);
}));
podsWatcher.onClose(
new WatcherException(
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesSharedInformerITCase.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesSharedInformerITCase.java
index c54ea3e5bbe..3d3d5b3e02a 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesSharedInformerITCase.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesSharedInformerITCase.java
@@ -18,21 +18,21 @@
package org.apache.flink.kubernetes.kubeclient.resources;
-import org.apache.flink.kubernetes.KubernetesResource;
+import org.apache.flink.kubernetes.KubernetesExtension;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.KubernetesConfigMapSharedWatcher;
import org.apache.flink.kubernetes.kubeclient.KubernetesSharedWatcher.Watch;
import org.apache.flink.util.ExecutorUtils;
-import org.apache.flink.util.TestLogger;
import org.apache.flink.util.concurrent.ExecutorThreadFactory;
import org.apache.flink.shaded.guava30.com.google.common.collect.ImmutableMap;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.ClassRule;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.ArrayList;
import java.util.List;
@@ -44,16 +44,14 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-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.assertThatCode;
/** IT Tests for the {@link KubernetesSharedInformer}. */
-public class KubernetesSharedInformerITCase extends TestLogger {
+class KubernetesSharedInformerITCase {
- @ClassRule public static KubernetesResource kubernetesResource = new KubernetesResource();
+ @RegisterExtension
+ private static final KubernetesExtension kubernetesExtension = new KubernetesExtension();
private final ImmutableMap<String, String> labels =
ImmutableMap.of("app", "shared-informer-test-cluster");
@@ -61,20 +59,21 @@ public class KubernetesSharedInformerITCase extends TestLogger {
private FlinkKubeClient client;
private ExecutorService watchCallbackExecutorService;
- @Before
- public void setUp() throws Exception {
- client = kubernetesResource.getFlinkKubeClient();
+ @BeforeEach
+ void setUp() throws Exception {
+ client = kubernetesExtension.getFlinkKubeClient();
watchCallbackExecutorService =
Executors.newCachedThreadPool(new ExecutorThreadFactory("Watch-Callback"));
}
- @After
- public void tearDown() throws Exception {
+ @AfterEach
+ void tearDown() throws Exception {
ExecutorUtils.gracefulShutdown(5, TimeUnit.SECONDS, watchCallbackExecutorService);
client.deleteConfigMapsByLabels(labels).get();
}
- @Test(timeout = 120000)
+ @Test
+ @Timeout(120000)
public void testWatch() throws Exception {
try (KubernetesConfigMapSharedWatcher watcher =
@@ -91,7 +90,7 @@ public class KubernetesSharedInformerITCase extends TestLogger {
for (TestingCallbackHandler handler : callbackHandlers) {
handler.addFuture.get();
handler.addOrUpdateFuture.get();
- assertFalse(handler.assertFuture.isCompletedExceptionally());
+ assertThat(handler.assertFuture).isNotCompletedExceptionally();
}
watchers.forEach(Watch::close);
callbackHandlers.clear();
@@ -115,7 +114,7 @@ public class KubernetesSharedInformerITCase extends TestLogger {
}
@Test
- public void testWatchWithBlockHandler() throws Exception {
+ void testWatchWithBlockHandler() throws Exception {
try (KubernetesConfigMapSharedWatcher watcher =
client.createConfigMapSharedWatcher(labels)) {
@@ -129,11 +128,9 @@ public class KubernetesSharedInformerITCase extends TestLogger {
for (int i = 1; i <= maxUpdateVal; i++) {
updateConfigMap(configMapName, ImmutableMap.of("val", String.valueOf(i)));
}
- try {
- handler.expectedFuture.get(120, TimeUnit.SECONDS);
- } catch (TimeoutException e) {
- fail("expected value: " + maxUpdateVal + ", actual: " + handler.val);
- }
+ assertThatCode(() -> handler.expectedFuture.get(120, TimeUnit.SECONDS))
+ .as("expected value: " + maxUpdateVal + ", actual: " + handler.val)
+ .doesNotThrowAnyException();
try {
handler.assertFuture.get(2 * block, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
@@ -219,14 +216,14 @@ public class KubernetesSharedInformerITCase extends TestLogger {
check(
assertFuture,
() -> {
- assertThat(kubernetesConfigMap.getName(), is(resourceName));
- assertFalse(addFuture.isDone());
- assertFalse(addOrUpdateFuture.isDone());
+ assertThat(kubernetesConfigMap.getName()).isEqualTo(resourceName);
+ assertThat(addFuture).isNotDone();
+ assertThat(addOrUpdateFuture).isNotDone();
});
addFuture.complete(null);
final String foo = kubernetesConfigMap.getData().get("foo");
if (foo != null) {
- check(assertFuture, () -> assertThat(foo, is("bar")));
+ check(assertFuture, () -> assertThat(foo).isEqualTo("bar"));
addOrUpdateFuture.complete(null);
}
}
@@ -238,12 +235,12 @@ public class KubernetesSharedInformerITCase extends TestLogger {
check(
assertFuture,
() -> {
- assertThat(kubernetesConfigMap.getName(), is(resourceName));
- assertThat(foo, is("bar"));
- assertTrue(addFuture.isDone());
+ assertThat(kubernetesConfigMap.getName()).isEqualTo(resourceName);
+ assertThat(foo).isEqualTo("bar");
+ assertThat(addFuture).isDone();
});
if (addOrUpdateFuture.isDone()) {
- check(assertFuture, () -> assertTrue(isDeleting(kubernetesConfigMap)));
+ check(assertFuture, () -> assertThat(isDeleting(kubernetesConfigMap)).isTrue());
} else {
addOrUpdateFuture.complete(null);
}
@@ -251,7 +248,7 @@ public class KubernetesSharedInformerITCase extends TestLogger {
@Override
public void onDeleted(List<KubernetesConfigMap> resources) {
- check(assertFuture, () -> assertFalse(deleteFuture.isDone()));
+ check(assertFuture, () -> assertThat(deleteFuture).isNotDone());
deleteFuture.complete(null);
}
}
@@ -287,7 +284,9 @@ public class KubernetesSharedInformerITCase extends TestLogger {
return;
}
final long newVal = Long.parseLong(valData);
- check(assertFuture, () -> assertTrue(newVal > val || isDeleting(kubernetesConfigMap)));
+ check(
+ assertFuture,
+ () -> assertThat(newVal > val || isDeleting(kubernetesConfigMap)).isTrue());
val = newVal;
block();
if (expected == val) {
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/services/ServiceTypeTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/services/ServiceTypeTest.java
index 3a11ad65156..506bd530ddb 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/services/ServiceTypeTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/services/ServiceTypeTest.java
@@ -21,27 +21,23 @@ package org.apache.flink.kubernetes.kubeclient.services;
import org.apache.flink.kubernetes.KubernetesClientTestBase;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for {@link ServiceType}. */
-public class ServiceTypeTest extends KubernetesClientTestBase {
+class ServiceTypeTest extends KubernetesClientTestBase {
@Test
- public void testServiceClassify() {
- assertThat(
- ServiceType.classify(buildExternalServiceWithClusterIP()),
- is(KubernetesConfigOptions.ServiceExposedType.ClusterIP));
- assertThat(
- ServiceType.classify(buildExternalServiceWithHeadlessClusterIP()),
- is(KubernetesConfigOptions.ServiceExposedType.Headless_ClusterIP));
- assertThat(
- ServiceType.classify(buildExternalServiceWithNodePort()),
- is(KubernetesConfigOptions.ServiceExposedType.NodePort));
- assertThat(
- ServiceType.classify(buildExternalServiceWithLoadBalancer("", "")),
- is(KubernetesConfigOptions.ServiceExposedType.LoadBalancer));
+ void testServiceClassify() {
+ assertThat(ServiceType.classify(buildExternalServiceWithClusterIP()))
+ .isEqualByComparingTo(KubernetesConfigOptions.ServiceExposedType.ClusterIP);
+ assertThat(ServiceType.classify(buildExternalServiceWithHeadlessClusterIP()))
+ .isEqualByComparingTo(
+ KubernetesConfigOptions.ServiceExposedType.Headless_ClusterIP);
+ assertThat(ServiceType.classify(buildExternalServiceWithNodePort()))
+ .isEqualByComparingTo(KubernetesConfigOptions.ServiceExposedType.NodePort);
+ assertThat(ServiceType.classify(buildExternalServiceWithLoadBalancer("", "")))
+ .isEqualByComparingTo(KubernetesConfigOptions.ServiceExposedType.LoadBalancer);
}
}
diff --git a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/utils/KubernetesUtilsTest.java b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/utils/KubernetesUtilsTest.java
index 5de12968c6f..e7071a2b76f 100644
--- a/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/utils/KubernetesUtilsTest.java
+++ b/flink-kubernetes/src/test/java/org/apache/flink/kubernetes/utils/KubernetesUtilsTest.java
@@ -23,96 +23,92 @@ import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HighAvailabilityOptions;
-import org.apache.flink.core.testutils.FlinkMatchers;
+import org.apache.flink.core.testutils.FlinkAssertions;
import org.apache.flink.kubernetes.KubernetesPodTemplateTestUtils;
import org.apache.flink.kubernetes.KubernetesTestBase;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkPod;
import org.apache.flink.util.FlinkRuntimeException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link KubernetesUtils}. */
-public class KubernetesUtilsTest extends KubernetesTestBase {
+class KubernetesUtilsTest extends KubernetesTestBase {
private static final FlinkPod EMPTY_POD = new FlinkPod.Builder().build();
@Test
- public void testParsePortRange() {
+ void testParsePortRange() {
final Configuration cfg = new Configuration();
cfg.set(BlobServerOptions.PORT, "50100-50200");
- try {
- KubernetesUtils.parsePort(cfg, BlobServerOptions.PORT);
- fail("Should fail with an exception.");
- } catch (FlinkRuntimeException e) {
- assertThat(
- e.getMessage(),
- containsString(
- BlobServerOptions.PORT.key()
- + " should be specified to a fixed port. Do not support a range of ports."));
- }
+ assertThatThrownBy(
+ () -> KubernetesUtils.parsePort(cfg, BlobServerOptions.PORT),
+ "Should fail with an exception.")
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(FlinkRuntimeException.class)
+ .hasMessageContaining(BlobServerOptions.PORT.key()));
}
@Test
- public void testParsePortNull() {
+ void testParsePortNull() {
final Configuration cfg = new Configuration();
ConfigOption<String> testingPort =
ConfigOptions.key("test.port").stringType().noDefaultValue();
- try {
- KubernetesUtils.parsePort(cfg, testingPort);
- fail("Should fail with an exception.");
- } catch (NullPointerException e) {
- assertThat(e.getMessage(), containsString(testingPort.key() + " should not be null."));
- }
+ assertThatThrownBy(
+ () -> KubernetesUtils.parsePort(cfg, testingPort),
+ "Should fail with an exception.")
+ .satisfies(
+ cause ->
+ assertThat(cause)
+ .isInstanceOf(NullPointerException.class)
+ .hasMessageContaining(
+ testingPort.key() + " should not be null."));
}
@Test
- public void testCheckWithDynamicPort() {
+ void testCheckWithDynamicPort() {
testCheckAndUpdatePortConfigOption("0", "6123", "6123");
}
@Test
- public void testCheckWithFixedPort() {
+ void testCheckWithFixedPort() {
testCheckAndUpdatePortConfigOption("6123", "16123", "6123");
}
@Test
- public void testLoadPodFromTemplateWithNonExistPathShouldFail() {
+ void testLoadPodFromTemplateWithNonExistPathShouldFail() {
final String nonExistFile = "/path/of/non-exist.yaml";
- try {
- KubernetesUtils.loadPodFromTemplateFile(
- flinkKubeClient,
- new File(nonExistFile),
- KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
- fail("Kubernetes client should fail when the pod template file does not exist.");
- } catch (Exception ex) {
- final String msg = String.format("Pod template file %s does not exist.", nonExistFile);
- assertThat(ex, FlinkMatchers.containsMessage(msg));
- }
+ final String msg = String.format("Pod template file %s does not exist.", nonExistFile);
+ assertThatThrownBy(
+ () ->
+ KubernetesUtils.loadPodFromTemplateFile(
+ flinkKubeClient,
+ new File(nonExistFile),
+ KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME),
+ "Kubernetes client should fail when the pod template file does not exist.")
+ .satisfies(FlinkAssertions.anyCauseMatches(msg));
}
@Test
- public void testLoadPodFromTemplateWithNoMainContainerShouldReturnEmptyMainContainer() {
+ void testLoadPodFromTemplateWithNoMainContainerShouldReturnEmptyMainContainer() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
"nonExistMainContainer");
- assertThat(flinkPod.getMainContainer(), is(EMPTY_POD.getMainContainer()));
- assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getContainers().size(), is(2));
+ assertThat(flinkPod.getMainContainer()).isEqualTo(EMPTY_POD.getMainContainer());
+ assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getContainers()).hasSize(2);
}
@Test
- public void testLoadPodFromTemplateAndCheckMetaData() {
+ void testLoadPodFromTemplateAndCheckMetaData() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
@@ -120,66 +116,60 @@ public class KubernetesUtilsTest extends KubernetesTestBase {
KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
// The pod name is defined in the test/resources/testing-pod-template.yaml.
final String expectedPodName = "pod-template";
- assertThat(
- flinkPod.getPodWithoutMainContainer().getMetadata().getName(), is(expectedPodName));
+ assertThat(flinkPod.getPodWithoutMainContainer().getMetadata().getName())
+ .isEqualTo(expectedPodName);
}
@Test
- public void testLoadPodFromTemplateAndCheckInitContainer() {
+ void testLoadPodFromTemplateAndCheckInitContainer() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
- assertThat(
- flinkPod.getPodWithoutMainContainer().getSpec().getInitContainers().size(), is(1));
- assertThat(
- flinkPod.getPodWithoutMainContainer().getSpec().getInitContainers().get(0),
- is(KubernetesPodTemplateTestUtils.createInitContainer()));
+ assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getInitContainers()).hasSize(1);
+ assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getInitContainers().get(0))
+ .isEqualTo(KubernetesPodTemplateTestUtils.createInitContainer());
}
@Test
- public void testLoadPodFromTemplateAndCheckMainContainer() {
+ void testLoadPodFromTemplateAndCheckMainContainer() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
- assertThat(
- flinkPod.getMainContainer().getName(),
- is(KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME));
- assertThat(
- flinkPod.getMainContainer().getVolumeMounts(),
- containsInAnyOrder(KubernetesPodTemplateTestUtils.createVolumeMount()));
+ assertThat(flinkPod.getMainContainer().getName())
+ .isEqualTo(KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
+ assertThat(flinkPod.getMainContainer().getVolumeMounts())
+ .contains(KubernetesPodTemplateTestUtils.createVolumeMount());
}
@Test
- public void testLoadPodFromTemplateAndCheckSideCarContainer() {
+ void testLoadPodFromTemplateAndCheckSideCarContainer() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
- assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getContainers().size(), is(1));
- assertThat(
- flinkPod.getPodWithoutMainContainer().getSpec().getContainers().get(0),
- is(KubernetesPodTemplateTestUtils.createSideCarContainer()));
+ assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getContainers()).hasSize(1);
+ assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getContainers().get(0))
+ .isEqualTo(KubernetesPodTemplateTestUtils.createSideCarContainer());
}
@Test
- public void testLoadPodFromTemplateAndCheckVolumes() {
+ void testLoadPodFromTemplateAndCheckVolumes() {
final FlinkPod flinkPod =
KubernetesUtils.loadPodFromTemplateFile(
flinkKubeClient,
KubernetesPodTemplateTestUtils.getPodTemplateFile(),
KubernetesPodTemplateTestUtils.TESTING_MAIN_CONTAINER_NAME);
- assertThat(
- flinkPod.getPodWithoutMainContainer().getSpec().getVolumes(),
- containsInAnyOrder(KubernetesPodTemplateTestUtils.createVolumes()));
+ assertThat(flinkPod.getPodWithoutMainContainer().getSpec().getVolumes())
+ .contains(KubernetesPodTemplateTestUtils.createVolumes());
}
@Test
- public void testResolveUserDefinedValueWithNotDefinedInPodTemplate() {
+ void testResolveUserDefinedValueWithNotDefinedInPodTemplate() {
final String resolvedImage =
KubernetesUtils.resolveUserDefinedValue(
flinkConfig,
@@ -187,11 +177,11 @@ public class KubernetesUtilsTest extends KubernetesTestBase {
CONTAINER_IMAGE,
null,
"container image");
- assertThat(resolvedImage, is(CONTAINER_IMAGE));
+ assertThat(resolvedImage).isEqualTo(CONTAINER_IMAGE);
}
@Test
- public void testResolveUserDefinedValueWithDefinedInPodTemplateAndConfigOptionExplicitlySet() {
+ void testResolveUserDefinedValueWithDefinedInPodTemplateAndConfigOptionExplicitlySet() {
final String imageInPodTemplate = "image-in-pod-template:v1";
final String resolvedImage =
KubernetesUtils.resolveUserDefinedValue(
@@ -200,11 +190,11 @@ public class KubernetesUtilsTest extends KubernetesTestBase {
CONTAINER_IMAGE,
imageInPodTemplate,
"container image");
- assertThat(resolvedImage, is(CONTAINER_IMAGE));
+ assertThat(resolvedImage).isEqualTo(CONTAINER_IMAGE);
}
@Test
- public void testResolveUserDefinedValueWithDefinedInPodTemplateAndConfigOptionNotSet() {
+ void testResolveUserDefinedValueWithDefinedInPodTemplateAndConfigOptionNotSet() {
final String imageInPodTemplate = "image-in-pod-template:v1";
final String resolvedImage =
KubernetesUtils.resolveUserDefinedValue(
@@ -213,7 +203,7 @@ public class KubernetesUtilsTest extends KubernetesTestBase {
CONTAINER_IMAGE,
imageInPodTemplate,
"container image");
- assertThat(resolvedImage, is(imageInPodTemplate));
+ assertThat(resolvedImage).isEqualTo(imageInPodTemplate);
}
private void testCheckAndUpdatePortConfigOption(
@@ -224,6 +214,7 @@ public class KubernetesUtilsTest extends KubernetesTestBase {
cfg,
HighAvailabilityOptions.HA_JOB_MANAGER_PORT_RANGE,
Integer.valueOf(fallbackPort));
- assertEquals(expectedPort, cfg.get(HighAvailabilityOptions.HA_JOB_MANAGER_PORT_RANGE));
+ assertThat(cfg.get(HighAvailabilityOptions.HA_JOB_MANAGER_PORT_RANGE))
+ .isEqualTo(expectedPort);
}
}
diff --git a/flink-kubernetes/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension b/flink-kubernetes/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension
new file mode 100644
index 00000000000..0b74fd4603c
--- /dev/null
+++ b/flink-kubernetes/src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension
@@ -0,0 +1,16 @@
+# 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.
+
+org.apache.flink.util.TestLoggerExtension
diff --git a/flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/junit5/MiniClusterExtension.java b/flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/junit5/MiniClusterExtension.java
index 4f880be56e0..fc21e1694cf 100644
--- a/flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/junit5/MiniClusterExtension.java
+++ b/flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/junit5/MiniClusterExtension.java
@@ -241,7 +241,9 @@ public final class MiniClusterExtension
@Override
public void afterAll(ExtensionContext context) throws Exception {
- internalMiniClusterExtension.afterAll(context);
+ if (internalMiniClusterExtension != null) {
+ internalMiniClusterExtension.afterAll(context);
+ }
}
// Implementation