You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by fa...@apache.org on 2024/05/11 08:59:07 UTC
(flink) branch master updated: [FLINK-25537] [JUnit5 Migration] Module: flink-core with,Package: util (#24670)
This is an automated email from the ASF dual-hosted git repository.
fanrui 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 5af9acba5b9 [FLINK-25537] [JUnit5 Migration] Module: flink-core with,Package: util (#24670)
5af9acba5b9 is described below
commit 5af9acba5b9fbcdf9aadf62310cd337d508158c3
Author: gongzhongqiang <go...@gigacloudtech.com>
AuthorDate: Sat May 11 16:58:57 2024 +0800
[FLINK-25537] [JUnit5 Migration] Module: flink-core with,Package: util (#24670)
---------
Co-authored-by: Rui Fan <19...@gmail.com>
Co-authored-by: Jiabao Sun <32...@qq.com>
---
.../java/org/apache/flink/util/AbstractIDTest.java | 56 ++--
.../java/org/apache/flink/util/ArrayUtilsTest.java | 32 +-
.../apache/flink/util/ClassLoaderUtilsTest.java | 145 ++++-----
.../apache/flink/util/CloseableIteratorTest.java | 27 +-
.../org/apache/flink/util/CollectionUtilTest.java | 150 +++++----
.../flink/util/CompressedSerializedValueTest.java | 53 ++--
.../org/apache/flink/util/ExceptionUtilsTest.java | 99 +++---
.../java/org/apache/flink/util/FileUtilsTest.java | 42 ++-
.../flink/util/FlinkUserCodeClassLoaderTest.java | 31 +-
.../flink/util/FlinkUserCodeClassLoadersTest.java | 106 +++----
.../java/org/apache/flink/util/IOUtilsTest.java | 19 +-
.../apache/flink/util/InstantiationUtilTest.java | 143 ++++-----
.../org/apache/flink/util/IterableUtilsTest.java | 10 +-
.../java/org/apache/flink/util/LambdaUtilTest.java | 19 +-
.../apache/flink/util/LinkedOptionalMapTest.java | 98 +++---
.../flink/util/LongValueSequenceIteratorTest.java | 23 +-
.../java/org/apache/flink/util/MathUtilTest.java | 238 +++++++-------
.../java/org/apache/flink/util/MdcUtilsTest.java | 16 +-
.../java/org/apache/flink/util/NetUtilsTest.java | 341 +++++++++------------
.../flink/util/NumberSequenceIteratorTest.java | 23 +-
.../java/org/apache/flink/util/OutputTagTest.java | 34 +-
.../flink/util/ProcessorArchitectureTest.java | 17 +-
.../org/apache/flink/util/PropertiesUtilTest.java | 14 +-
.../java/org/apache/flink/util/ReferenceTest.java | 14 +-
.../org/apache/flink/util/ResourceGuardTest.java | 90 +++---
.../org/apache/flink/util/SerializedValueTest.java | 83 +++--
.../org/apache/flink/util/StringUtilsTest.java | 47 ++-
.../apache/flink/util/StringValueUtilsTest.java | 28 +-
.../util/TemporaryClassLoaderContextTest.java | 14 +-
.../org/apache/flink/util/TernaryBooleanTest.java | 59 ++--
.../java/org/apache/flink/util/TimeUtilsTest.java | 196 ++++++------
.../org/apache/flink/util/UnionIteratorTest.java | 171 ++++-------
.../apache/flink/util/WrappingProxyUtilTest.java | 35 +--
.../flink/util/concurrent/ConjunctFutureTest.java | 187 +++++------
.../ExponentialBackoffRetryStrategyTest.java | 12 +-
.../util/concurrent/FixedRetryStrategyTest.java | 8 +-
.../flink/util/concurrent/FutureUtilsTest.java | 19 +-
.../IncrementalDelayRetryStrategyTest.java | 12 +-
.../flink/util/function/CachingSupplierTest.java | 9 +-
39 files changed, 1221 insertions(+), 1499 deletions(-)
diff --git a/flink-core/src/test/java/org/apache/flink/util/AbstractIDTest.java b/flink-core/src/test/java/org/apache/flink/util/AbstractIDTest.java
index 8c809b75f3a..bde559ebca6 100644
--- a/flink-core/src/test/java/org/apache/flink/util/AbstractIDTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/AbstractIDTest.java
@@ -20,44 +20,40 @@ package org.apache.flink.util;
import org.apache.flink.core.testutils.CommonTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.InputStream;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** This class contains tests for the {@link org.apache.flink.util.AbstractID} class. */
-public class AbstractIDTest extends TestLogger {
+class AbstractIDTest {
/** Tests the serialization/deserialization of an abstract ID. */
@Test
- public void testSerialization() throws Exception {
+ void testSerialization() throws Exception {
final AbstractID origID = new AbstractID();
final AbstractID copyID = CommonTestUtils.createCopySerializable(origID);
- assertEquals(origID.hashCode(), copyID.hashCode());
- assertEquals(origID, copyID);
+ assertThat(copyID).hasSameHashCodeAs(origID.hashCode());
+ assertThat(copyID).isEqualTo(origID);
}
@Test
- public void testConvertToBytes() throws Exception {
+ void testConvertToBytes() {
final AbstractID origID = new AbstractID();
AbstractID copy1 = new AbstractID(origID);
AbstractID copy2 = new AbstractID(origID.getBytes());
AbstractID copy3 = new AbstractID(origID.getLowerPart(), origID.getUpperPart());
- assertEquals(origID, copy1);
- assertEquals(origID, copy2);
- assertEquals(origID, copy3);
+ assertThat(copy1).isEqualTo(origID);
+ assertThat(copy2).isEqualTo(origID);
+ assertThat(copy3).isEqualTo(origID);
}
@Test
- public void testCompare() throws Exception {
+ void testCompare() throws Exception {
AbstractID id1 = new AbstractID(0, 0);
AbstractID id2 = new AbstractID(1, 0);
AbstractID id3 = new AbstractID(0, 1);
@@ -71,16 +67,16 @@ public class AbstractIDTest extends TestLogger {
AbstractID id10 = new AbstractID(Long.MIN_VALUE, Long.MAX_VALUE);
// test self equality
- assertEquals(0, id1.compareTo(CommonTestUtils.createCopySerializable(id1)));
- assertEquals(0, id2.compareTo(CommonTestUtils.createCopySerializable(id2)));
- assertEquals(0, id3.compareTo(CommonTestUtils.createCopySerializable(id3)));
- assertEquals(0, id4.compareTo(CommonTestUtils.createCopySerializable(id4)));
- assertEquals(0, id5.compareTo(CommonTestUtils.createCopySerializable(id5)));
- assertEquals(0, id6.compareTo(CommonTestUtils.createCopySerializable(id6)));
- assertEquals(0, id7.compareTo(CommonTestUtils.createCopySerializable(id7)));
- assertEquals(0, id8.compareTo(CommonTestUtils.createCopySerializable(id8)));
- assertEquals(0, id9.compareTo(CommonTestUtils.createCopySerializable(id9)));
- assertEquals(0, id10.compareTo(CommonTestUtils.createCopySerializable(id10)));
+ assertThat(id1).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id1));
+ assertThat(id2).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id2));
+ assertThat(id3).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id3));
+ assertThat(id4).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id4));
+ assertThat(id5).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id5));
+ assertThat(id6).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id6));
+ assertThat(id7).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id7));
+ assertThat(id8).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id8));
+ assertThat(id9).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id9));
+ assertThat(id10).isEqualByComparingTo(CommonTestUtils.createCopySerializable(id10));
// test order
assertCompare(id1, id2, -1);
@@ -109,7 +105,7 @@ public class AbstractIDTest extends TestLogger {
* abstractID-with-toString-field-set have been created with the serialized data.
*/
@Test
- public void testOldAbstractIDDeserialization() throws Exception {
+ void testOldAbstractIDDeserialization() throws Exception {
final long lowerPart = 42L;
final long upperPart = 1337L;
final AbstractID expectedAbstractId = new AbstractID(lowerPart, upperPart);
@@ -120,7 +116,7 @@ public class AbstractIDTest extends TestLogger {
final AbstractID deserializedAbstractId =
InstantiationUtil.deserializeObject(
resourceAsStream, getClass().getClassLoader());
- assertThat(deserializedAbstractId, is(equalTo(expectedAbstractId)));
+ assertThat(deserializedAbstractId).isEqualTo(expectedAbstractId);
}
final String resourceName2 = "abstractID-with-toString-field-set";
@@ -129,7 +125,7 @@ public class AbstractIDTest extends TestLogger {
final AbstractID deserializedAbstractId =
InstantiationUtil.deserializeObject(
resourceAsStream, getClass().getClassLoader());
- assertThat(deserializedAbstractId, is(equalTo(expectedAbstractId)));
+ assertThat(deserializedAbstractId).isEqualTo(expectedAbstractId);
}
}
@@ -140,7 +136,7 @@ public class AbstractIDTest extends TestLogger {
int sgnAB = cmpAB > 0 ? 1 : (cmpAB < 0 ? -1 : 0);
int sgnBA = cmpBA > 0 ? 1 : (cmpBA < 0 ? -1 : 0);
- assertEquals(signum, sgnAB);
- assertTrue(sgnAB == -sgnBA);
+ assertThat(sgnAB).isEqualTo(signum);
+ assertThat(-sgnBA).isEqualTo(sgnAB);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/ArrayUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/ArrayUtilsTest.java
index 02284eb26c3..357ae3d9065 100644
--- a/flink-core/src/test/java/org/apache/flink/util/ArrayUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/ArrayUtilsTest.java
@@ -18,42 +18,32 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link ArrayUtils}. */
-public class ArrayUtilsTest extends TestLogger {
+class ArrayUtilsTest {
@Test
- public void concatWithEmptyArray() {
+ void concatWithEmptyArray() {
String[] emptyArray = new String[] {};
String[] nonEmptyArray = new String[] {"some value"};
- assertThat(
- "Should return the non empty array",
- ArrayUtils.concat(emptyArray, nonEmptyArray),
- sameInstance(nonEmptyArray));
+ assertThat(ArrayUtils.concat(emptyArray, nonEmptyArray)).isSameAs(nonEmptyArray);
- assertThat(
- "Should return the non empty array",
- ArrayUtils.concat(nonEmptyArray, emptyArray),
- sameInstance(nonEmptyArray));
+ assertThat(ArrayUtils.concat(nonEmptyArray, emptyArray)).isSameAs(nonEmptyArray);
}
@Test
- public void concatArrays() {
+ void concatArrays() {
String[] array1 = new String[] {"A", "B", "C", "D", "E", "F", "G"};
String[] array2 = new String[] {"1", "2", "3"};
- assertThat(
- ArrayUtils.concat(array1, array2),
- is(new String[] {"A", "B", "C", "D", "E", "F", "G", "1", "2", "3"}));
+ assertThat(ArrayUtils.concat(array1, array2))
+ .isEqualTo(new String[] {"A", "B", "C", "D", "E", "F", "G", "1", "2", "3"});
- assertThat(
- ArrayUtils.concat(array2, array1),
- is(new String[] {"1", "2", "3", "A", "B", "C", "D", "E", "F", "G"}));
+ assertThat(ArrayUtils.concat(array2, array1))
+ .isEqualTo(new String[] {"1", "2", "3", "A", "B", "C", "D", "E", "F", "G"});
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/ClassLoaderUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/ClassLoaderUtilsTest.java
index 3574bced1ab..b0e44ff32cb 100644
--- a/flink-core/src/test/java/org/apache/flink/util/ClassLoaderUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/ClassLoaderUtilsTest.java
@@ -18,7 +18,7 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileOutputStream;
@@ -31,82 +31,67 @@ import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests that validate the {@link ClassLoaderUtil}. */
-public class ClassLoaderUtilsTest {
+class ClassLoaderUtilsTest {
@Test
- public void testWithURLClassLoader() {
- File validJar = null;
- File invalidJar = null;
+ void testWithURLClassLoader() throws Exception {
+ File validJar;
+ File invalidJar;
- try {
- // file with jar contents
- validJar = File.createTempFile("flink-url-test", ".tmp");
- createValidJar(validJar);
-
- // validate that the JAR is correct and the test setup is not broken
- JarFile jarFile = null;
- try {
- jarFile = new JarFile(validJar.getAbsolutePath());
- } catch (Exception e) {
- e.printStackTrace();
- fail("test setup broken: cannot create a valid jar file");
- } finally {
- if (jarFile != null) {
- jarFile.close();
- }
- }
-
- // file with some random contents
- invalidJar = File.createTempFile("flink-url-test", ".tmp");
- try (FileOutputStream invalidout = new FileOutputStream(invalidJar)) {
- invalidout.write(
- new byte[] {
- -1, 1, -2, 3, -3, 4,
- });
- }
+ // file with jar contents
+ validJar = File.createTempFile("flink-url-test", ".tmp");
+ createValidJar(validJar);
- // non existing file
- File nonExisting = File.createTempFile("flink-url-test", ".tmp");
- assertTrue("Cannot create and delete temp file", nonExisting.delete());
-
- // create a URL classloader with
- // - a HTTP URL
- // - a file URL for an existing jar file
- // - a file URL for an existing file that is not a jar file
- // - a file URL for a non-existing file
-
- URL[] urls = {
- new URL("http", "localhost", 26712, "/some/file/path"),
- new URL("file", null, validJar.getAbsolutePath()),
- new URL("file", null, invalidJar.getAbsolutePath()),
- new URL("file", null, nonExisting.getAbsolutePath()),
- };
-
- URLClassLoader loader = new URLClassLoader(urls, getClass().getClassLoader());
- String info = ClassLoaderUtil.getUserCodeClassLoaderInfo(loader);
-
- assertTrue(info.indexOf("/some/file/path") > 0);
- assertTrue(info.indexOf(validJar.getAbsolutePath() + "' (valid") > 0);
- assertTrue(info.indexOf(invalidJar.getAbsolutePath() + "' (invalid JAR") > 0);
- assertTrue(info.indexOf(nonExisting.getAbsolutePath() + "' (missing") > 0);
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
+ // validate that the JAR is correct and the test setup is not broken
+ JarFile jarFile = null;
+ try {
+ jarFile = new JarFile(validJar.getAbsolutePath());
} finally {
- if (validJar != null) {
- //noinspection ResultOfMethodCallIgnored
- validJar.delete();
- }
- if (invalidJar != null) {
- //noinspection ResultOfMethodCallIgnored
- invalidJar.delete();
+ if (jarFile != null) {
+ jarFile.close();
}
}
+
+ // file with some random contents
+ invalidJar = File.createTempFile("flink-url-test", ".tmp");
+ try (FileOutputStream invalidout = new FileOutputStream(invalidJar)) {
+ invalidout.write(
+ new byte[] {
+ -1, 1, -2, 3, -3, 4,
+ });
+ }
+
+ // non existing file
+ File nonExisting = File.createTempFile("flink-url-test", ".tmp");
+ assertThat(nonExisting.delete()).isTrue();
+
+ // create a URL classloader with
+ // - a HTTP URL
+ // - a file URL for an existing jar file
+ // - a file URL for an existing file that is not a jar file
+ // - a file URL for a non-existing file
+
+ URL[] urls = {
+ new URL("http", "localhost", 26712, "/some/file/path"),
+ new URL("file", null, validJar.getAbsolutePath()),
+ new URL("file", null, invalidJar.getAbsolutePath()),
+ new URL("file", null, nonExisting.getAbsolutePath()),
+ };
+
+ URLClassLoader loader = new URLClassLoader(urls, getClass().getClassLoader());
+ String info = ClassLoaderUtil.getUserCodeClassLoaderInfo(loader);
+
+ assertThat(info).contains("/some/file/path");
+ assertThat(info).contains(validJar.getAbsolutePath() + "' (valid");
+ assertThat(info).contains(invalidJar.getAbsolutePath() + "' (invalid JAR");
+ assertThat(info).contains(nonExisting.getAbsolutePath() + "' (missing");
+ //noinspection ResultOfMethodCallIgnored
+ validJar.delete();
+ //noinspection ResultOfMethodCallIgnored
+ invalidJar.delete();
}
private static void createValidJar(final File jarFile) throws Exception {
@@ -135,25 +120,15 @@ public class ClassLoaderUtilsTest {
}
@Test
- public void testWithAppClassLoader() {
- try {
- String result =
- ClassLoaderUtil.getUserCodeClassLoaderInfo(ClassLoader.getSystemClassLoader());
- assertTrue(result.toLowerCase().contains("system classloader"));
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testWithAppClassLoader() {
+ String result =
+ ClassLoaderUtil.getUserCodeClassLoaderInfo(ClassLoader.getSystemClassLoader());
+ assertThat(result.toLowerCase()).contains("system classloader");
}
@Test
- public void testInvalidClassLoaders() {
- try {
- // must return something when invoked with 'null'
- assertNotNull(ClassLoaderUtil.getUserCodeClassLoaderInfo(null));
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testInvalidClassLoaders() {
+ // must return something when invoked with 'null'
+ assertThat(ClassLoaderUtil.getUserCodeClassLoaderInfo(null)).isNotNull();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/CloseableIteratorTest.java b/flink-core/src/test/java/org/apache/flink/util/CloseableIteratorTest.java
index ed1f7a7be5f..8abb3091255 100644
--- a/flink-core/src/test/java/org/apache/flink/util/CloseableIteratorTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/CloseableIteratorTest.java
@@ -17,36 +17,36 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static java.util.Arrays.asList;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertFalse;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** {@link CloseableIterator} test. */
@SuppressWarnings("unchecked")
-public class CloseableIteratorTest {
+class CloseableIteratorTest {
private static final String[] ELEMENTS = new String[] {"element-1", "element-2"};
@Test
- public void testFlattenEmpty() throws Exception {
+ void testFlattenEmpty() throws Exception {
List<CloseableIterator<?>> iterators =
asList(
CloseableIterator.flatten(),
CloseableIterator.flatten(CloseableIterator.empty()),
CloseableIterator.flatten(CloseableIterator.flatten()));
for (CloseableIterator<?> i : iterators) {
- assertFalse(i.hasNext());
+ assertThat(i).isExhausted();
i.close();
}
}
@Test
- public void testFlattenIteration() {
+ void testFlattenIteration() {
CloseableIterator<String> iterator =
CloseableIterator.flatten(
CloseableIterator.ofElement(ELEMENTS[0], unused -> {}),
@@ -54,11 +54,11 @@ public class CloseableIteratorTest {
List<String> iterated = new ArrayList<>();
iterator.forEachRemaining(iterated::add);
- assertArrayEquals(ELEMENTS, iterated.toArray());
+ assertThat(iterated.toArray()).isEqualTo(ELEMENTS);
}
- @Test(expected = TestException.class)
- public void testFlattenErrorHandling() throws Exception {
+ @Test
+ void testFlattenErrorHandling() {
List<String> closed = new ArrayList<>();
CloseableIterator<String> iterator =
CloseableIterator.flatten(
@@ -69,11 +69,8 @@ public class CloseableIteratorTest {
throw new TestException();
}),
CloseableIterator.ofElement(ELEMENTS[1], closed::add));
- try {
- iterator.close();
- } finally {
- assertArrayEquals(ELEMENTS, closed.toArray());
- }
+ assertThatThrownBy(iterator::close).isInstanceOf(TestException.class);
+ assertThat(closed.toArray()).isEqualTo(ELEMENTS);
}
private static class TestException extends RuntimeException {}
diff --git a/flink-core/src/test/java/org/apache/flink/util/CollectionUtilTest.java b/flink-core/src/test/java/org/apache/flink/util/CollectionUtilTest.java
index 50493316e51..a4c4c42111f 100644
--- a/flink-core/src/test/java/org/apache/flink/util/CollectionUtilTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/CollectionUtilTest.java
@@ -18,9 +18,7 @@
package org.apache.flink.util;
-import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
import java.util.ArrayList;
import java.util.Arrays;
@@ -31,14 +29,13 @@ import java.util.List;
import static org.apache.flink.util.CollectionUtil.HASH_MAP_DEFAULT_LOAD_FACTOR;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.fail;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for java collection utilities. */
-@ExtendWith(TestLoggerExtension.class)
-public class CollectionUtilTest {
+class CollectionUtilTest {
@Test
- public void testPartition() {
+ void testPartition() {
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Collection<List<Integer>> partitioned = CollectionUtil.partition(list, 4);
@@ -49,87 +46,81 @@ public class CollectionUtilTest {
}
@Test
- public void testOfNullableWithNull() {
+ void testOfNullableWithNull() {
assertThat(CollectionUtil.ofNullable(null)).isEmpty();
}
@Test
- public void testFromNullableWithObject() {
+ void testFromNullableWithObject() {
final Object element = new Object();
assertThat(CollectionUtil.ofNullable(element)).singleElement().isEqualTo(element);
}
@Test
- public void testComputeCapacity() {
- Assertions.assertEquals(
- 1, CollectionUtil.computeRequiredCapacity(0, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 2, CollectionUtil.computeRequiredCapacity(1, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 3, CollectionUtil.computeRequiredCapacity(2, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 4, CollectionUtil.computeRequiredCapacity(3, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 6, CollectionUtil.computeRequiredCapacity(4, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 7, CollectionUtil.computeRequiredCapacity(5, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 8, CollectionUtil.computeRequiredCapacity(6, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 10, CollectionUtil.computeRequiredCapacity(7, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 11, CollectionUtil.computeRequiredCapacity(8, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 134, CollectionUtil.computeRequiredCapacity(100, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 1334, CollectionUtil.computeRequiredCapacity(1000, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- 13334, CollectionUtil.computeRequiredCapacity(10000, HASH_MAP_DEFAULT_LOAD_FACTOR));
-
- Assertions.assertEquals(20000, CollectionUtil.computeRequiredCapacity(10000, 0.5f));
-
- Assertions.assertEquals(100000, CollectionUtil.computeRequiredCapacity(10000, 0.1f));
-
- Assertions.assertEquals(
- 1431655808,
- CollectionUtil.computeRequiredCapacity(
- Integer.MAX_VALUE / 2, HASH_MAP_DEFAULT_LOAD_FACTOR));
- Assertions.assertEquals(
- Integer.MAX_VALUE,
- CollectionUtil.computeRequiredCapacity(
- 1 + Integer.MAX_VALUE / 2, HASH_MAP_DEFAULT_LOAD_FACTOR));
-
- try {
- CollectionUtil.computeRequiredCapacity(-1, HASH_MAP_DEFAULT_LOAD_FACTOR);
- Assertions.fail();
- } catch (IllegalArgumentException expected) {
- }
-
- try {
- CollectionUtil.computeRequiredCapacity(Integer.MIN_VALUE, HASH_MAP_DEFAULT_LOAD_FACTOR);
- Assertions.fail();
- } catch (IllegalArgumentException expected) {
- }
+ void testComputeCapacity() {
+ assertThat(CollectionUtil.computeRequiredCapacity(0, HASH_MAP_DEFAULT_LOAD_FACTOR)).isOne();
+ assertThat(CollectionUtil.computeRequiredCapacity(1, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(2);
+ assertThat(CollectionUtil.computeRequiredCapacity(2, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(3);
+ assertThat(CollectionUtil.computeRequiredCapacity(3, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(4);
+ assertThat(CollectionUtil.computeRequiredCapacity(4, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(6);
+ assertThat(CollectionUtil.computeRequiredCapacity(5, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(7);
+ assertThat(CollectionUtil.computeRequiredCapacity(6, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(8);
+ assertThat(CollectionUtil.computeRequiredCapacity(7, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(10);
+ assertThat(CollectionUtil.computeRequiredCapacity(8, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(11);
+ assertThat(CollectionUtil.computeRequiredCapacity(100, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(134);
+ assertThat(CollectionUtil.computeRequiredCapacity(1000, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(1334);
+ assertThat(CollectionUtil.computeRequiredCapacity(10000, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(13334);
+
+ assertThat(
+ CollectionUtil.computeRequiredCapacity(
+ Integer.MAX_VALUE / 2, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(1431655808);
+
+ assertThat(
+ CollectionUtil.computeRequiredCapacity(
+ 1 + Integer.MAX_VALUE / 2, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isEqualTo(Integer.MAX_VALUE);
+
+ assertThatThrownBy(
+ () ->
+ CollectionUtil.computeRequiredCapacity(
+ -1, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isInstanceOf(IllegalArgumentException.class);
+
+ assertThatThrownBy(
+ () ->
+ CollectionUtil.computeRequiredCapacity(
+ Integer.MIN_VALUE, HASH_MAP_DEFAULT_LOAD_FACTOR))
+ .isInstanceOf(IllegalArgumentException.class);
}
@Test
- public void testIsEmptyOrAllElementsNull() {
- Assertions.assertTrue(CollectionUtil.isEmptyOrAllElementsNull(Collections.emptyList()));
- Assertions.assertTrue(
- CollectionUtil.isEmptyOrAllElementsNull(Collections.singletonList(null)));
- Assertions.assertTrue(CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList(null, null)));
- Assertions.assertFalse(
- CollectionUtil.isEmptyOrAllElementsNull(Collections.singletonList("test")));
- Assertions.assertFalse(
- CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList(null, "test")));
- Assertions.assertFalse(
- CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList("test", null)));
- Assertions.assertFalse(
- CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList(null, "test", null)));
+ void testIsEmptyOrAllElementsNull() {
+ assertThat(CollectionUtil.isEmptyOrAllElementsNull(Collections.emptyList())).isTrue();
+ assertThat(CollectionUtil.isEmptyOrAllElementsNull(Collections.singletonList(null)))
+ .isTrue();
+ assertThat(CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList(null, null))).isTrue();
+ assertThat(CollectionUtil.isEmptyOrAllElementsNull(Collections.singletonList("test")))
+ .isFalse();
+ assertThat(CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList(null, "test"))).isFalse();
+ assertThat(CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList("test", null))).isFalse();
+ assertThat(CollectionUtil.isEmptyOrAllElementsNull(Arrays.asList(null, "test", null)))
+ .isFalse();
}
@Test
- public void testCheckedSubTypeCast() {
+ void testCheckedSubTypeCast() {
List<A> list = new ArrayList<>();
B b = new B();
C c = new C();
@@ -138,15 +129,12 @@ public class CollectionUtilTest {
list.add(null);
Collection<B> castSuccess = CollectionUtil.checkedSubTypeCast(list, B.class);
Iterator<B> iterator = castSuccess.iterator();
- Assertions.assertEquals(b, iterator.next());
- Assertions.assertEquals(c, iterator.next());
- Assertions.assertNull(iterator.next());
- Assertions.assertFalse(iterator.hasNext());
- try {
- Collection<C> castFail = CollectionUtil.checkedSubTypeCast(list, C.class);
- fail("Expected ClassCastException");
- } catch (ClassCastException expected) {
- }
+ assertThat(iterator.next()).isEqualTo(b);
+ assertThat(iterator.next()).isEqualTo(c);
+ assertThat(iterator.next()).isNull();
+ assertThat(iterator).isExhausted();
+ assertThatThrownBy(() -> CollectionUtil.checkedSubTypeCast(list, C.class))
+ .isInstanceOf(ClassCastException.class);
}
static class A {}
diff --git a/flink-core/src/test/java/org/apache/flink/util/CompressedSerializedValueTest.java b/flink-core/src/test/java/org/apache/flink/util/CompressedSerializedValueTest.java
index 83d8d4f6a63..db9e287bd9c 100644
--- a/flink-core/src/test/java/org/apache/flink/util/CompressedSerializedValueTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/CompressedSerializedValueTest.java
@@ -20,56 +20,57 @@ package org.apache.flink.util;
import org.apache.flink.core.testutils.CommonTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertArrayEquals;
-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;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link CompressedSerializedValue}. */
-public class CompressedSerializedValueTest {
+class CompressedSerializedValueTest {
@Test
- public void testSimpleValue() throws Exception {
+ void testSimpleValue() throws Exception {
final String value = "teststring";
CompressedSerializedValue<String> v = CompressedSerializedValue.fromObject(value);
CompressedSerializedValue<String> copy = CommonTestUtils.createCopySerializable(v);
- assertEquals(value, v.deserializeValue(getClass().getClassLoader()));
- assertEquals(value, copy.deserializeValue(getClass().getClassLoader()));
+ assertThat(v.deserializeValue(getClass().getClassLoader())).isEqualTo(value);
+ assertThat(copy.deserializeValue(getClass().getClassLoader())).isEqualTo(value);
- assertEquals(v, copy);
- assertEquals(v.hashCode(), copy.hashCode());
+ assertThat(copy).isEqualTo(v);
+ assertThat(copy).hasSameHashCodeAs(v.hashCode());
- assertNotNull(v.toString());
- assertNotNull(copy.toString());
+ assertThat(v.toString()).isNotNull();
+ assertThat(copy.toString()).isNotNull();
- assertNotEquals(0, v.getSize());
- assertArrayEquals(v.getByteArray(), copy.getByteArray());
+ assertThat(v.getSize()).isNotEqualTo(0);
+ assertThat(copy.getByteArray()).isEqualTo(v.getByteArray());
byte[] bytes = v.getByteArray();
CompressedSerializedValue<String> saved =
CompressedSerializedValue.fromBytes(Arrays.copyOf(bytes, bytes.length));
- assertEquals(v, saved);
- assertArrayEquals(v.getByteArray(), saved.getByteArray());
+ assertThat(saved).isEqualTo(v);
+ assertThat(saved.getByteArray()).isEqualTo(v.getByteArray());
}
- @Test(expected = NullPointerException.class)
- public void testNullValue() throws Exception {
- CompressedSerializedValue.fromObject(null);
+ @Test
+ void testNullValue() {
+ assertThatThrownBy(() -> CompressedSerializedValue.fromObject(null))
+ .isInstanceOf(NullPointerException.class);
}
- @Test(expected = NullPointerException.class)
- public void testFromNullBytes() {
- CompressedSerializedValue.fromBytes(null);
+ @Test
+ void testFromNullBytes() {
+ assertThatThrownBy(() -> CompressedSerializedValue.fromBytes(null))
+ .isInstanceOf(NullPointerException.class);
}
- @Test(expected = IllegalArgumentException.class)
- public void testFromEmptyBytes() {
- CompressedSerializedValue.fromBytes(new byte[0]);
+ @Test
+ void testFromEmptyBytes() {
+ assertThatThrownBy(() -> CompressedSerializedValue.fromBytes(new byte[0]))
+ .isInstanceOf(IllegalArgumentException.class);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/ExceptionUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/ExceptionUtilsTest.java
index 84ba06f874a..1bb0f066400 100644
--- a/flink-core/src/test/java/org/apache/flink/util/ExceptionUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/ExceptionUtilsTest.java
@@ -18,99 +18,88 @@
package org.apache.flink.util;
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.sameInstance;
-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.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for the utility methods in {@link ExceptionUtils}. */
-public class ExceptionUtilsTest extends TestLogger {
+class ExceptionUtilsTest {
@Test
- public void testStringifyNullException() {
- assertNotNull(ExceptionUtils.STRINGIFIED_NULL_EXCEPTION);
- assertEquals(
- ExceptionUtils.STRINGIFIED_NULL_EXCEPTION, ExceptionUtils.stringifyException(null));
+ void testStringifyNullException() {
+ assertThat(ExceptionUtils.STRINGIFIED_NULL_EXCEPTION)
+ .isEqualTo(ExceptionUtils.stringifyException(null));
}
@Test
- public void testJvmFatalError() {
+ void testJvmFatalError() {
// not all errors are fatal
- assertFalse(ExceptionUtils.isJvmFatalError(new Error()));
+ assertThat(ExceptionUtils.isJvmFatalError(new Error())).isFalse();
// linkage errors are not fatal
- assertFalse(ExceptionUtils.isJvmFatalError(new LinkageError()));
+ assertThat(ExceptionUtils.isJvmFatalError(new LinkageError())).isFalse();
// some errors are fatal
- assertTrue(ExceptionUtils.isJvmFatalError(new InternalError()));
- assertTrue(ExceptionUtils.isJvmFatalError(new UnknownError()));
+ assertThat(ExceptionUtils.isJvmFatalError(new InternalError())).isTrue();
+ assertThat(ExceptionUtils.isJvmFatalError(new UnknownError())).isTrue();
}
@Test
- public void testRethrowFatalError() {
+ void testRethrowFatalError() {
// fatal error is rethrown
- try {
- ExceptionUtils.rethrowIfFatalError(new InternalError());
- fail();
- } catch (InternalError ignored) {
- }
+ assertThatThrownBy(() -> ExceptionUtils.rethrowIfFatalError(new InternalError()))
+ .isInstanceOf(InternalError.class);
// non-fatal error is not rethrown
ExceptionUtils.rethrowIfFatalError(new NoClassDefFoundError());
}
@Test
- public void testFindThrowableByType() {
- assertTrue(
- ExceptionUtils.findThrowable(
+ void testFindThrowableByType() {
+ assertThat(
+ ExceptionUtils.findThrowable(
new RuntimeException(new IllegalStateException()),
- IllegalStateException.class)
- .isPresent());
+ IllegalStateException.class))
+ .isPresent();
}
@Test
- public void testExceptionStripping() {
+ void testExceptionStripping() {
final FlinkException expectedException = new FlinkException("test exception");
final Throwable strippedException =
ExceptionUtils.stripException(
new RuntimeException(new RuntimeException(expectedException)),
RuntimeException.class);
- assertThat(strippedException, is(equalTo(expectedException)));
+ assertThat(strippedException).isEqualTo(expectedException);
}
@Test
- public void testInvalidExceptionStripping() {
+ void testInvalidExceptionStripping() {
final FlinkException expectedException =
new FlinkException(new RuntimeException(new FlinkException("inner exception")));
final Throwable strippedException =
ExceptionUtils.stripException(expectedException, RuntimeException.class);
- assertThat(strippedException, is(equalTo(expectedException)));
+ assertThat(strippedException).isEqualTo(expectedException);
}
@Test
- public void testTryEnrichTaskExecutorErrorCanHandleNullValueWithoutCausingException() {
+ void testTryEnrichTaskExecutorErrorCanHandleNullValueWithoutCausingException() {
ExceptionUtils.tryEnrichOutOfMemoryError(null, "", "", "");
}
@Test
- public void testUpdateDetailMessageOfBasicThrowable() {
+ void testUpdateDetailMessageOfBasicThrowable() {
Throwable rootThrowable = new OutOfMemoryError("old message");
ExceptionUtils.updateDetailMessage(rootThrowable, t -> "new message");
- assertThat(rootThrowable.getMessage(), is("new message"));
+ assertThat(rootThrowable.getMessage()).isEqualTo("new message");
}
@Test
- public void testUpdateDetailMessageOfRelevantThrowableAsCause() {
+ void testUpdateDetailMessageOfRelevantThrowableAsCause() {
Throwable oomCause =
new IllegalArgumentException("another message deep down in the cause tree");
@@ -124,45 +113,45 @@ public class ExceptionUtilsTest extends TestLogger {
rootThrowable,
t -> t.getClass().equals(OutOfMemoryError.class) ? "new message" : null);
- assertThat(rootThrowable.getCause(), sameInstance(oom));
- assertThat(rootThrowable.getCause().getMessage(), is("new message"));
- assertThat(rootThrowable.getCause().getStackTrace(), is(oom.getStackTrace()));
- assertThat(rootThrowable.getCause().getSuppressed(), is(oom.getSuppressed()));
+ assertThat(rootThrowable.getCause()).isSameAs(oom);
+ assertThat(rootThrowable.getCause().getMessage()).isEqualTo("new message");
+ assertThat(rootThrowable.getCause().getStackTrace()).isEqualTo(oom.getStackTrace());
+ assertThat(rootThrowable.getCause().getSuppressed()).isEqualTo(oom.getSuppressed());
- assertThat(rootThrowable.getCause().getCause(), sameInstance(oomCause));
+ assertThat(rootThrowable.getCause().getCause()).isSameAs(oomCause);
}
@Test
- public void testUpdateDetailMessageWithoutRelevantThrowable() {
+ void testUpdateDetailMessageWithoutRelevantThrowable() {
Throwable originalThrowable =
new IllegalStateException(
"root message", new IllegalArgumentException("cause message"));
ExceptionUtils.updateDetailMessage(originalThrowable, t -> null);
- assertThat(originalThrowable.getMessage(), is("root message"));
- assertThat(originalThrowable.getCause().getMessage(), is("cause message"));
+ assertThat(originalThrowable.getMessage()).isEqualTo("root message");
+ assertThat(originalThrowable.getCause().getMessage()).isEqualTo("cause message");
}
@Test
- public void testUpdateDetailMessageOfNullWithoutException() {
+ void testUpdateDetailMessageOfNullWithoutException() {
ExceptionUtils.updateDetailMessage(null, t -> "new message");
}
@Test
- public void testUpdateDetailMessageWithMissingPredicate() {
+ void testUpdateDetailMessageWithMissingPredicate() {
Throwable root = new Exception("old message");
ExceptionUtils.updateDetailMessage(root, null);
- assertThat(root.getMessage(), is("old message"));
+ assertThat(root.getMessage()).isEqualTo("old message");
}
@Test
- public void testIsMetaspaceOutOfMemoryErrorCanHandleNullValue() {
- assertFalse(ExceptionUtils.isMetaspaceOutOfMemoryError(null));
+ void testIsMetaspaceOutOfMemoryErrorCanHandleNullValue() {
+ assertThat(ExceptionUtils.isMetaspaceOutOfMemoryError(null)).isFalse();
}
@Test
- public void testIsDirectOutOfMemoryErrorCanHandleNullValue() {
- assertFalse(ExceptionUtils.isDirectOutOfMemoryError(null));
+ void testIsDirectOutOfMemoryErrorCanHandleNullValue() {
+ assertThat(ExceptionUtils.isDirectOutOfMemoryError(null)).isFalse();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/FileUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/FileUtilsTest.java
index 1576305d0aa..982e2d57425 100644
--- a/flink-core/src/test/java/org/apache/flink/util/FileUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/FileUtilsTest.java
@@ -24,10 +24,8 @@ import org.apache.flink.core.fs.Path;
import org.apache.flink.core.testutils.CheckedThread;
import org.apache.flink.testutils.junit.utils.TempDirUtils;
-import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
@@ -59,7 +57,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assumptions.assumeThat;
/** Tests for the {@link FileUtils}. */
-@ExtendWith(TestLoggerExtension.class)
public class FileUtilsTest {
@TempDir private java.nio.file.Path temporaryFolder;
@@ -185,7 +182,7 @@ public class FileUtilsTest {
}
FileUtils.deleteDirectory(symbolicLink);
- assertThat(fileInLinkedDirectory.exists()).isTrue();
+ assertThat(fileInLinkedDirectory).exists();
}
@Test
@@ -252,14 +249,14 @@ public class FileUtilsTest {
final java.nio.file.Path rootPath = temporaryFolder.getRoot();
final java.nio.file.Path relativePath = FileUtils.relativizePath(rootPath, absolutePath);
- assertThat(relativePath.isAbsolute()).isFalse();
+ assertThat(relativePath).isRelative();
assertThat(absolutePath).isEqualTo(rootPath.resolve(relativePath));
}
@Test
void testRelativizeOfRelativePath() {
final java.nio.file.Path path = Paths.get("foobar");
- assertThat(path.isAbsolute()).isFalse();
+ assertThat(path).isRelative();
final java.nio.file.Path relativePath =
FileUtils.relativizePath(temporaryFolder.getRoot(), path);
@@ -278,7 +275,7 @@ public class FileUtilsTest {
@Test
void testRelativePathToURL() throws MalformedURLException {
final java.nio.file.Path relativePath = Paths.get("foobar");
- assertThat(relativePath.isAbsolute()).isFalse();
+ assertThat(relativePath).isRelative();
final URL relativeURL = FileUtils.toURL(relativePath);
final java.nio.file.Path transformedPath = Paths.get(relativeURL.getPath());
@@ -371,11 +368,11 @@ public class FileUtilsTest {
final File parent = TempDirUtils.newFolder(temporaryFolder);
// Empty directory should have size 0
- Assertions.assertEquals(0, FileUtils.getDirectoryFilesSize(parent.toPath()));
+ assertThat(FileUtils.getDirectoryFilesSize(parent.toPath())).isZero();
// Expected size: (20*5^0 + 20*5^1 + 20*5^2 + 20*5^3) * 1 byte = 3120 bytes
generateRandomDirs(parent, 20, 5, 3);
- Assertions.assertEquals(3120, FileUtils.getDirectoryFilesSize(parent.toPath()));
+ assertThat(FileUtils.getDirectoryFilesSize(parent.toPath())).isEqualTo(3120);
}
// ------------------------------------------------------------------------
@@ -546,24 +543,21 @@ public class FileUtilsTest {
}
@Test
- public void testExpandDirWithValidPaths() {
- Assertions.assertDoesNotThrow(() -> writeZipAndFetchExpandedPath("t0", "/level1/level2/"));
- Assertions.assertDoesNotThrow(
- () -> writeZipAndFetchExpandedPath("t1", "/level1/level2/file.txt"));
- Assertions.assertDoesNotThrow(
- () -> writeZipAndFetchExpandedPath("t2", "/level1/../level1/file.txt"));
- Assertions.assertDoesNotThrow(
- () -> writeZipAndFetchExpandedPath("t3", "/level1/level2/level3/../"));
- Assertions.assertThrows(
- IOException.class,
- () -> writeZipAndFetchExpandedPath("t2", "/level1/level2/../../pass"));
+ void testExpandDirWithValidPaths() throws IOException {
+ writeZipAndFetchExpandedPath("t0", "/level1/level2/");
+ writeZipAndFetchExpandedPath("t1", "/level1/level2/file.txt");
+ writeZipAndFetchExpandedPath("t2", "/level1/../level1/file.txt");
+ writeZipAndFetchExpandedPath("t3", "/level1/level2/level3/../");
+ assertThatThrownBy(() -> writeZipAndFetchExpandedPath("t2", "/level1/level2/../../pass"))
+ .isInstanceOf(IOException.class);
}
@Test
- public void testExpandDirWithForbiddenEscape() {
- Assertions.assertThrows(
- IOException.class, () -> writeZipAndFetchExpandedPath("t1", "/../../"));
- Assertions.assertThrows(IOException.class, () -> writeZipAndFetchExpandedPath("t2", "../"));
+ void testExpandDirWithForbiddenEscape() {
+ assertThatThrownBy(() -> writeZipAndFetchExpandedPath("t1", "/../../"))
+ .isInstanceOf(IOException.class);
+ assertThatThrownBy(() -> writeZipAndFetchExpandedPath("t2", "../"))
+ .isInstanceOf(IOException.class);
}
/**
diff --git a/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoaderTest.java b/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoaderTest.java
index 6c89f6d9703..9ca3f0cc188 100644
--- a/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoaderTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoaderTest.java
@@ -18,30 +18,33 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URL;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for the {@link FlinkUserCodeClassLoader}. */
-public class FlinkUserCodeClassLoaderTest extends TestLogger {
+class FlinkUserCodeClassLoaderTest {
@Test
- public void testExceptionHandling() {
+ void testExceptionHandling() {
RuntimeException expectedException = new RuntimeException("Expected exception");
AtomicReference<Throwable> handledException = new AtomicReference<>();
- try (FlinkUserCodeClassLoader classLoaderWithErrorHandler =
- new ThrowingURLClassLoader(handledException::set, expectedException)) {
- classLoaderWithErrorHandler.loadClass("dummy.class");
- fail("The expected exception is not thrown");
- } catch (Throwable t) {
- assertThat(handledException.get(), is(expectedException));
- assertThat(t, is(expectedException));
- }
+
+ assertThatThrownBy(
+ () -> {
+ try (FlinkUserCodeClassLoader classLoaderWithErrorHandler =
+ new ThrowingURLClassLoader(
+ handledException::set, expectedException)) {
+ classLoaderWithErrorHandler.loadClass("dummy.class");
+ }
+ })
+ .isSameAs(expectedException);
+
+ assertThat(handledException.get()).isSameAs(expectedException);
}
private static class ThrowingURLClassLoader extends FlinkUserCodeClassLoader {
diff --git a/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoadersTest.java b/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoadersTest.java
index d3f938e458f..0c8b99504df 100644
--- a/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoadersTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/FlinkUserCodeClassLoadersTest.java
@@ -18,33 +18,24 @@
package org.apache.flink.util;
-import org.junit.BeforeClass;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
+import org.apache.flink.testutils.junit.utils.TempDirUtils;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import static org.apache.flink.util.FlinkUserCodeClassLoader.NOOP_EXCEPTION_HANDLER;
-import static org.assertj.core.api.Assertions.fail;
-import static org.hamcrest.CoreMatchers.isA;
-import static org.hamcrest.Matchers.startsWith;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for classloading and class loader utilities. */
-public class FlinkUserCodeClassLoadersTest extends TestLogger {
-
- @ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
+class FlinkUserCodeClassLoadersTest {
- @Rule public ExpectedException expectedException = ExpectedException.none();
+ @TempDir private static java.nio.file.Path tempFolder;
public static final String USER_CLASS = "UserClass";
public static final String USER_CLASS_CODE =
@@ -55,18 +46,18 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
private static File userJar;
- @BeforeClass
- public static void prepare() throws Exception {
+ @BeforeAll
+ static void prepare() throws Exception {
userJar =
UserClassLoaderJarTestUtils.createJarFile(
- temporaryFolder.newFolder("test-jar"),
+ TempDirUtils.newFolder(tempFolder, "test-jar"),
"test-classloader.jar",
USER_CLASS,
USER_CLASS_CODE);
}
@Test
- public void testParentFirstClassLoading() throws Exception {
+ void testParentFirstClassLoading() throws Exception {
final ClassLoader parentClassLoader = getClass().getClassLoader();
// collect the libraries / class folders with RocksDB related code: the state backend and
@@ -85,15 +76,15 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
final Class<?> clazz2 = Class.forName(className, false, childClassLoader1);
final Class<?> clazz3 = Class.forName(className, false, childClassLoader2);
- assertEquals(clazz1, clazz2);
- assertEquals(clazz1, clazz3);
+ assertThat(clazz2).isEqualTo(clazz1);
+ assertThat(clazz3).isEqualTo(clazz1);
childClassLoader1.close();
childClassLoader2.close();
}
@Test
- public void testChildFirstClassLoading() throws Exception {
+ void testChildFirstClassLoading() throws Exception {
final ClassLoader parentClassLoader = getClass().getClassLoader();
// collect the libraries / class folders with RocksDB related code: the state backend and
@@ -112,16 +103,16 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
final Class<?> clazz2 = Class.forName(className, false, childClassLoader1);
final Class<?> clazz3 = Class.forName(className, false, childClassLoader2);
- assertNotEquals(clazz1, clazz2);
- assertNotEquals(clazz1, clazz3);
- assertNotEquals(clazz2, clazz3);
+ assertThat(clazz2).isNotEqualTo(clazz1);
+ assertThat(clazz3).isNotEqualTo(clazz1);
+ assertThat(clazz3).isNotEqualTo(clazz2);
childClassLoader1.close();
childClassLoader2.close();
}
@Test
- public void testRepeatedChildFirstClassLoading() throws Exception {
+ void testRepeatedChildFirstClassLoading() throws Exception {
final ClassLoader parentClassLoader = getClass().getClassLoader();
// collect the libraries / class folders with RocksDB related code: the state backend and
@@ -138,16 +129,16 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
final Class<?> clazz3 = Class.forName(className, false, childClassLoader);
final Class<?> clazz4 = Class.forName(className, false, childClassLoader);
- assertNotEquals(clazz1, clazz2);
+ assertThat(clazz2).isNotEqualTo(clazz1);
- assertEquals(clazz2, clazz3);
- assertEquals(clazz2, clazz4);
+ assertThat(clazz3).isEqualTo(clazz2);
+ assertThat(clazz4).isEqualTo(clazz2);
childClassLoader.close();
}
@Test
- public void testRepeatedParentFirstPatternClass() throws Exception {
+ void testRepeatedParentFirstPatternClass() throws Exception {
final String className = FlinkUserCodeClassLoadersTest.class.getName();
final String parentFirstPattern = className.substring(0, className.lastIndexOf('.'));
@@ -170,15 +161,15 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
final Class<?> clazz3 = Class.forName(className, false, childClassLoader);
final Class<?> clazz4 = Class.forName(className, false, childClassLoader);
- assertEquals(clazz1, clazz2);
- assertEquals(clazz1, clazz3);
- assertEquals(clazz1, clazz4);
+ assertThat(clazz2).isEqualTo(clazz1);
+ assertThat(clazz3).isEqualTo(clazz1);
+ assertThat(clazz4).isEqualTo(clazz1);
childClassLoader.close();
}
@Test
- public void testGetClassLoaderInfo() throws Exception {
+ void testGetClassLoaderInfo() throws Exception {
final ClassLoader parentClassLoader = getClass().getClassLoader();
final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();
@@ -188,15 +179,14 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
String formattedURL = ClassLoaderUtil.formatURL(childCodePath);
- assertEquals(
- ClassLoaderUtil.getUserCodeClassLoaderInfo(childClassLoader),
- "URL ClassLoader:" + formattedURL);
+ assertThat("URL ClassLoader:" + formattedURL)
+ .isEqualTo(ClassLoaderUtil.getUserCodeClassLoaderInfo(childClassLoader));
childClassLoader.close();
}
@Test
- public void testGetClassLoaderInfoWithClassLoaderClosed() throws Exception {
+ void testGetClassLoaderInfoWithClassLoaderClosed() throws Exception {
final ClassLoader parentClassLoader = getClass().getClassLoader();
final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();
@@ -206,9 +196,8 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
childClassLoader.close();
- assertThat(
- ClassLoaderUtil.getUserCodeClassLoaderInfo(childClassLoader),
- startsWith("Cannot access classloader info due to an exception."));
+ assertThat(ClassLoaderUtil.getUserCodeClassLoaderInfo(childClassLoader))
+ .startsWith("Cannot access classloader info due to an exception.");
}
private static MutableURLClassLoader createParentFirstClassLoader(
@@ -228,7 +217,7 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
}
@Test
- public void testClosingOfClassloader() throws Exception {
+ void testClosingOfClassloader() throws Exception {
final String className = ClassToLoad.class.getName();
final ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader().getParent();
@@ -240,24 +229,24 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
final Class<?> loadedClass = childClassLoader.loadClass(className);
- assertNotSame(ClassToLoad.class, loadedClass);
+ assertThat(loadedClass).isNotSameAs(ClassToLoad.class);
childClassLoader.close();
// after closing, no loaded class should be reachable anymore
- expectedException.expect(isA(IllegalStateException.class));
- childClassLoader.loadClass(className);
+ assertThatThrownBy(() -> childClassLoader.loadClass(className))
+ .isInstanceOf(IllegalStateException.class);
}
@Test
- public void testParallelCapable() {
+ void testParallelCapable() {
// It will be true only if all the super classes (except class Object) of the caller are
// registered as parallel capable.
- assertTrue(TestParentFirstClassLoader.isParallelCapable);
+ assertThat(TestParentFirstClassLoader.isParallelCapable).isTrue();
}
@Test
- public void testParentFirstClassLoadingByAddURL() throws Exception {
+ void testParentFirstClassLoadingByAddURL() throws Exception {
// collect the libraries / class folders with RocksDB related code: the state backend and
// RocksDB itself
final URL childCodePath = getClass().getProtectionDomain().getCodeSource().getLocation();
@@ -282,8 +271,8 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
final Class<?> clazz2 = Class.forName(USER_CLASS, false, childClassLoader1);
final Class<?> clazz3 = Class.forName(USER_CLASS, false, childClassLoader2);
- assertEquals(clazz1, clazz2);
- assertEquals(clazz1, clazz3);
+ assertThat(clazz2).isEqualTo(clazz1);
+ assertThat(clazz3).isEqualTo(clazz1);
parentClassLoader.close();
childClassLoader1.close();
@@ -291,7 +280,7 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
}
@Test
- public void testChildFirstClassLoadingByAddURL() throws Exception {
+ void testChildFirstClassLoadingByAddURL() throws Exception {
// collect the libraries / class folders with RocksDB related code: the state backend and
// RocksDB itself
@@ -320,7 +309,7 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
final Class<?> clazz1 = Class.forName(USER_CLASS, false, childClassLoader1);
final Class<?> clazz2 = Class.forName(USER_CLASS, false, childClassLoader2);
- assertNotEquals(clazz1, clazz2);
+ assertThat(clazz2).isNotEqualTo(clazz1);
parentClassLoader.close();
childClassLoader1.close();
@@ -329,11 +318,8 @@ public class FlinkUserCodeClassLoadersTest extends TestLogger {
private void assertClassNotFoundException(
String className, boolean initialize, ClassLoader classLoader) {
- try {
- Class.forName(className, initialize, classLoader);
- fail("Should fail.");
- } catch (ClassNotFoundException e) {
- }
+ assertThatThrownBy(() -> Class.forName(className, initialize, classLoader))
+ .isInstanceOf(ClassNotFoundException.class);
}
private static class TestParentFirstClassLoader
diff --git a/flink-core/src/test/java/org/apache/flink/util/IOUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/IOUtilsTest.java
index dc00e9f56dd..729b3cdc212 100644
--- a/flink-core/src/test/java/org/apache/flink/util/IOUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/IOUtilsTest.java
@@ -18,38 +18,39 @@
package org.apache.flink.util;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
/** Tests for the {@link IOUtils}. */
-public class IOUtilsTest extends TestLogger {
+class IOUtilsTest {
@Test
- public void testTryReadFullyFromLongerStream() throws IOException {
+ void testTryReadFullyFromLongerStream() throws IOException {
ByteArrayInputStream inputStream =
new ByteArrayInputStream("test-data".getBytes(StandardCharsets.UTF_8));
byte[] out = new byte[4];
int read = IOUtils.tryReadFully(inputStream, out);
- Assert.assertArrayEquals(
- "test".getBytes(StandardCharsets.UTF_8), Arrays.copyOfRange(out, 0, read));
+ assertThat(Arrays.copyOfRange(out, 0, read))
+ .containsExactly("test".getBytes(StandardCharsets.UTF_8));
}
@Test
- public void testTryReadFullyFromShorterStream() throws IOException {
+ void testTryReadFullyFromShorterStream() throws IOException {
ByteArrayInputStream inputStream =
new ByteArrayInputStream("t".getBytes(StandardCharsets.UTF_8));
byte[] out = new byte[4];
int read = IOUtils.tryReadFully(inputStream, out);
- Assert.assertArrayEquals(
- "t".getBytes(StandardCharsets.UTF_8), Arrays.copyOfRange(out, 0, read));
+ assertThat(Arrays.copyOfRange(out, 0, read))
+ .containsExactly("t".getBytes(StandardCharsets.UTF_8));
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/InstantiationUtilTest.java b/flink-core/src/test/java/org/apache/flink/util/InstantiationUtilTest.java
index 1d4150d9269..3fb73bad6ff 100644
--- a/flink-core/src/test/java/org/apache/flink/util/InstantiationUtilTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/InstantiationUtilTest.java
@@ -24,13 +24,13 @@ import org.apache.flink.core.io.IOReadableWritable;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.testutils.ClassLoaderUtils;
+import org.apache.flink.testutils.junit.utils.TempDirUtils;
import org.apache.flink.types.DoubleValue;
import org.apache.flink.types.StringValue;
import org.apache.flink.types.Value;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.ObjectInputStream;
@@ -41,16 +41,13 @@ import java.net.URLClassLoader;
import java.util.Objects;
import java.util.Random;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for the {@link InstantiationUtil}. */
-public class InstantiationUtilTest extends TestLogger {
+class InstantiationUtilTest {
- @ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir private static java.nio.file.Path tempFolder;
private static final String PROXY_DEFINITION_FORMAT =
"import java.lang.reflect.InvocationHandler;"
@@ -65,7 +62,7 @@ public class InstantiationUtilTest extends TestLogger {
+ "}";
@Test
- public void testResolveProxyClass() throws Exception {
+ void testResolveProxyClass() throws Exception {
final String interfaceName = "UserDefinedInterface";
final String proxyName = "UserProxy";
@@ -81,13 +78,13 @@ public class InstantiationUtilTest extends TestLogger {
byte[] serializeObject = InstantiationUtil.serializeObject(proxy);
Object deserializedProxy =
InstantiationUtil.deserializeObject(serializeObject, userClassLoader);
- assertNotNull(deserializedProxy);
+ assertThat(deserializedProxy).isNotNull();
}
}
private URLClassLoader createClassLoader(String interfaceName, String proxyName)
throws IOException {
- return ClassLoaderUtils.withRoot(temporaryFolder.newFolder())
+ return ClassLoaderUtils.withRoot(TempDirUtils.newFolder(tempFolder))
.addClass(
interfaceName, String.format("interface %s { void test();}", interfaceName))
.addClass(proxyName, createProxyDefinition(proxyName))
@@ -99,20 +96,20 @@ public class InstantiationUtilTest extends TestLogger {
}
@Test
- public void testInstantiationOfStringValue() {
- StringValue stringValue = InstantiationUtil.instantiate(StringValue.class, null);
- assertNotNull(stringValue);
+ void testInstantiationOfStringValue() {
+ Object stringValue = InstantiationUtil.instantiate(StringValue.class, null);
+ assertThat(stringValue).isNotNull();
}
@Test
- public void testInstantiationOfStringValueAndCastToValue() {
- StringValue stringValue = InstantiationUtil.instantiate(StringValue.class, Value.class);
- assertNotNull(stringValue);
+ void testInstantiationOfStringValueAndCastToValue() {
+ Object stringValue = InstantiationUtil.instantiate(StringValue.class, Value.class);
+ assertThat(stringValue).isNotNull();
}
@Test
- public void testHasNullaryConstructor() {
- assertTrue(InstantiationUtil.hasPublicNullaryConstructor(StringValue.class));
+ void testHasNullaryConstructor() {
+ assertThat(InstantiationUtil.hasPublicNullaryConstructor(StringValue.class)).isTrue();
}
/**
@@ -124,22 +121,23 @@ public class InstantiationUtilTest extends TestLogger {
}
@Test
- public void testClassIsProper() {
- assertTrue(InstantiationUtil.isProperClass(StringValue.class));
+ void testClassIsProper() {
+ assertThat(InstantiationUtil.isProperClass(StringValue.class)).isTrue();
}
@Test
- public void testClassIsNotProper() {
- assertFalse(InstantiationUtil.isProperClass(Value.class));
+ void testClassIsNotProper() {
+ assertThat(InstantiationUtil.isProperClass(Value.class)).isFalse();
}
- @Test(expected = RuntimeException.class)
- public void testCheckForInstantiationOfPrivateClass() {
- InstantiationUtil.checkForInstantiation(TestClass.class);
+ @Test
+ void testCheckForInstantiationOfPrivateClass() {
+ assertThatThrownBy(() -> InstantiationUtil.checkForInstantiation(TestClass.class))
+ .isInstanceOf(RuntimeException.class);
}
@Test
- public void testSerializationToByteArray() throws IOException {
+ void testSerializationToByteArray() throws IOException {
final DoubleValue toSerialize = new DoubleValue(Math.random());
final DoubleValueSerializer serializer = new DoubleValueSerializer();
@@ -148,72 +146,57 @@ public class InstantiationUtilTest extends TestLogger {
DoubleValue deserialized =
InstantiationUtil.deserializeFromByteArray(serializer, serialized);
- assertEquals(
- "Serialized record is not equal after serialization.", toSerialize, deserialized);
+ assertThat(deserialized).isEqualTo(toSerialize);
}
@Test
- public void testCompressionAndSerializationAlongWithDecompressionAndDeserialization()
+ void testCompressionAndSerializationAlongWithDecompressionAndDeserialization()
throws IOException, ClassNotFoundException {
final String value = "teststring";
- assertEquals(
- value,
- InstantiationUtil.decompressAndDeserializeObject(
- InstantiationUtil.serializeObjectAndCompress(value),
- getClass().getClassLoader()));
+ assertThat(
+ (String)
+ InstantiationUtil.decompressAndDeserializeObject(
+ InstantiationUtil.serializeObjectAndCompress(value),
+ getClass().getClassLoader()))
+ .isEqualTo(value);
}
@Test
- public void testWriteToConfigFailingSerialization() {
- try {
- final String key1 = "testkey1";
- final String key2 = "testkey2";
- final Configuration config = new Configuration();
-
- try {
- InstantiationUtil.writeObjectToConfig(
- new TestClassWriteFails(), config, "irgnored");
- fail("should throw an exception");
- } catch (TestException e) {
- // expected
- } catch (Exception e) {
- fail("Wrong exception type - exception not properly forwarded");
- }
-
- InstantiationUtil.writeObjectToConfig(new TestClassReadFails(), config, key1);
- InstantiationUtil.writeObjectToConfig(new TestClassReadFailsCNF(), config, key2);
-
- try {
- InstantiationUtil.readObjectFromConfig(config, key1, getClass().getClassLoader());
- fail("should throw an exception");
- } catch (TestException e) {
- // expected
- } catch (Exception e) {
- fail("Wrong exception type - exception not properly forwarded");
- }
-
- try {
- InstantiationUtil.readObjectFromConfig(config, key2, getClass().getClassLoader());
- fail("should throw an exception");
- } catch (ClassNotFoundException e) {
- // expected
- } catch (Exception e) {
- fail("Wrong exception type - exception not properly forwarded");
- }
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testWriteToConfigFailingSerialization() throws IOException {
+ final String key1 = "testkey1";
+ final String key2 = "testkey2";
+ final Configuration config = new Configuration();
+
+ assertThatThrownBy(
+ () ->
+ InstantiationUtil.writeObjectToConfig(
+ new TestClassWriteFails(), config, "irgnored"))
+ .isInstanceOf(TestException.class);
+
+ InstantiationUtil.writeObjectToConfig(new TestClassReadFails(), config, key1);
+ InstantiationUtil.writeObjectToConfig(new TestClassReadFailsCNF(), config, key2);
+
+ assertThatThrownBy(
+ () ->
+ InstantiationUtil.readObjectFromConfig(
+ config, key1, getClass().getClassLoader()))
+ .isInstanceOf(TestException.class);
+
+ assertThatThrownBy(
+ () ->
+ InstantiationUtil.readObjectFromConfig(
+ config, key2, getClass().getClassLoader()))
+ .isInstanceOf(ClassNotFoundException.class);
}
@Test
- public void testCopyWritable() throws Exception {
+ void testCopyWritable() throws Exception {
WritableType original = new WritableType();
WritableType copy = InstantiationUtil.createCopyWritable(original);
- assertTrue(original != copy);
- assertTrue(original.equals(copy));
+ assertThat(copy).isNotSameAs(original);
+ assertThat(copy).isEqualTo(original);
}
// --------------------------------------------------------------------------------------------
diff --git a/flink-core/src/test/java/org/apache/flink/util/IterableUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/IterableUtilsTest.java
index 3b0f7423dcd..6470641afba 100644
--- a/flink-core/src/test/java/org/apache/flink/util/IterableUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/IterableUtilsTest.java
@@ -18,26 +18,26 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.stream.Stream;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link IterableUtils}. */
-public class IterableUtilsTest extends TestLogger {
+class IterableUtilsTest {
private final Iterable<Integer> testIterable = Arrays.asList(1, 8, 5, 3, 8);
@Test
- public void testToStream() {
+ void testToStream() {
Queue<Integer> deque = new ArrayDeque<>();
testIterable.forEach(deque::add);
Stream<Integer> stream = IterableUtils.toStream(testIterable);
- assertTrue(stream.allMatch(value -> deque.poll().equals(value)));
+ assertThat(stream.allMatch(value -> deque.poll().equals(value))).isTrue();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/LambdaUtilTest.java b/flink-core/src/test/java/org/apache/flink/util/LambdaUtilTest.java
index a06082c64c7..211529b37a1 100644
--- a/flink-core/src/test/java/org/apache/flink/util/LambdaUtilTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/LambdaUtilTest.java
@@ -18,18 +18,18 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URL;
import java.net.URLClassLoader;
-import static org.junit.Assert.assertSame;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link LambdaUtil}. */
-public class LambdaUtilTest {
+class LambdaUtilTest {
@Test
- public void testRunWithContextClassLoaderRunnable() throws Exception {
+ void testRunWithContextClassLoaderRunnable() {
final ClassLoader aPrioriContextClassLoader =
Thread.currentThread().getContextClassLoader();
@@ -41,17 +41,18 @@ public class LambdaUtilTest {
Thread.currentThread().setContextClassLoader(original);
LambdaUtil.withContextClassLoader(
- temp, () -> assertSame(temp, Thread.currentThread().getContextClassLoader()));
+ temp, () -> assertThat(Thread.currentThread().getContextClassLoader()))
+ .isSameAs(temp);
// make sure the method restored the original context class loader
- assertSame(original, Thread.currentThread().getContextClassLoader());
+ assertThat(Thread.currentThread().getContextClassLoader()).isSameAs(original);
} finally {
Thread.currentThread().setContextClassLoader(aPrioriContextClassLoader);
}
}
@Test
- public void testRunWithContextClassLoaderSupplier() throws Exception {
+ void testRunWithContextClassLoaderSupplier() {
final ClassLoader aPrioriContextClassLoader =
Thread.currentThread().getContextClassLoader();
@@ -65,12 +66,12 @@ public class LambdaUtilTest {
LambdaUtil.withContextClassLoader(
temp,
() -> {
- assertSame(temp, Thread.currentThread().getContextClassLoader());
+ assertThat(Thread.currentThread().getContextClassLoader()).isSameAs(temp);
return true;
});
// make sure the method restored the original context class loader
- assertSame(original, Thread.currentThread().getContextClassLoader());
+ assertThat(Thread.currentThread().getContextClassLoader()).isSameAs(original);
} finally {
Thread.currentThread().setContextClassLoader(aPrioriContextClassLoader);
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/LinkedOptionalMapTest.java b/flink-core/src/test/java/org/apache/flink/util/LinkedOptionalMapTest.java
index ebea55b77b2..fc535509844 100644
--- a/flink-core/src/test/java/org/apache/flink/util/LinkedOptionalMapTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/LinkedOptionalMapTest.java
@@ -20,66 +20,60 @@ package org.apache.flink.util;
import org.apache.flink.util.LinkedOptionalMap.MergeResult;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.empty;
-import static org.hamcrest.Matchers.hasItem;
-import static org.hamcrest.Matchers.hasItems;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Test {@link LinkedOptionalMap}. */
-public class LinkedOptionalMapTest {
+class LinkedOptionalMapTest {
@Test
- public void usageExample() {
+ void usageExample() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("java.lang.String", String.class, "a string class");
map.put("scala.Option", null, "a scala Option");
map.put("java.lang.Boolean", Boolean.class, null);
- assertThat(map.keyNames(), hasItems("java.lang.String", "scala.Option"));
- assertThat(map.absentKeysOrValues(), hasItems("scala.Option", "java.lang.Boolean"));
+ assertThat(map.keyNames()).contains("java.lang.String", "scala.Option");
+ assertThat(map.absentKeysOrValues()).contains("scala.Option", "java.lang.Boolean");
}
@Test
- public void overridingKeyWithTheSameKeyName() {
+ void overridingKeyWithTheSameKeyName() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("java.lang.String", null, "a string class");
map.put("java.lang.String", String.class, "a string class");
- assertThat(map.absentKeysOrValues(), is(empty()));
+ assertThat(map.absentKeysOrValues()).isEmpty();
}
@Test
- public void overridingKeysAndValuesWithTheSameKeyName() {
+ void overridingKeysAndValuesWithTheSameKeyName() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("java.lang.String", null, null);
map.put("java.lang.String", String.class, "a string class");
- assertThat(map.absentKeysOrValues(), is(empty()));
+ assertThat(map.absentKeysOrValues()).isEmpty();
}
@Test
- public void overridingAValueWithMissingKeyShouldBeConsideredAsAbsent() {
+ void overridingAValueWithMissingKeyShouldBeConsideredAsAbsent() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("java.lang.String", null, null);
map.put("java.lang.String", null, "a string class");
- assertThat(map.absentKeysOrValues(), hasItem("java.lang.String"));
+ assertThat(map.absentKeysOrValues()).contains("java.lang.String");
}
@Test
- public void mergingMapsWithPresentEntriesLeavesNoAbsentKeyNames() {
+ void mergingMapsWithPresentEntriesLeavesNoAbsentKeyNames() {
LinkedOptionalMap<Class<?>, String> first = new LinkedOptionalMap<>();
first.put("b", null, null);
first.put("c", String.class, null);
@@ -92,11 +86,11 @@ public class LinkedOptionalMapTest {
first.putAll(second);
- assertThat(first.absentKeysOrValues(), is(empty()));
+ assertThat(first.absentKeysOrValues()).isEmpty();
}
@Test
- public void mergingMapsPreserversTheOrderOfTheOriginalMap() {
+ void mergingMapsPreserversTheOrderOfTheOriginalMap() {
LinkedOptionalMap<Class<?>, String> first = new LinkedOptionalMap<>();
first.put("b", null, null);
first.put("c", String.class, null);
@@ -109,11 +103,11 @@ public class LinkedOptionalMapTest {
first.putAll(second);
- assertThat(first.keyNames(), contains("b", "c", "a", "d"));
+ assertThat(first.keyNames()).contains("b", "c", "a", "d");
}
@Test
- public void mergingToEmpty() {
+ void mergingToEmpty() {
LinkedOptionalMap<Class<?>, String> first = new LinkedOptionalMap<>();
LinkedOptionalMap<Class<?>, String> second = new LinkedOptionalMap<>();
@@ -124,29 +118,37 @@ public class LinkedOptionalMapTest {
first.putAll(second);
- assertThat(first.keyNames(), contains("a", "b", "c", "d"));
+ assertThat(first.keyNames()).contains("a", "b", "c", "d");
}
- @Test(expected = IllegalStateException.class)
- public void unwrapOptionalsWithMissingValueThrows() {
- LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
+ @Test
+ void unwrapOptionalsWithMissingValueThrows() {
+ assertThatThrownBy(
+ () -> {
+ LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
- map.put("a", String.class, null);
+ map.put("a", String.class, null);
- map.unwrapOptionals();
+ map.unwrapOptionals();
+ })
+ .isInstanceOf(IllegalStateException.class);
}
- @Test(expected = IllegalStateException.class)
- public void unwrapOptionalsWithMissingKeyThrows() {
- LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
+ @Test
+ void unwrapOptionalsWithMissingKeyThrows() {
+ assertThatThrownBy(
+ () -> {
+ LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
- map.put("a", null, "blabla");
+ map.put("a", null, "blabla");
- map.unwrapOptionals();
+ map.unwrapOptionals();
+ })
+ .isInstanceOf(IllegalStateException.class);
}
@Test
- public void unwrapOptionalsPreservesOrder() {
+ void unwrapOptionalsPreservesOrder() {
LinkedOptionalMap<Class<?>, String> map = new LinkedOptionalMap<>();
map.put("a", String.class, "aaa");
@@ -154,12 +156,12 @@ public class LinkedOptionalMapTest {
LinkedHashMap<Class<?>, String> m = map.unwrapOptionals();
- assertThat(m.keySet(), contains(String.class, Boolean.class));
- assertThat(m.values(), contains("aaa", "bbb"));
+ assertThat(m).containsKeys(String.class, Boolean.class);
+ assertThat(m).containsValues("aaa", "bbb");
}
@Test
- public void testPrefix() {
+ void testPrefix() {
LinkedOptionalMap<Class<?>, String> left = new LinkedOptionalMap<>();
left.put("a", String.class, "aaa");
@@ -169,11 +171,11 @@ public class LinkedOptionalMapTest {
right.put("c", Boolean.class, "bbb");
- assertTrue(LinkedOptionalMap.isLeftPrefixOfRight(left, right));
+ assertThat(LinkedOptionalMap.isLeftPrefixOfRight(left, right)).isTrue();
}
@Test
- public void testNonPrefix() {
+ void testNonPrefix() {
LinkedOptionalMap<Class<?>, String> left = new LinkedOptionalMap<>();
left.put("a", String.class, "aaa");
@@ -184,12 +186,11 @@ public class LinkedOptionalMapTest {
right.put("b", Boolean.class, "bbb");
right.put("c", Boolean.class, "bbb");
- assertFalse(LinkedOptionalMap.isLeftPrefixOfRight(left, right));
+ assertThat(LinkedOptionalMap.isLeftPrefixOfRight(left, right)).isFalse();
}
@Test
- @SuppressWarnings("unchecked")
- public void demoMergeResult() {
+ void demoMergeResult() {
LinkedOptionalMap<Class<?>, String> left = new LinkedOptionalMap<>();
left.put("b", null, null);
left.put("c", String.class, null);
@@ -202,11 +203,12 @@ public class LinkedOptionalMapTest {
MergeResult<Class<?>, String> result = LinkedOptionalMap.mergeRightIntoLeft(left, right);
- assertThat(result.hasMissingKeys(), is(false));
- assertThat(result.isOrderedSubset(), is(true));
- assertThat(result.missingKeys(), is(empty()));
+ assertThat(result.hasMissingKeys()).isFalse();
+ assertThat(result.isOrderedSubset()).isTrue();
+ assertThat(result.missingKeys()).isEmpty();
LinkedHashMap<Class<?>, String> merged = result.getMerged();
- assertThat(merged.keySet(), contains(String.class, Void.class, Boolean.class, Long.class));
+ assertThat(merged.keySet())
+ .containsExactly(String.class, Void.class, Boolean.class, Long.class);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/LongValueSequenceIteratorTest.java b/flink-core/src/test/java/org/apache/flink/util/LongValueSequenceIteratorTest.java
index 2cf82c991ad..65210c6988e 100644
--- a/flink-core/src/test/java/org/apache/flink/util/LongValueSequenceIteratorTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/LongValueSequenceIteratorTest.java
@@ -18,16 +18,15 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link LongValueSequenceIterator}. */
-public class LongValueSequenceIteratorTest extends TestLogger {
+class LongValueSequenceIteratorTest {
@Test
- public void testSplitRegular() {
+ void testSplitRegular() {
testSplitting(new org.apache.flink.util.LongValueSequenceIterator(0, 10), 2);
testSplitting(new org.apache.flink.util.LongValueSequenceIterator(100, 100000), 7);
testSplitting(new org.apache.flink.util.LongValueSequenceIterator(-100, 0), 5);
@@ -35,7 +34,7 @@ public class LongValueSequenceIteratorTest extends TestLogger {
}
@Test
- public void testSplittingLargeRangesBy2() {
+ void testSplittingLargeRangesBy2() {
testSplitting(new org.apache.flink.util.LongValueSequenceIterator(0, Long.MAX_VALUE), 2);
testSplitting(
new org.apache.flink.util.LongValueSequenceIterator(-1000000000L, Long.MAX_VALUE),
@@ -46,7 +45,7 @@ public class LongValueSequenceIteratorTest extends TestLogger {
}
@Test
- public void testSplittingTooSmallRanges() {
+ void testSplittingTooSmallRanges() {
testSplitting(new org.apache.flink.util.LongValueSequenceIterator(0, 0), 2);
testSplitting(new org.apache.flink.util.LongValueSequenceIterator(-5, -5), 2);
testSplitting(new org.apache.flink.util.LongValueSequenceIterator(-5, -4), 3);
@@ -57,15 +56,15 @@ public class LongValueSequenceIteratorTest extends TestLogger {
org.apache.flink.util.LongValueSequenceIterator iter, int numSplits) {
org.apache.flink.util.LongValueSequenceIterator[] splits = iter.split(numSplits);
- assertEquals(numSplits, splits.length);
+ assertThat(splits).hasSize(numSplits);
// test start and end of range
- assertEquals(iter.getCurrent(), splits[0].getCurrent());
- assertEquals(iter.getTo(), splits[numSplits - 1].getTo());
+ assertThat(splits[0].getCurrent()).isEqualTo(iter.getCurrent());
+ assertThat(splits[numSplits - 1].getTo()).isEqualTo(iter.getTo());
// test continuous range
for (int i = 1; i < splits.length; i++) {
- assertEquals(splits[i - 1].getTo() + 1, splits[i].getCurrent());
+ assertThat(splits[i].getCurrent()).isEqualTo(splits[i - 1].getTo() + 1);
}
testMaxSplitDiff(splits);
@@ -90,6 +89,6 @@ public class LongValueSequenceIteratorTest extends TestLogger {
maxSplitSize = Math.max(maxSplitSize, diff);
}
- assertTrue(maxSplitSize == minSplitSize || maxSplitSize - 1 == minSplitSize);
+ assertThat(maxSplitSize == minSplitSize || maxSplitSize - 1 == minSplitSize).isTrue();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/MathUtilTest.java b/flink-core/src/test/java/org/apache/flink/util/MathUtilTest.java
index 305ff34cca5..437545203ab 100644
--- a/flink-core/src/test/java/org/apache/flink/util/MathUtilTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/MathUtilTest.java
@@ -18,155 +18,149 @@
package org.apache.flink.util;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for the {@link MathUtils}. */
-public class MathUtilTest {
+class MathUtilTest {
@Test
- public void testLog2Computation() {
- assertEquals(0, MathUtils.log2floor(1));
- assertEquals(1, MathUtils.log2floor(2));
- assertEquals(1, MathUtils.log2floor(3));
- assertEquals(2, MathUtils.log2floor(4));
- assertEquals(2, MathUtils.log2floor(5));
- assertEquals(2, MathUtils.log2floor(7));
- assertEquals(3, MathUtils.log2floor(8));
- assertEquals(3, MathUtils.log2floor(9));
- assertEquals(4, MathUtils.log2floor(16));
- assertEquals(4, MathUtils.log2floor(17));
- assertEquals(13, MathUtils.log2floor((0x1 << 13) + 1));
- assertEquals(30, MathUtils.log2floor(Integer.MAX_VALUE));
- assertEquals(31, MathUtils.log2floor(-1));
+ void testLog2Computation() {
+ assertThat(MathUtils.log2floor(1)).isZero();
+ assertThat(MathUtils.log2floor(2)).isOne();
+ assertThat(MathUtils.log2floor(3)).isOne();
+ assertThat(MathUtils.log2floor(4)).isEqualTo(2);
+ assertThat(MathUtils.log2floor(5)).isEqualTo(2);
+ assertThat(MathUtils.log2floor(7)).isEqualTo(2);
+ assertThat(MathUtils.log2floor(8)).isEqualTo(3);
+ assertThat(MathUtils.log2floor(9)).isEqualTo(3);
+ assertThat(MathUtils.log2floor(16)).isEqualTo(4);
+ assertThat(MathUtils.log2floor(17)).isEqualTo(4);
+ assertThat(MathUtils.log2floor((0x1 << 13) + 1)).isEqualTo(13);
+ assertThat(MathUtils.log2floor(Integer.MAX_VALUE)).isEqualTo(30);
+ assertThat(MathUtils.log2floor(-1)).isEqualTo(31);
- try {
- MathUtils.log2floor(0);
- fail();
- } catch (ArithmeticException ignored) {
- }
+ assertThatThrownBy(() -> MathUtils.log2floor(0)).isInstanceOf(ArithmeticException.class);
}
@Test
- public void testRoundDownToPowerOf2() {
- assertEquals(0, MathUtils.roundDownToPowerOf2(0));
- assertEquals(1, MathUtils.roundDownToPowerOf2(1));
- assertEquals(2, MathUtils.roundDownToPowerOf2(2));
- assertEquals(2, MathUtils.roundDownToPowerOf2(3));
- assertEquals(4, MathUtils.roundDownToPowerOf2(4));
- assertEquals(4, MathUtils.roundDownToPowerOf2(5));
- assertEquals(4, MathUtils.roundDownToPowerOf2(6));
- assertEquals(4, MathUtils.roundDownToPowerOf2(7));
- assertEquals(8, MathUtils.roundDownToPowerOf2(8));
- assertEquals(8, MathUtils.roundDownToPowerOf2(9));
- assertEquals(8, MathUtils.roundDownToPowerOf2(15));
- assertEquals(16, MathUtils.roundDownToPowerOf2(16));
- assertEquals(16, MathUtils.roundDownToPowerOf2(17));
- assertEquals(16, MathUtils.roundDownToPowerOf2(31));
- assertEquals(32, MathUtils.roundDownToPowerOf2(32));
- assertEquals(32, MathUtils.roundDownToPowerOf2(33));
- assertEquals(32, MathUtils.roundDownToPowerOf2(42));
- assertEquals(32, MathUtils.roundDownToPowerOf2(63));
- assertEquals(64, MathUtils.roundDownToPowerOf2(64));
- assertEquals(64, MathUtils.roundDownToPowerOf2(125));
- assertEquals(16384, MathUtils.roundDownToPowerOf2(25654));
- assertEquals(33554432, MathUtils.roundDownToPowerOf2(34366363));
- assertEquals(33554432, MathUtils.roundDownToPowerOf2(63463463));
- assertEquals(1073741824, MathUtils.roundDownToPowerOf2(1852987883));
- assertEquals(1073741824, MathUtils.roundDownToPowerOf2(Integer.MAX_VALUE));
+ void testRoundDownToPowerOf2() {
+ assertThat(MathUtils.roundDownToPowerOf2(0)).isZero();
+ assertThat(MathUtils.roundDownToPowerOf2(1)).isOne();
+ assertThat(MathUtils.roundDownToPowerOf2(2)).isEqualTo(2);
+ assertThat(MathUtils.roundDownToPowerOf2(3)).isEqualTo(2);
+ assertThat(MathUtils.roundDownToPowerOf2(4)).isEqualTo(4);
+ assertThat(MathUtils.roundDownToPowerOf2(5)).isEqualTo(4);
+ assertThat(MathUtils.roundDownToPowerOf2(6)).isEqualTo(4);
+ assertThat(MathUtils.roundDownToPowerOf2(7)).isEqualTo(4);
+ assertThat(MathUtils.roundDownToPowerOf2(8)).isEqualTo(8);
+ assertThat(MathUtils.roundDownToPowerOf2(9)).isEqualTo(8);
+ assertThat(MathUtils.roundDownToPowerOf2(15)).isEqualTo(8);
+ assertThat(MathUtils.roundDownToPowerOf2(16)).isEqualTo(16);
+ assertThat(MathUtils.roundDownToPowerOf2(17)).isEqualTo(16);
+ assertThat(MathUtils.roundDownToPowerOf2(31)).isEqualTo(16);
+ assertThat(MathUtils.roundDownToPowerOf2(32)).isEqualTo(32);
+ assertThat(MathUtils.roundDownToPowerOf2(33)).isEqualTo(32);
+ assertThat(MathUtils.roundDownToPowerOf2(42)).isEqualTo(32);
+ assertThat(MathUtils.roundDownToPowerOf2(63)).isEqualTo(32);
+ assertThat(MathUtils.roundDownToPowerOf2(64)).isEqualTo(64);
+ assertThat(MathUtils.roundDownToPowerOf2(125)).isEqualTo(64);
+ assertThat(MathUtils.roundDownToPowerOf2(25654)).isEqualTo(16384);
+ assertThat(MathUtils.roundDownToPowerOf2(34366363)).isEqualTo(33554432);
+ assertThat(MathUtils.roundDownToPowerOf2(63463463)).isEqualTo(33554432);
+ assertThat(MathUtils.roundDownToPowerOf2(1852987883)).isEqualTo(1073741824);
+ assertThat(MathUtils.roundDownToPowerOf2(Integer.MAX_VALUE)).isEqualTo(1073741824);
}
@Test
- public void testRoundUpToPowerOf2() {
- assertEquals(0, MathUtils.roundUpToPowerOfTwo(0));
- assertEquals(1, MathUtils.roundUpToPowerOfTwo(1));
- assertEquals(2, MathUtils.roundUpToPowerOfTwo(2));
- assertEquals(4, MathUtils.roundUpToPowerOfTwo(3));
- assertEquals(4, MathUtils.roundUpToPowerOfTwo(4));
- assertEquals(8, MathUtils.roundUpToPowerOfTwo(5));
- assertEquals(8, MathUtils.roundUpToPowerOfTwo(6));
- assertEquals(8, MathUtils.roundUpToPowerOfTwo(7));
- assertEquals(8, MathUtils.roundUpToPowerOfTwo(8));
- assertEquals(16, MathUtils.roundUpToPowerOfTwo(9));
- assertEquals(16, MathUtils.roundUpToPowerOfTwo(15));
- assertEquals(16, MathUtils.roundUpToPowerOfTwo(16));
- assertEquals(32, MathUtils.roundUpToPowerOfTwo(17));
- assertEquals(32, MathUtils.roundUpToPowerOfTwo(31));
- assertEquals(32, MathUtils.roundUpToPowerOfTwo(32));
- assertEquals(64, MathUtils.roundUpToPowerOfTwo(33));
- assertEquals(64, MathUtils.roundUpToPowerOfTwo(42));
- assertEquals(64, MathUtils.roundUpToPowerOfTwo(63));
- assertEquals(64, MathUtils.roundUpToPowerOfTwo(64));
- assertEquals(128, MathUtils.roundUpToPowerOfTwo(125));
- assertEquals(32768, MathUtils.roundUpToPowerOfTwo(25654));
- assertEquals(67108864, MathUtils.roundUpToPowerOfTwo(34366363));
- assertEquals(67108864, MathUtils.roundUpToPowerOfTwo(67108863));
- assertEquals(67108864, MathUtils.roundUpToPowerOfTwo(67108864));
- assertEquals(0x40000000, MathUtils.roundUpToPowerOfTwo(0x3FFFFFFE));
- assertEquals(0x40000000, MathUtils.roundUpToPowerOfTwo(0x3FFFFFFF));
- assertEquals(0x40000000, MathUtils.roundUpToPowerOfTwo(0x40000000));
+ void testRoundUpToPowerOf2() {
+ assertThat(MathUtils.roundUpToPowerOfTwo(0)).isZero();
+ assertThat(MathUtils.roundUpToPowerOfTwo(1)).isOne();
+ assertThat(MathUtils.roundUpToPowerOfTwo(2)).isEqualTo(2);
+ assertThat(MathUtils.roundUpToPowerOfTwo(3)).isEqualTo(4);
+ assertThat(MathUtils.roundUpToPowerOfTwo(4)).isEqualTo(4);
+ assertThat(MathUtils.roundUpToPowerOfTwo(5)).isEqualTo(8);
+ assertThat(MathUtils.roundUpToPowerOfTwo(6)).isEqualTo(8);
+ assertThat(MathUtils.roundUpToPowerOfTwo(7)).isEqualTo(8);
+ assertThat(MathUtils.roundUpToPowerOfTwo(8)).isEqualTo(8);
+ assertThat(MathUtils.roundUpToPowerOfTwo(9)).isEqualTo(16);
+ assertThat(MathUtils.roundUpToPowerOfTwo(15)).isEqualTo(16);
+ assertThat(MathUtils.roundUpToPowerOfTwo(16)).isEqualTo(16);
+ assertThat(MathUtils.roundUpToPowerOfTwo(17)).isEqualTo(32);
+ assertThat(MathUtils.roundUpToPowerOfTwo(31)).isEqualTo(32);
+ assertThat(MathUtils.roundUpToPowerOfTwo(32)).isEqualTo(32);
+ assertThat(MathUtils.roundUpToPowerOfTwo(33)).isEqualTo(64);
+ assertThat(MathUtils.roundUpToPowerOfTwo(42)).isEqualTo(64);
+ assertThat(MathUtils.roundUpToPowerOfTwo(63)).isEqualTo(64);
+ assertThat(MathUtils.roundUpToPowerOfTwo(64)).isEqualTo(64);
+ assertThat(MathUtils.roundUpToPowerOfTwo(125)).isEqualTo(128);
+ assertThat(MathUtils.roundUpToPowerOfTwo(25654)).isEqualTo(32768);
+ assertThat(MathUtils.roundUpToPowerOfTwo(34366363)).isEqualTo(67108864);
+ assertThat(MathUtils.roundUpToPowerOfTwo(67108863)).isEqualTo(67108864);
+ assertThat(MathUtils.roundUpToPowerOfTwo(67108864)).isEqualTo(67108864);
+ assertThat(MathUtils.roundUpToPowerOfTwo(0x3FFFFFFE)).isEqualTo(0x40000000);
+ assertThat(MathUtils.roundUpToPowerOfTwo(0x3FFFFFFF)).isEqualTo(0x40000000);
+ assertThat(MathUtils.roundUpToPowerOfTwo(0x40000000)).isEqualTo(0x40000000);
}
@Test
- public void testPowerOfTwo() {
- assertTrue(MathUtils.isPowerOf2(1));
- assertTrue(MathUtils.isPowerOf2(2));
- assertTrue(MathUtils.isPowerOf2(4));
- assertTrue(MathUtils.isPowerOf2(8));
- assertTrue(MathUtils.isPowerOf2(32768));
- assertTrue(MathUtils.isPowerOf2(65536));
- assertTrue(MathUtils.isPowerOf2(1 << 30));
- assertTrue(MathUtils.isPowerOf2(1L + Integer.MAX_VALUE));
- assertTrue(MathUtils.isPowerOf2(1L << 41));
- assertTrue(MathUtils.isPowerOf2(1L << 62));
+ void testPowerOfTwo() {
+ assertThat(MathUtils.isPowerOf2(1)).isTrue();
+ assertThat(MathUtils.isPowerOf2(2)).isTrue();
+ assertThat(MathUtils.isPowerOf2(4)).isTrue();
+ assertThat(MathUtils.isPowerOf2(8)).isTrue();
+ assertThat(MathUtils.isPowerOf2(32768)).isTrue();
+ assertThat(MathUtils.isPowerOf2(65536)).isTrue();
+ assertThat(MathUtils.isPowerOf2(1 << 30)).isTrue();
+ assertThat(MathUtils.isPowerOf2(1L + Integer.MAX_VALUE)).isTrue();
+ assertThat(MathUtils.isPowerOf2(1L << 41)).isTrue();
+ assertThat(MathUtils.isPowerOf2(1L << 62)).isTrue();
- assertFalse(MathUtils.isPowerOf2(3));
- assertFalse(MathUtils.isPowerOf2(5));
- assertFalse(MathUtils.isPowerOf2(567923));
- assertFalse(MathUtils.isPowerOf2(Integer.MAX_VALUE));
- assertFalse(MathUtils.isPowerOf2(Long.MAX_VALUE));
+ assertThat(MathUtils.isPowerOf2(3)).isFalse();
+ assertThat(MathUtils.isPowerOf2(5)).isFalse();
+ assertThat(MathUtils.isPowerOf2(567923)).isFalse();
+ assertThat(MathUtils.isPowerOf2(Integer.MAX_VALUE)).isFalse();
+ assertThat(MathUtils.isPowerOf2(Long.MAX_VALUE)).isFalse();
}
@Test
- public void testFlipSignBit() {
- Assert.assertEquals(0L, MathUtils.flipSignBit(Long.MIN_VALUE));
- Assert.assertEquals(Long.MIN_VALUE, MathUtils.flipSignBit(0L));
- Assert.assertEquals(-1L, MathUtils.flipSignBit(Long.MAX_VALUE));
- Assert.assertEquals(Long.MAX_VALUE, MathUtils.flipSignBit(-1L));
- Assert.assertEquals(42L | Long.MIN_VALUE, MathUtils.flipSignBit(42L));
- Assert.assertEquals(-42L & Long.MAX_VALUE, MathUtils.flipSignBit(-42L));
+ void testFlipSignBit() {
+ assertThat(MathUtils.flipSignBit(Long.MIN_VALUE)).isZero();
+ assertThat(MathUtils.flipSignBit(0L)).isEqualTo(Long.MIN_VALUE);
+ assertThat(MathUtils.flipSignBit(Long.MAX_VALUE)).isEqualTo(-1L);
+ assertThat(MathUtils.flipSignBit(-1L)).isEqualTo(Long.MAX_VALUE);
+ assertThat(MathUtils.flipSignBit(42L)).isEqualTo(42L | Long.MIN_VALUE);
+ assertThat(MathUtils.flipSignBit(-42L)).isEqualTo(-42L & Long.MAX_VALUE);
}
@Test
- public void testDivideRoundUp() {
- assertThat(MathUtils.divideRoundUp(0, 1), is(0));
- assertThat(MathUtils.divideRoundUp(0, 2), is(0));
- assertThat(MathUtils.divideRoundUp(1, 1), is(1));
- assertThat(MathUtils.divideRoundUp(1, 2), is(1));
- assertThat(MathUtils.divideRoundUp(2, 1), is(2));
- assertThat(MathUtils.divideRoundUp(2, 2), is(1));
- assertThat(MathUtils.divideRoundUp(2, 3), is(1));
+ void testDivideRoundUp() {
+ assertThat(MathUtils.divideRoundUp(0, 1)).isZero();
+ assertThat(MathUtils.divideRoundUp(0, 2)).isZero();
+ assertThat(MathUtils.divideRoundUp(1, 1)).isOne();
+ assertThat(MathUtils.divideRoundUp(1, 2)).isOne();
+ assertThat(MathUtils.divideRoundUp(2, 1)).isEqualTo(2);
+ assertThat(MathUtils.divideRoundUp(2, 2)).isOne();
+ assertThat(MathUtils.divideRoundUp(2, 3)).isOne();
}
- @Test(expected = IllegalArgumentException.class)
- public void testDivideRoundUpNegativeDividend() {
- MathUtils.divideRoundUp(-1, 1);
+ @Test
+ void testDivideRoundUpNegativeDividend() {
+ assertThatThrownBy(() -> MathUtils.divideRoundUp(-1, 1))
+ .isInstanceOf(IllegalArgumentException.class);
}
- @Test(expected = IllegalArgumentException.class)
- public void testDivideRoundUpNegativeDivisor() {
- MathUtils.divideRoundUp(1, -1);
+ @Test
+ void testDivideRoundUpNegativeDivisor() {
+ assertThatThrownBy(() -> MathUtils.divideRoundUp(1, -1))
+ .isInstanceOf(IllegalArgumentException.class);
}
- @Test(expected = IllegalArgumentException.class)
- public void testDivideRoundUpZeroDivisor() {
- MathUtils.divideRoundUp(1, 0);
+ @Test
+ void testDivideRoundUpZeroDivisor() {
+ assertThatThrownBy(() -> MathUtils.divideRoundUp(1, 0))
+ .isInstanceOf(IllegalArgumentException.class);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/MdcUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/MdcUtilsTest.java
index 35917d28c72..92d99a15c86 100644
--- a/flink-core/src/test/java/org/apache/flink/util/MdcUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/MdcUtilsTest.java
@@ -51,14 +51,14 @@ class MdcUtilsTest {
new LoggerAuditingExtension(MdcUtilsTest.class, DEBUG);
@Test
- public void testJobIDAsContext() {
+ void testJobIDAsContext() {
JobID jobID = new JobID();
assertThat(MdcUtils.asContextData(jobID))
.isEqualTo(Collections.singletonMap("flink-job-id", jobID.toHexString()));
}
@Test
- public void testMdcCloseableAddsJobId() throws Exception {
+ void testMdcCloseableAddsJobId() throws Exception {
assertJobIDLogged(
jobID -> {
try (MdcCloseable ignored = MdcUtils.withContext(asContextData(jobID))) {
@@ -68,7 +68,7 @@ class MdcUtilsTest {
}
@Test
- public void testMdcCloseableRemovesJobId() {
+ void testMdcCloseableRemovesJobId() {
JobID jobID = new JobID();
try (MdcCloseable ignored = MdcUtils.withContext(asContextData(jobID))) {
// ...
@@ -78,12 +78,12 @@ class MdcUtilsTest {
}
@Test
- public void testWrapRunnable() throws Exception {
+ void testWrapRunnable() throws Exception {
assertJobIDLogged(jobID -> wrapRunnable(asContextData(jobID), LOGGING_RUNNABLE).run());
}
@Test
- public void testWrapCallable() throws Exception {
+ void testWrapCallable() throws Exception {
assertJobIDLogged(
jobID ->
wrapCallable(
@@ -96,7 +96,7 @@ class MdcUtilsTest {
}
@Test
- public void testScopeExecutor() throws Exception {
+ void testScopeExecutor() throws Exception {
assertJobIDLogged(
jobID ->
MdcUtils.scopeToJob(jobID, Executors.directExecutor())
@@ -104,7 +104,7 @@ class MdcUtilsTest {
}
@Test
- public void testScopeExecutorService() throws Exception {
+ void testScopeExecutorService() throws Exception {
assertJobIDLogged(
jobID ->
MdcUtils.scopeToJob(jobID, Executors.newDirectExecutorService())
@@ -113,7 +113,7 @@ class MdcUtilsTest {
}
@Test
- public void testScopeScheduledExecutorService() throws Exception {
+ void testScopeScheduledExecutorService() throws Exception {
ScheduledExecutorService ses =
java.util.concurrent.Executors.newSingleThreadScheduledExecutor();
try {
diff --git a/flink-core/src/test/java/org/apache/flink/util/NetUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/NetUtilsTest.java
index a21b6c9727e..eb94a270968 100644
--- a/flink-core/src/test/java/org/apache/flink/util/NetUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/NetUtilsTest.java
@@ -20,9 +20,7 @@ package org.apache.flink.util;
import org.apache.flink.configuration.IllegalConfigurationException;
-import org.assertj.core.api.Assertions;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetAddress;
@@ -32,41 +30,41 @@ import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
+import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import static org.apache.flink.util.NetUtils.socketToUrl;
-import static org.hamcrest.core.IsCollectionContaining.hasItems;
-import static org.hamcrest.core.IsNot.not;
-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 the {@link NetUtils}. */
-public class NetUtilsTest extends TestLogger {
+class NetUtilsTest {
@Test
- public void testCorrectHostnamePort() throws Exception {
+ void testCorrectHostnamePort() throws Exception {
final URL url = new URL("http", "foo.com", 8080, "/index.html");
- assertEquals(url, NetUtils.getCorrectHostnamePort("foo.com:8080/index.html"));
+ assertThat(NetUtils.getCorrectHostnamePort("foo.com:8080/index.html")).isEqualTo(url);
}
@Test
- public void testCorrectHostnamePortWithHttpsScheme() throws Exception {
+ void testCorrectHostnamePortWithHttpsScheme() throws Exception {
final URL url = new URL("https", "foo.com", 8080, "/some/other/path/index.html");
- assertEquals(
- url,
- NetUtils.getCorrectHostnamePort("https://foo.com:8080/some/other/path/index.html"));
+ assertThat(
+ NetUtils.getCorrectHostnamePort(
+ "https://foo.com:8080/some/other/path/index.html"))
+ .isEqualTo(url);
}
@Test
- public void testParseHostPortAddress() {
+ void testParseHostPortAddress() {
final InetSocketAddress socketAddress = new InetSocketAddress("foo.com", 8080);
- assertEquals(socketAddress, NetUtils.parseHostPortAddress("foo.com:8080"));
+ assertThat(NetUtils.parseHostPortAddress("foo.com:8080")).isEqualTo(socketAddress);
}
@Test
- public void testAcceptWithoutTimeoutSuppressesTimeoutException() throws IOException {
+ void testAcceptWithoutTimeoutSuppressesTimeoutException() throws IOException {
// Validates that acceptWithoutTimeout suppresses all SocketTimeoutExceptions
Socket expected = new Socket();
ServerSocket serverSocket =
@@ -84,11 +82,11 @@ public class NetUtilsTest extends TestLogger {
}
};
- assertEquals(expected, NetUtils.acceptWithoutTimeout(serverSocket));
+ assertThat(NetUtils.acceptWithoutTimeout(serverSocket)).isEqualTo(expected);
}
@Test
- public void testAcceptWithoutTimeoutDefaultTimeout() throws IOException {
+ void testAcceptWithoutTimeoutDefaultTimeout() throws IOException {
// Default timeout (should be zero)
final Socket expected = new Socket();
try (final ServerSocket serverSocket =
@@ -98,12 +96,12 @@ public class NetUtilsTest extends TestLogger {
return expected;
}
}) {
- assertEquals(expected, NetUtils.acceptWithoutTimeout(serverSocket));
+ assertThat(NetUtils.acceptWithoutTimeout(serverSocket)).isEqualTo(expected);
}
}
@Test
- public void testAcceptWithoutTimeoutZeroTimeout() throws IOException {
+ void testAcceptWithoutTimeoutZeroTimeout() throws IOException {
// Explicitly sets a timeout of zero
final Socket expected = new Socket();
try (final ServerSocket serverSocket =
@@ -114,123 +112,104 @@ public class NetUtilsTest extends TestLogger {
}
}) {
serverSocket.setSoTimeout(0);
- assertEquals(expected, NetUtils.acceptWithoutTimeout(serverSocket));
+ assertThat(NetUtils.acceptWithoutTimeout(serverSocket)).isEqualTo(expected);
}
}
- @Test(expected = IllegalArgumentException.class)
- public void testAcceptWithoutTimeoutRejectsSocketWithSoTimeout() throws IOException {
- try (final ServerSocket serverSocket = new ServerSocket(0)) {
- serverSocket.setSoTimeout(5);
- NetUtils.acceptWithoutTimeout(serverSocket);
- }
+ @Test
+ void testAcceptWithoutTimeoutRejectsSocketWithSoTimeout() {
+ assertThatThrownBy(
+ () -> {
+ try (final ServerSocket serverSocket = new ServerSocket(0)) {
+ serverSocket.setSoTimeout(5);
+ NetUtils.acceptWithoutTimeout(serverSocket);
+ }
+ })
+ .isInstanceOf(IllegalArgumentException.class);
}
@Test
- public void testIPv4toURL() {
- try {
- final String addressString = "192.168.0.1";
+ void testIPv4toURL() throws UnknownHostException {
+ final String addressString = "192.168.0.1";
- InetAddress address = InetAddress.getByName(addressString);
- assertEquals(addressString, NetUtils.ipAddressToUrlString(address));
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ InetAddress address = InetAddress.getByName(addressString);
+ assertThat(NetUtils.ipAddressToUrlString(address)).isEqualTo(addressString);
}
@Test
- public void testIPv6toURL() {
- try {
- final String addressString = "2001:01db8:00:0:00:ff00:42:8329";
- final String normalizedAddress = "[2001:1db8::ff00:42:8329]";
-
- InetAddress address = InetAddress.getByName(addressString);
- assertEquals(normalizedAddress, NetUtils.ipAddressToUrlString(address));
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testIPv6toURL() throws UnknownHostException {
+ final String addressString = "2001:01db8:00:0:00:ff00:42:8329";
+ final String normalizedAddress = "[2001:1db8::ff00:42:8329]";
+
+ InetAddress address = InetAddress.getByName(addressString);
+ assertThat(NetUtils.ipAddressToUrlString(address)).isEqualTo(normalizedAddress);
}
@Test
- public void testIPv4URLEncoding() {
- try {
- final String addressString = "10.244.243.12";
- final int port = 23453;
-
- InetAddress address = InetAddress.getByName(addressString);
- InetSocketAddress socketAddress = new InetSocketAddress(address, port);
-
- assertEquals(addressString, NetUtils.ipAddressToUrlString(address));
- assertEquals(
- addressString + ':' + port,
- NetUtils.ipAddressAndPortToUrlString(address, port));
- assertEquals(
- addressString + ':' + port, NetUtils.socketAddressToUrlString(socketAddress));
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testIPv4URLEncoding() throws UnknownHostException {
+ final String addressString = "10.244.243.12";
+ final int port = 23453;
+
+ InetAddress address = InetAddress.getByName(addressString);
+ InetSocketAddress socketAddress = new InetSocketAddress(address, port);
+
+ assertThat(NetUtils.ipAddressToUrlString(address)).isEqualTo(addressString);
+ assertThat(NetUtils.ipAddressAndPortToUrlString(address, port))
+ .isEqualTo(addressString + ':' + port);
+ assertThat(NetUtils.socketAddressToUrlString(socketAddress))
+ .isEqualTo(addressString + ':' + port);
}
@Test
- public void testIPv6URLEncoding() {
- try {
- final String addressString = "2001:db8:10:11:12:ff00:42:8329";
- final String bracketedAddressString = '[' + addressString + ']';
- final int port = 23453;
-
- InetAddress address = InetAddress.getByName(addressString);
- InetSocketAddress socketAddress = new InetSocketAddress(address, port);
-
- assertEquals(bracketedAddressString, NetUtils.ipAddressToUrlString(address));
- assertEquals(
- bracketedAddressString + ':' + port,
- NetUtils.ipAddressAndPortToUrlString(address, port));
- assertEquals(
- bracketedAddressString + ':' + port,
- NetUtils.socketAddressToUrlString(socketAddress));
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testIPv6URLEncoding() throws UnknownHostException {
+ final String addressString = "2001:db8:10:11:12:ff00:42:8329";
+ final String bracketedAddressString = '[' + addressString + ']';
+ final int port = 23453;
+
+ InetAddress address = InetAddress.getByName(addressString);
+ InetSocketAddress socketAddress = new InetSocketAddress(address, port);
+
+ assertThat(NetUtils.ipAddressToUrlString(address)).isEqualTo(bracketedAddressString);
+ assertThat(NetUtils.ipAddressAndPortToUrlString(address, port))
+ .isEqualTo(bracketedAddressString + ':' + port);
+ assertThat(NetUtils.socketAddressToUrlString(socketAddress))
+ .isEqualTo(bracketedAddressString + ':' + port);
}
@Test
- public void testFreePortRangeUtility() {
+ void testFreePortRangeUtility() {
// inspired by Hadoop's example for "yarn.app.mapreduce.am.job.client.port-range"
String rangeDefinition =
"50000-50050, 50100-50200,51234 "; // this also contains some whitespaces
Iterator<Integer> portsIter = NetUtils.getPortRangeFromString(rangeDefinition);
Set<Integer> ports = new HashSet<>();
while (portsIter.hasNext()) {
- Assert.assertTrue("Duplicate element", ports.add(portsIter.next()));
+ assertThat(ports.add(portsIter.next())).isTrue();
}
- Assert.assertEquals(51 + 101 + 1, ports.size());
+ assertThat(ports).hasSize(51 + 101 + 1);
// check first range
- Assert.assertThat(ports, hasItems(50000, 50001, 50002, 50050));
+ assertThat(ports).contains(50000, 50001, 50002, 50050);
// check second range and last point
- Assert.assertThat(ports, hasItems(50100, 50101, 50110, 50200, 51234));
+ assertThat(ports).contains(50100, 50101, 50110, 50200, 51234);
// check that only ranges are included
- Assert.assertThat(ports, not(hasItems(50051, 50052, 1337, 50201, 49999, 50099)));
+ assertThat(ports).doesNotContain(50051, 50052, 1337, 50201, 49999, 50099);
// test single port "range":
portsIter = NetUtils.getPortRangeFromString(" 51234");
- Assert.assertTrue(portsIter.hasNext());
- Assert.assertEquals(51234, (int) portsIter.next());
- Assert.assertFalse(portsIter.hasNext());
+ assertThat(portsIter.hasNext()).isTrue();
+ assertThat((int) portsIter.next()).isEqualTo(51234);
+ assertThat(portsIter).isExhausted();
// test port list
portsIter = NetUtils.getPortRangeFromString("5,1,2,3,4");
- Assert.assertTrue(portsIter.hasNext());
- Assert.assertEquals(5, (int) portsIter.next());
- Assert.assertEquals(1, (int) portsIter.next());
- Assert.assertEquals(2, (int) portsIter.next());
- Assert.assertEquals(3, (int) portsIter.next());
- Assert.assertEquals(4, (int) portsIter.next());
- Assert.assertFalse(portsIter.hasNext());
+ assertThat(portsIter.hasNext()).isTrue();
+ assertThat((int) portsIter.next()).isEqualTo(5);
+ assertThat((int) portsIter.next()).isOne();
+ assertThat((int) portsIter.next()).isEqualTo(2);
+ assertThat((int) portsIter.next()).isEqualTo(3);
+ assertThat((int) portsIter.next()).isEqualTo(4);
+ assertThat(portsIter).isExhausted();
Throwable error = null;
@@ -240,7 +219,7 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof NumberFormatException);
+ assertThat(error).isInstanceOf(NumberFormatException.class);
error = null;
// incomplete range
@@ -249,7 +228,7 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof NumberFormatException);
+ assertThat(error).isInstanceOf(NumberFormatException.class);
error = null;
// incomplete range
@@ -258,7 +237,7 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof NumberFormatException);
+ assertThat(error).isInstanceOf(NumberFormatException.class);
error = null;
// empty range
@@ -267,7 +246,7 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof NumberFormatException);
+ assertThat(error).isInstanceOf(NumberFormatException.class);
// invalid port
try {
@@ -275,7 +254,7 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof IllegalConfigurationException);
+ assertThat(error).isInstanceOf(IllegalConfigurationException.class);
// invalid start
try {
@@ -283,7 +262,7 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof IllegalConfigurationException);
+ assertThat(error).isInstanceOf(IllegalConfigurationException.class);
// invalid end
try {
@@ -291,7 +270,7 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof IllegalConfigurationException);
+ assertThat(error).isInstanceOf(IllegalConfigurationException.class);
// same range
try {
@@ -299,117 +278,79 @@ public class NetUtilsTest extends TestLogger {
} catch (Throwable t) {
error = t;
}
- Assert.assertTrue(error instanceof IllegalConfigurationException);
+ assertThat(error).isInstanceOf(IllegalConfigurationException.class);
}
@Test
- public void testFormatAddress() {
- {
- // null
- String host = null;
- int port = 42;
- Assert.assertEquals(
- "127.0.0.1" + ":" + port,
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port));
- }
- {
- // IPv4
- String host = "1.2.3.4";
- int port = 42;
- Assert.assertEquals(
- host + ":" + port,
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port));
- }
- {
- // IPv6
- String host = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
- int port = 42;
- Assert.assertEquals(
- "[2001:db8:85a3::8a2e:370:7334]:" + port,
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port));
- }
- {
- // [IPv6]
- String host = "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]";
- int port = 42;
- Assert.assertEquals(
- "[2001:db8:85a3::8a2e:370:7334]:" + port,
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port));
- }
- {
- // Hostnames
- String host = "somerandomhostname";
- int port = 99;
- Assert.assertEquals(
- host + ":" + port,
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port));
- }
- {
- // Whitespace
- String host = " somerandomhostname ";
- int port = 99;
- Assert.assertEquals(
- host.trim() + ":" + port,
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port));
- }
- {
- // Illegal hostnames
- String host = "illegalhost.";
- int port = 42;
- try {
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port);
- fail();
- } catch (Exception ignored) {
- }
- // Illegal hostnames
- host = "illegalhost:fasf";
- try {
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port);
- fail();
- } catch (Exception ignored) {
- }
- }
- {
- // Illegal port ranges
- String host = "1.2.3.4";
- int port = -1;
- try {
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port);
- fail();
- } catch (Exception ignored) {
- }
- }
- {
- // lower case conversion of hostnames
- String host = "CamelCaseHostName";
- int port = 99;
- Assert.assertEquals(
- host.toLowerCase() + ":" + port,
- NetUtils.unresolvedHostAndPortToNormalizedString(host, port));
- }
+ void testFormatAddress() {
+
+ assertThat(NetUtils.unresolvedHostAndPortToNormalizedString(null, 42))
+ .isEqualTo("127.0.0.1" + ":" + 42);
+
+ // IPv4
+ assertThat(NetUtils.unresolvedHostAndPortToNormalizedString("1.2.3.4", 42))
+ .isEqualTo("1.2.3.4" + ":" + 42);
+
+ // IPv6
+ assertThat(
+ NetUtils.unresolvedHostAndPortToNormalizedString(
+ "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 42))
+ .isEqualTo("[2001:db8:85a3::8a2e:370:7334]:" + 42);
+
+ // [IPv6]
+ assertThat(
+ NetUtils.unresolvedHostAndPortToNormalizedString(
+ "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]", 42))
+ .isEqualTo("[2001:db8:85a3::8a2e:370:7334]:" + 42);
+
+ // Hostnames
+ assertThat(NetUtils.unresolvedHostAndPortToNormalizedString("somerandomhostname", 99))
+ .isEqualTo("somerandomhostname" + ":" + 99);
+
+ // Whitespace
+ assertThat(NetUtils.unresolvedHostAndPortToNormalizedString(" somerandomhostname ", 99))
+ .isEqualTo("somerandomhostname" + ":" + 99);
+
+ // Illegal hostnames
+ assertThatThrownBy(
+ () -> NetUtils.unresolvedHostAndPortToNormalizedString("illegalhost.", 42))
+ .isInstanceOf(IllegalConfigurationException.class);
+ assertThatThrownBy(
+ () ->
+ NetUtils.unresolvedHostAndPortToNormalizedString(
+ "illegalhost:fasf", 42))
+ .isInstanceOf(IllegalConfigurationException.class);
+
+ // Illegal port ranges
+ assertThatThrownBy(() -> NetUtils.unresolvedHostAndPortToNormalizedString("1.2.3.4", -1))
+ .isInstanceOf(Exception.class);
+
+ // lower case conversion of hostnames
+ assertThat(NetUtils.unresolvedHostAndPortToNormalizedString("CamelCaseHostName", 99))
+ .isEqualTo("camelcasehostname" + ":" + 99);
}
@Test
- public void testSocketToUrl() throws MalformedURLException {
+ void testSocketToUrl() throws MalformedURLException {
InetSocketAddress socketAddress = new InetSocketAddress("foo.com", 8080);
URL expectedResult = new URL("http://foo.com:8080");
- Assertions.assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult);
+ assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult);
}
@Test
- public void testIpv6SocketToUrl() throws MalformedURLException {
+ void testIpv6SocketToUrl() throws MalformedURLException {
InetSocketAddress socketAddress = new InetSocketAddress("[2001:1db8::ff00:42:8329]", 8080);
URL expectedResult = new URL("http://[2001:1db8::ff00:42:8329]:8080");
- Assertions.assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult);
+ assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult);
}
@Test
- public void testIpv4SocketToUrl() throws MalformedURLException {
+ void testIpv4SocketToUrl() throws MalformedURLException {
InetSocketAddress socketAddress = new InetSocketAddress("192.168.0.1", 8080);
URL expectedResult = new URL("http://192.168.0.1:8080");
- Assertions.assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult);
+ assertThat(socketToUrl(socketAddress)).isEqualTo(expectedResult);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/NumberSequenceIteratorTest.java b/flink-core/src/test/java/org/apache/flink/util/NumberSequenceIteratorTest.java
index 8335b9d250a..f9f7f117e9a 100644
--- a/flink-core/src/test/java/org/apache/flink/util/NumberSequenceIteratorTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/NumberSequenceIteratorTest.java
@@ -18,16 +18,15 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link NumberSequenceIterator}. */
-public class NumberSequenceIteratorTest extends TestLogger {
+class NumberSequenceIteratorTest {
@Test
- public void testSplitRegular() {
+ void testSplitRegular() {
testSplitting(new NumberSequenceIterator(0, 10), 2);
testSplitting(new NumberSequenceIterator(100, 100000), 7);
testSplitting(new NumberSequenceIterator(-100, 0), 5);
@@ -35,14 +34,14 @@ public class NumberSequenceIteratorTest extends TestLogger {
}
@Test
- public void testSplittingLargeRangesBy2() {
+ void testSplittingLargeRangesBy2() {
testSplitting(new NumberSequenceIterator(0, Long.MAX_VALUE), 2);
testSplitting(new NumberSequenceIterator(-1000000000L, Long.MAX_VALUE), 2);
testSplitting(new NumberSequenceIterator(Long.MIN_VALUE, Long.MAX_VALUE), 2);
}
@Test
- public void testSplittingTooSmallRanges() {
+ void testSplittingTooSmallRanges() {
testSplitting(new NumberSequenceIterator(0, 0), 2);
testSplitting(new NumberSequenceIterator(-5, -5), 2);
testSplitting(new NumberSequenceIterator(-5, -4), 3);
@@ -52,15 +51,15 @@ public class NumberSequenceIteratorTest extends TestLogger {
private static void testSplitting(NumberSequenceIterator iter, int numSplits) {
NumberSequenceIterator[] splits = iter.split(numSplits);
- assertEquals(numSplits, splits.length);
+ assertThat(splits).hasSize(numSplits);
// test start and end of range
- assertEquals(iter.getCurrent(), splits[0].getCurrent());
- assertEquals(iter.getTo(), splits[numSplits - 1].getTo());
+ assertThat(splits[0].getCurrent()).isEqualTo(iter.getCurrent());
+ assertThat(splits[numSplits - 1].getTo()).isEqualTo(iter.getTo());
// test continuous range
for (int i = 1; i < splits.length; i++) {
- assertEquals(splits[i - 1].getTo() + 1, splits[i].getCurrent());
+ assertThat(splits[i].getCurrent()).isEqualTo(splits[i - 1].getTo() + 1);
}
testMaxSplitDiff(splits);
@@ -85,6 +84,6 @@ public class NumberSequenceIteratorTest extends TestLogger {
maxSplitSize = Math.max(maxSplitSize, diff);
}
- assertTrue(maxSplitSize == minSplitSize || maxSplitSize - 1 == minSplitSize);
+ assertThat(maxSplitSize == minSplitSize || maxSplitSize - 1 == minSplitSize).isTrue();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/OutputTagTest.java b/flink-core/src/test/java/org/apache/flink/util/OutputTagTest.java
index 3c1c133bd0c..43d48ac53a0 100644
--- a/flink-core/src/test/java/org/apache/flink/util/OutputTagTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/OutputTagTest.java
@@ -20,28 +20,34 @@ package org.apache.flink.util;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for the {@link OutputTag}. */
-public class OutputTagTest {
+class OutputTagTest {
- @Test(expected = NullPointerException.class)
- public void testNullRejected() {
- new OutputTag<Integer>(null);
+ @Test
+ void testNullRejected() {
+ assertThatThrownBy(() -> new OutputTag<Integer>(null))
+ .isInstanceOf(NullPointerException.class);
}
- @Test(expected = NullPointerException.class)
- public void testNullRejectedWithTypeInfo() {
- new OutputTag<>(null, BasicTypeInfo.INT_TYPE_INFO);
+ @Test
+ void testNullRejectedWithTypeInfo() {
+ assertThatThrownBy(() -> new OutputTag<>(null, BasicTypeInfo.INT_TYPE_INFO))
+ .isInstanceOf(NullPointerException.class);
}
- @Test(expected = IllegalArgumentException.class)
- public void testEmptyStringRejected() {
- new OutputTag<Integer>("");
+ @Test
+ void testEmptyStringRejected() {
+ assertThatThrownBy(() -> new OutputTag<Integer>(""))
+ .isInstanceOf(IllegalArgumentException.class);
}
- @Test(expected = IllegalArgumentException.class)
- public void testEmptyStringRejectedWithTypeInfo() {
- new OutputTag<>("", BasicTypeInfo.INT_TYPE_INFO);
+ @Test
+ void testEmptyStringRejectedWithTypeInfo() {
+ assertThatThrownBy(() -> new OutputTag<>("", BasicTypeInfo.INT_TYPE_INFO))
+ .isInstanceOf(IllegalArgumentException.class);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/ProcessorArchitectureTest.java b/flink-core/src/test/java/org/apache/flink/util/ProcessorArchitectureTest.java
index b6b4162b19b..858748f7f90 100644
--- a/flink-core/src/test/java/org/apache/flink/util/ProcessorArchitectureTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/ProcessorArchitectureTest.java
@@ -18,24 +18,23 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link ProcessorArchitecture}. */
-public class ProcessorArchitectureTest {
+class ProcessorArchitectureTest {
@Test
- public void testArchitectureNotUnknown() {
+ void testArchitectureNotUnknown() {
final ProcessorArchitecture arch = ProcessorArchitecture.getProcessorArchitecture();
- assertNotEquals(ProcessorArchitecture.UNKNOWN, arch);
+ assertThat(arch).isNotEqualTo(ProcessorArchitecture.UNKNOWN);
}
@Test
- public void testNamesNotNull() {
+ void testNamesNotNull() {
final ProcessorArchitecture arch = ProcessorArchitecture.getProcessorArchitecture();
- assertNotNull(arch.getArchitectureName());
- assertNotNull(arch.getAlternativeNames());
+ assertThat(arch.getArchitectureName()).isNotNull();
+ assertThat(arch.getAlternativeNames()).isNotNull();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/PropertiesUtilTest.java b/flink-core/src/test/java/org/apache/flink/util/PropertiesUtilTest.java
index 293471a9046..1de683c3b3c 100644
--- a/flink-core/src/test/java/org/apache/flink/util/PropertiesUtilTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/PropertiesUtilTest.java
@@ -18,18 +18,18 @@
package org.apache.flink.util;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Properties;
import static org.apache.flink.util.PropertiesUtil.flatten;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link PropertiesUtil}. */
-public class PropertiesUtilTest {
+class PropertiesUtilTest {
@Test
- public void testFlatten() {
+ void testFlatten() {
// default Properties is null
Properties prop1 = new Properties();
prop1.put("key1", "value1");
@@ -43,8 +43,8 @@ public class PropertiesUtilTest {
prop3.put("key3", "value3");
Properties flattened = flatten(prop3);
- Assert.assertEquals(flattened.get("key1"), "value1");
- Assert.assertEquals(flattened.get("key2"), "value2");
- Assert.assertEquals(flattened.get("key3"), "value3");
+ assertThat("value1").isEqualTo(flattened.get("key1"));
+ assertThat("value2").isEqualTo(flattened.get("key2"));
+ assertThat("value3").isEqualTo(flattened.get("key3"));
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/ReferenceTest.java b/flink-core/src/test/java/org/apache/flink/util/ReferenceTest.java
index 8c1f999aaba..1292fcc4acd 100644
--- a/flink-core/src/test/java/org/apache/flink/util/ReferenceTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/ReferenceTest.java
@@ -18,31 +18,29 @@
package org.apache.flink.util;
-import org.junit.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link Reference}. */
-@ExtendWith({TestLoggerExtension.class})
-public class ReferenceTest {
+class ReferenceTest {
@Test
- public void testOwnedReferenceIsOwned() {
+ void testOwnedReferenceIsOwned() {
final Reference<String> value = Reference.owned("foobar");
assertThat(value.isOwned()).isTrue();
}
@Test
- public void testBorrowedReferenceIsNotOwned() {
+ void testBorrowedReferenceIsNotOwned() {
final Reference<String> value = Reference.borrowed("foobar");
assertThat(value.isOwned()).isFalse();
}
@Test
- public void testOwnedReferenceReturnsSomeOwned() {
+ void testOwnedReferenceReturnsSomeOwned() {
final String value = "foobar";
final Reference<String> owned = Reference.owned(value);
@@ -50,7 +48,7 @@ public class ReferenceTest {
}
@Test
- public void testBorrowedReferenceReturnsEmptyOwned() {
+ void testBorrowedReferenceReturnsEmptyOwned() {
Reference<String> value = Reference.borrowed("foobar");
assertThat(value.owned()).isEmpty();
diff --git a/flink-core/src/test/java/org/apache/flink/util/ResourceGuardTest.java b/flink-core/src/test/java/org/apache/flink/util/ResourceGuardTest.java
index 80f641e66f7..987529d9197 100644
--- a/flink-core/src/test/java/org/apache/flink/util/ResourceGuardTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/ResourceGuardTest.java
@@ -18,54 +18,50 @@
package org.apache.flink.util;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
/** Tests for the {@link ResourceGuard}. */
-public class ResourceGuardTest extends TestLogger {
+class ResourceGuardTest {
@Test
- public void testClose() {
+ void testClose() {
ResourceGuard resourceGuard = new ResourceGuard();
- Assert.assertFalse(resourceGuard.isClosed());
+ assertThat(resourceGuard.isClosed()).isFalse();
resourceGuard.close();
- Assert.assertTrue(resourceGuard.isClosed());
- try {
- resourceGuard.acquireResource();
- Assert.fail();
- } catch (IOException ignore) {
- }
+ assertThat(resourceGuard.isClosed()).isTrue();
+ assertThatThrownBy(resourceGuard::acquireResource).isInstanceOf(IOException.class);
}
@Test
- public void testAcquireReleaseClose() throws IOException {
+ void testAcquireReleaseClose() throws IOException {
ResourceGuard resourceGuard = new ResourceGuard();
ResourceGuard.Lease lease = resourceGuard.acquireResource();
- Assert.assertEquals(1, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isOne();
lease.close();
- Assert.assertEquals(0, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isZero();
resourceGuard.close();
- Assert.assertTrue(resourceGuard.isClosed());
+ assertThat(resourceGuard.isClosed()).isTrue();
}
@Test
- public void testCloseBlockIfAcquired() throws Exception {
+ void testCloseBlockIfAcquired() throws Exception {
ResourceGuard resourceGuard = new ResourceGuard();
ResourceGuard.Lease lease = resourceGuard.acquireResource();
AtomicBoolean checker = new AtomicBoolean(true);
Thread closerThread =
- new Thread() {
- @Override
- public void run() {
- // this line should block until all acquires are matched by releases.
- resourceGuard.close();
- checker.set(false);
- }
- };
+ new Thread(
+ () -> {
+ // this line should block until all acquires are matched by releases.
+ resourceGuard.close();
+ checker.set(false);
+ });
closerThread.start();
@@ -75,36 +71,30 @@ public class ResourceGuardTest extends TestLogger {
}
// validate that the close()-call is still blocked.
- Assert.assertTrue(checker.get());
+ assertThat(checker.get()).isTrue();
// validate that the closed-status is already effective.
- try {
- resourceGuard.acquireResource();
- Assert.fail("Resource guard is expected to be already closed.");
- } catch (IOException ignore) {
- }
+ assertThatThrownBy(resourceGuard::acquireResource).isInstanceOf(IOException.class);
// this matches the first acquire and will unblock the close()-call in the other thread.
lease.close();
closerThread.join(60_000);
- Assert.assertFalse(checker.get());
+ assertThat(checker.get()).isFalse();
}
@Test
- public void testInterruptHandledCorrectly() throws Exception {
+ void testInterruptHandledCorrectly() throws Exception {
ResourceGuard resourceGuard = new ResourceGuard();
ResourceGuard.Lease lease = resourceGuard.acquireResource();
AtomicBoolean checker = new AtomicBoolean(true);
Thread closerThread =
- new Thread() {
- @Override
- public void run() {
- // this line should block until all acquires are matched by releases.
- resourceGuard.close();
- checker.set(false);
- }
- };
+ new Thread(
+ () -> {
+ // this line should block until all acquires are matched by releases.
+ resourceGuard.close();
+ checker.set(false);
+ });
closerThread.start();
@@ -120,32 +110,32 @@ public class ResourceGuardTest extends TestLogger {
closerThread.join(100);
// check that unblock through interrupting failed.
- Assert.assertTrue(checker.get());
+ assertThat(checker.get()).isTrue();
// proper unblocking by closing the lease.
lease.close();
closerThread.join(60_000);
- Assert.assertFalse(checker.get());
+ assertThat(checker.get()).isFalse();
}
@Test
- public void testLeaseCloseIsIdempotent() throws Exception {
+ void testLeaseCloseIsIdempotent() throws Exception {
ResourceGuard resourceGuard = new ResourceGuard();
ResourceGuard.Lease lease1 = resourceGuard.acquireResource();
ResourceGuard.Lease lease2 = resourceGuard.acquireResource();
- Assert.assertEquals(2, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isEqualTo(2);
lease1.close();
- Assert.assertEquals(1, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isOne();
lease1.close();
- Assert.assertEquals(1, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isOne();
lease2.close();
- Assert.assertEquals(0, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isZero();
ResourceGuard.Lease lease3 = resourceGuard.acquireResource();
- Assert.assertEquals(1, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isOne();
lease2.close();
- Assert.assertEquals(1, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isOne();
lease3.close();
- Assert.assertEquals(0, resourceGuard.getLeaseCount());
+ assertThat(resourceGuard.getLeaseCount()).isZero();
resourceGuard.close();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/SerializedValueTest.java b/flink-core/src/test/java/org/apache/flink/util/SerializedValueTest.java
index 011d44fd05e..41bfed8eb1e 100644
--- a/flink-core/src/test/java/org/apache/flink/util/SerializedValueTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/SerializedValueTest.java
@@ -20,62 +20,57 @@ package org.apache.flink.util;
import org.apache.flink.core.testutils.CommonTestUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-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;
/** Tests for the {@link SerializedValue}. */
-public class SerializedValueTest {
+class SerializedValueTest {
@Test
- public void testSimpleValue() {
- try {
- final String value = "teststring";
-
- SerializedValue<String> v = new SerializedValue<>(value);
- SerializedValue<String> copy = CommonTestUtils.createCopySerializable(v);
-
- assertEquals(value, v.deserializeValue(getClass().getClassLoader()));
- assertEquals(value, copy.deserializeValue(getClass().getClassLoader()));
-
- assertEquals(v, copy);
- assertEquals(v.hashCode(), copy.hashCode());
-
- assertNotNull(v.toString());
- assertNotNull(copy.toString());
-
- assertNotEquals(0, v.getByteArray().length);
- assertArrayEquals(v.getByteArray(), copy.getByteArray());
-
- byte[] bytes = v.getByteArray();
- SerializedValue<String> saved =
- SerializedValue.fromBytes(Arrays.copyOf(bytes, bytes.length));
- assertEquals(v, saved);
- assertArrayEquals(v.getByteArray(), saved.getByteArray());
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testSimpleValue() throws Exception {
+ final String value = "teststring";
+
+ SerializedValue<String> v = new SerializedValue<>(value);
+ SerializedValue<String> copy = CommonTestUtils.createCopySerializable(v);
+
+ assertThat(v.deserializeValue(getClass().getClassLoader())).isEqualTo(value);
+ assertThat(copy.deserializeValue(getClass().getClassLoader())).isEqualTo(value);
+
+ assertThat(copy).isEqualTo(v);
+ assertThat(copy).hasSameHashCodeAs(v);
+
+ assertThat(v.toString()).isNotNull();
+ assertThat(copy.toString()).isNotNull();
+
+ assertThat(v.getByteArray()).isNotEmpty();
+ assertThat(copy.getByteArray()).isEqualTo(v.getByteArray());
+
+ byte[] bytes = v.getByteArray();
+ SerializedValue<String> saved =
+ SerializedValue.fromBytes(Arrays.copyOf(bytes, bytes.length));
+ assertThat(saved).isEqualTo(v);
+ assertThat(saved.getByteArray()).isEqualTo(v.getByteArray());
}
- @Test(expected = NullPointerException.class)
- public void testNullValue() throws Exception {
- new SerializedValue<>(null);
+ @Test
+ void testNullValue() {
+ assertThatThrownBy(() -> new SerializedValue<>(null))
+ .isInstanceOf(NullPointerException.class);
}
- @Test(expected = NullPointerException.class)
- public void testFromNullBytes() {
- SerializedValue.fromBytes(null);
+ @Test
+ void testFromNullBytes() {
+ assertThatThrownBy(() -> SerializedValue.fromBytes(null))
+ .isInstanceOf(NullPointerException.class);
}
- @Test(expected = IllegalArgumentException.class)
- public void testFromEmptyBytes() {
- SerializedValue.fromBytes(new byte[0]);
+ @Test
+ void testFromEmptyBytes() {
+ assertThatThrownBy(() -> SerializedValue.fromBytes(new byte[0]))
+ .isInstanceOf(IllegalArgumentException.class);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/StringUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/StringUtilsTest.java
index 20b6d7d8b71..65f7aebbf98 100644
--- a/flink-core/src/test/java/org/apache/flink/util/StringUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/StringUtilsTest.java
@@ -18,64 +18,59 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.DayOfWeek;
import java.util.Random;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link StringUtils}. */
-public class StringUtilsTest extends TestLogger {
+class StringUtilsTest {
@Test
- public void testControlCharacters() {
+ void testControlCharacters() {
String testString = "\b \t \n \f \r default";
String controlString = StringUtils.showControlCharacters(testString);
- assertEquals("\\b \\t \\n \\f \\r default", controlString);
+ assertThat(controlString).isEqualTo("\\b \\t \\n \\f \\r default");
}
@Test
- public void testArrayAwareToString() {
- assertEquals("null", StringUtils.arrayAwareToString(null));
+ void testArrayAwareToString() {
+ assertThat(StringUtils.arrayAwareToString(null)).isEqualTo("null");
- assertEquals("MONDAY", StringUtils.arrayAwareToString(DayOfWeek.MONDAY));
+ assertThat(StringUtils.arrayAwareToString(DayOfWeek.MONDAY)).isEqualTo("MONDAY");
- assertEquals("[1, 2, 3]", StringUtils.arrayAwareToString(new int[] {1, 2, 3}));
+ assertThat(StringUtils.arrayAwareToString(new int[] {1, 2, 3})).isEqualTo("[1, 2, 3]");
- assertEquals(
- "[[4, 5, 6], null, []]",
- StringUtils.arrayAwareToString(new byte[][] {{4, 5, 6}, null, {}}));
+ assertThat(StringUtils.arrayAwareToString(new byte[][] {{4, 5, 6}, null, {}}))
+ .isEqualTo("[[4, 5, 6], null, []]");
- assertEquals(
- "[[4, 5, 6], null, MONDAY]",
- StringUtils.arrayAwareToString(
- new Object[] {new Integer[] {4, 5, 6}, null, DayOfWeek.MONDAY}));
+ assertThat(
+ StringUtils.arrayAwareToString(
+ new Object[] {new Integer[] {4, 5, 6}, null, DayOfWeek.MONDAY}))
+ .isEqualTo("[[4, 5, 6], null, MONDAY]");
}
@Test
- public void testStringToHexArray() {
+ void testStringToHexArray() {
String hex = "019f314a";
byte[] hexArray = StringUtils.hexStringToByte(hex);
byte[] expectedArray = new byte[] {1, -97, 49, 74};
- assertArrayEquals(expectedArray, hexArray);
+ assertThat(hexArray).isEqualTo(expectedArray);
}
@Test
- public void testHexArrayToString() {
+ void testHexArrayToString() {
byte[] byteArray = new byte[] {1, -97, 49, 74};
String hex = StringUtils.byteToHexString(byteArray);
- assertEquals("019f314a", hex);
+ assertThat(hex).isEqualTo("019f314a");
}
@Test
- public void testGenerateAlphanumeric() {
+ void testGenerateAlphanumeric() {
String str = StringUtils.generateRandomAlphanumericString(new Random(), 256);
- if (!str.matches("[a-zA-Z0-9]{256}")) {
- fail("Not alphanumeric: " + str);
- }
+ assertThat(str).matches("[a-zA-Z0-9]{256}");
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/StringValueUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/StringValueUtilsTest.java
index 6e2f7e82298..53d82dfca08 100644
--- a/flink-core/src/test/java/org/apache/flink/util/StringValueUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/StringValueUtilsTest.java
@@ -21,53 +21,51 @@ package org.apache.flink.util;
import org.apache.flink.types.StringValue;
import org.apache.flink.util.StringValueUtils.WhitespaceTokenizer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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;
/** Tests for the {@link StringValueUtils}. */
-public class StringValueUtilsTest extends TestLogger {
+class StringValueUtilsTest {
@Test
- public void testToLowerCaseConverting() {
+ void testToLowerCaseConverting() {
StringValue testString = new StringValue("TEST");
StringValueUtils.toLowerCase(testString);
- assertEquals(new StringValue("test"), testString);
+ assertThat((Object) testString).isEqualTo(new StringValue("test"));
}
@Test
- public void testReplaceNonWordChars() {
+ void testReplaceNonWordChars() {
StringValue testString = new StringValue("TEST123_@");
StringValueUtils.replaceNonWordChars(testString, '!');
- assertEquals(new StringValue("TEST123_!"), testString);
+ assertThat((Object) testString).isEqualTo(new StringValue("TEST123_!"));
}
@Test
- public void testTokenizerOnStringWithoutNexToken() {
+ void testTokenizerOnStringWithoutNexToken() {
StringValue testString = new StringValue("test");
StringValueUtils.WhitespaceTokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setStringToTokenize(testString);
// first token
tokenizer.next(testString);
// next token is not exist
- assertFalse(tokenizer.next(testString));
+ assertThat(tokenizer.next(testString)).isFalse();
}
@Test
- public void testTokenizerOnStringWithNexToken() {
+ void testTokenizerOnStringWithNexToken() {
StringValue testString = new StringValue("test test");
StringValueUtils.WhitespaceTokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setStringToTokenize(testString);
- assertTrue(tokenizer.next(testString));
+ assertThat(tokenizer.next(testString)).isTrue();
}
@Test
- public void testTokenizerOnStringOnlyWithDelimiter() {
+ void testTokenizerOnStringOnlyWithDelimiter() {
StringValue testString = new StringValue(" ");
StringValueUtils.WhitespaceTokenizer tokenizer = new WhitespaceTokenizer();
tokenizer.setStringToTokenize(testString);
- assertFalse(tokenizer.next(testString));
+ assertThat(tokenizer.next(testString)).isFalse();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/TemporaryClassLoaderContextTest.java b/flink-core/src/test/java/org/apache/flink/util/TemporaryClassLoaderContextTest.java
index 4f5192b7715..e158a2ec3bb 100644
--- a/flink-core/src/test/java/org/apache/flink/util/TemporaryClassLoaderContextTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/TemporaryClassLoaderContextTest.java
@@ -18,18 +18,18 @@
package org.apache.flink.util;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URL;
import static org.apache.flink.util.FlinkUserCodeClassLoader.NOOP_EXCEPTION_HANDLER;
+import static org.assertj.core.api.Assertions.assertThat;
/** Test for {@link TemporaryClassLoaderContext}. */
-public class TemporaryClassLoaderContextTest {
+class TemporaryClassLoaderContextTest {
@Test
- public void testTemporaryClassLoaderContext() {
+ void testTemporaryClassLoaderContext() {
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
final ChildFirstClassLoader temporaryClassLoader =
@@ -38,10 +38,10 @@ public class TemporaryClassLoaderContextTest {
try (TemporaryClassLoaderContext ignored =
TemporaryClassLoaderContext.of(temporaryClassLoader)) {
- Assert.assertEquals(
- temporaryClassLoader, Thread.currentThread().getContextClassLoader());
+ assertThat(Thread.currentThread().getContextClassLoader())
+ .isEqualTo(temporaryClassLoader);
}
- Assert.assertEquals(contextClassLoader, Thread.currentThread().getContextClassLoader());
+ assertThat(Thread.currentThread().getContextClassLoader()).isEqualTo(contextClassLoader);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/TernaryBooleanTest.java b/flink-core/src/test/java/org/apache/flink/util/TernaryBooleanTest.java
index 284dd7f7621..fb11ac4ea0b 100644
--- a/flink-core/src/test/java/org/apache/flink/util/TernaryBooleanTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/TernaryBooleanTest.java
@@ -18,60 +18,57 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.apache.flink.util.TernaryBoolean.FALSE;
import static org.apache.flink.util.TernaryBoolean.TRUE;
import static org.apache.flink.util.TernaryBoolean.UNDEFINED;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.assertj.core.api.Assertions.assertThat;
/** Tests for the {@link TernaryBoolean} class. */
-public class TernaryBooleanTest {
+class TernaryBooleanTest {
@Test
- public void testWithDefault() {
- assertTrue(TRUE.getOrDefault(true));
- assertTrue(TRUE.getOrDefault(false));
+ void testWithDefault() {
+ assertThat(TRUE.getOrDefault(true)).isTrue();
+ assertThat(TRUE.getOrDefault(false)).isTrue();
- assertFalse(FALSE.getOrDefault(true));
- assertFalse(FALSE.getOrDefault(false));
+ assertThat(FALSE.getOrDefault(true)).isFalse();
+ assertThat(FALSE.getOrDefault(false)).isFalse();
- assertTrue(UNDEFINED.getOrDefault(true));
- assertFalse(UNDEFINED.getOrDefault(false));
+ assertThat(UNDEFINED.getOrDefault(true)).isTrue();
+ assertThat(UNDEFINED.getOrDefault(false)).isFalse();
}
@Test
- public void testResolveUndefined() {
- assertEquals(TRUE, TRUE.resolveUndefined(true));
- assertEquals(TRUE, TRUE.resolveUndefined(false));
+ void testResolveUndefined() {
+ assertThat(TRUE.resolveUndefined(true)).isEqualTo(TRUE);
+ assertThat(TRUE.resolveUndefined(false)).isEqualTo(TRUE);
- assertEquals(FALSE, FALSE.resolveUndefined(true));
- assertEquals(FALSE, FALSE.resolveUndefined(false));
+ assertThat(FALSE.resolveUndefined(true)).isEqualTo(FALSE);
+ assertThat(FALSE.resolveUndefined(false)).isEqualTo(FALSE);
- assertEquals(TRUE, UNDEFINED.resolveUndefined(true));
- assertEquals(FALSE, UNDEFINED.resolveUndefined(false));
+ assertThat(UNDEFINED.resolveUndefined(true)).isEqualTo(TRUE);
+ assertThat(UNDEFINED.resolveUndefined(false)).isEqualTo(FALSE);
}
@Test
- public void testToBoolean() {
- assertTrue(Boolean.TRUE == TRUE.getAsBoolean());
- assertTrue(Boolean.FALSE == FALSE.getAsBoolean());
- assertNull(UNDEFINED.getAsBoolean());
+ void testToBoolean() {
+ assertThat(TRUE.getAsBoolean()).isSameAs(Boolean.TRUE);
+ assertThat(FALSE.getAsBoolean()).isSameAs(Boolean.FALSE);
+ assertThat(UNDEFINED.getAsBoolean()).isNull();
}
@Test
- public void testFromBoolean() {
- assertEquals(TRUE, TernaryBoolean.fromBoolean(true));
- assertEquals(FALSE, TernaryBoolean.fromBoolean(false));
+ void testFromBoolean() {
+ assertThat(TernaryBoolean.fromBoolean(true)).isEqualTo(TRUE);
+ assertThat(TernaryBoolean.fromBoolean(false)).isEqualTo(FALSE);
}
@Test
- public void testFromBoxedBoolean() {
- assertEquals(TRUE, TernaryBoolean.fromBoxedBoolean(Boolean.TRUE));
- assertEquals(FALSE, TernaryBoolean.fromBoxedBoolean(Boolean.FALSE));
- assertEquals(UNDEFINED, TernaryBoolean.fromBoxedBoolean(null));
+ void testFromBoxedBoolean() {
+ assertThat(TernaryBoolean.fromBoxedBoolean(Boolean.TRUE)).isEqualTo(TRUE);
+ assertThat(TernaryBoolean.fromBoxedBoolean(Boolean.FALSE)).isEqualTo(FALSE);
+ assertThat(TernaryBoolean.fromBoxedBoolean(null)).isEqualTo(UNDEFINED);
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/TimeUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/TimeUtilsTest.java
index 269f0839c6a..349604fd042 100644
--- a/flink-core/src/test/java/org/apache/flink/util/TimeUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/TimeUtilsTest.java
@@ -20,173 +20,153 @@ package org.apache.flink.util;
import org.apache.flink.api.common.time.Time;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link TimeUtils}. */
-public class TimeUtilsTest {
+class TimeUtilsTest {
@Test
- public void testParseDurationNanos() {
- assertEquals(424562, TimeUtils.parseDuration("424562ns").getNano());
- assertEquals(424562, TimeUtils.parseDuration("424562nano").getNano());
- assertEquals(424562, TimeUtils.parseDuration("424562nanos").getNano());
- assertEquals(424562, TimeUtils.parseDuration("424562nanosecond").getNano());
- assertEquals(424562, TimeUtils.parseDuration("424562nanoseconds").getNano());
- assertEquals(424562, TimeUtils.parseDuration("424562 ns").getNano());
+ void testParseDurationNanos() {
+ assertThat(TimeUtils.parseDuration("424562ns").getNano()).isEqualTo(424562);
+ assertThat(TimeUtils.parseDuration("424562nano").getNano()).isEqualTo(424562);
+ assertThat(TimeUtils.parseDuration("424562nanos").getNano()).isEqualTo(424562);
+ assertThat(TimeUtils.parseDuration("424562nanosecond").getNano()).isEqualTo(424562);
+ assertThat(TimeUtils.parseDuration("424562nanoseconds").getNano()).isEqualTo(424562);
+ assertThat(TimeUtils.parseDuration("424562 ns").getNano()).isEqualTo(424562);
}
@Test
- public void testParseDurationMicros() {
- assertEquals(565731 * 1000L, TimeUtils.parseDuration("565731µs").getNano());
- assertEquals(565731 * 1000L, TimeUtils.parseDuration("565731micro").getNano());
- assertEquals(565731 * 1000L, TimeUtils.parseDuration("565731micros").getNano());
- assertEquals(565731 * 1000L, TimeUtils.parseDuration("565731microsecond").getNano());
- assertEquals(565731 * 1000L, TimeUtils.parseDuration("565731microseconds").getNano());
- assertEquals(565731 * 1000L, TimeUtils.parseDuration("565731 µs").getNano());
+ void testParseDurationMicros() {
+ assertThat(TimeUtils.parseDuration("565731µs").getNano()).isEqualTo(565731 * 1000L);
+ assertThat(TimeUtils.parseDuration("565731micro").getNano()).isEqualTo(565731 * 1000L);
+ assertThat(TimeUtils.parseDuration("565731micros").getNano()).isEqualTo(565731 * 1000L);
+ assertThat(TimeUtils.parseDuration("565731microsecond").getNano())
+ .isEqualTo(565731 * 1000L);
+ assertThat(TimeUtils.parseDuration("565731microseconds").getNano())
+ .isEqualTo(565731 * 1000L);
+ assertThat(TimeUtils.parseDuration("565731 µs").getNano()).isEqualTo(565731 * 1000L);
}
@Test
- public void testParseDurationMillis() {
- assertEquals(1234, TimeUtils.parseDuration("1234").toMillis());
- assertEquals(1234, TimeUtils.parseDuration("1234ms").toMillis());
- assertEquals(1234, TimeUtils.parseDuration("1234milli").toMillis());
- assertEquals(1234, TimeUtils.parseDuration("1234millis").toMillis());
- assertEquals(1234, TimeUtils.parseDuration("1234millisecond").toMillis());
- assertEquals(1234, TimeUtils.parseDuration("1234milliseconds").toMillis());
- assertEquals(1234, TimeUtils.parseDuration("1234 ms").toMillis());
+ void testParseDurationMillis() {
+ assertThat(TimeUtils.parseDuration("1234").toMillis()).isEqualTo(1234);
+ assertThat(TimeUtils.parseDuration("1234ms").toMillis()).isEqualTo(1234);
+ assertThat(TimeUtils.parseDuration("1234milli").toMillis()).isEqualTo(1234);
+ assertThat(TimeUtils.parseDuration("1234millis").toMillis()).isEqualTo(1234);
+ assertThat(TimeUtils.parseDuration("1234millisecond").toMillis()).isEqualTo(1234);
+ assertThat(TimeUtils.parseDuration("1234milliseconds").toMillis()).isEqualTo(1234);
+ assertThat(TimeUtils.parseDuration("1234 ms").toMillis()).isEqualTo(1234);
}
@Test
- public void testParseDurationSeconds() {
- assertEquals(667766, TimeUtils.parseDuration("667766s").getSeconds());
- assertEquals(667766, TimeUtils.parseDuration("667766sec").getSeconds());
- assertEquals(667766, TimeUtils.parseDuration("667766secs").getSeconds());
- assertEquals(667766, TimeUtils.parseDuration("667766second").getSeconds());
- assertEquals(667766, TimeUtils.parseDuration("667766seconds").getSeconds());
- assertEquals(667766, TimeUtils.parseDuration("667766 s").getSeconds());
+ void testParseDurationSeconds() {
+ assertThat(TimeUtils.parseDuration("667766s").getSeconds()).isEqualTo(667766);
+ assertThat(TimeUtils.parseDuration("667766sec").getSeconds()).isEqualTo(667766);
+ assertThat(TimeUtils.parseDuration("667766secs").getSeconds()).isEqualTo(667766);
+ assertThat(TimeUtils.parseDuration("667766second").getSeconds()).isEqualTo(667766);
+ assertThat(TimeUtils.parseDuration("667766seconds").getSeconds()).isEqualTo(667766);
+ assertThat(TimeUtils.parseDuration("667766 s").getSeconds()).isEqualTo(667766);
}
@Test
- public void testParseDurationMinutes() {
- assertEquals(7657623, TimeUtils.parseDuration("7657623m").toMinutes());
- assertEquals(7657623, TimeUtils.parseDuration("7657623min").toMinutes());
- assertEquals(7657623, TimeUtils.parseDuration("7657623minute").toMinutes());
- assertEquals(7657623, TimeUtils.parseDuration("7657623minutes").toMinutes());
- assertEquals(7657623, TimeUtils.parseDuration("7657623 min").toMinutes());
+ void testParseDurationMinutes() {
+ assertThat(TimeUtils.parseDuration("7657623m").toMinutes()).isEqualTo(7657623);
+ assertThat(TimeUtils.parseDuration("7657623min").toMinutes()).isEqualTo(7657623);
+ assertThat(TimeUtils.parseDuration("7657623minute").toMinutes()).isEqualTo(7657623);
+ assertThat(TimeUtils.parseDuration("7657623minutes").toMinutes()).isEqualTo(7657623);
+ assertThat(TimeUtils.parseDuration("7657623 min").toMinutes()).isEqualTo(7657623);
}
@Test
- public void testParseDurationHours() {
- assertEquals(987654, TimeUtils.parseDuration("987654h").toHours());
- assertEquals(987654, TimeUtils.parseDuration("987654hour").toHours());
- assertEquals(987654, TimeUtils.parseDuration("987654hours").toHours());
- assertEquals(987654, TimeUtils.parseDuration("987654 h").toHours());
+ void testParseDurationHours() {
+ assertThat(TimeUtils.parseDuration("987654h").toHours()).isEqualTo(987654);
+ assertThat(TimeUtils.parseDuration("987654hour").toHours()).isEqualTo(987654);
+ assertThat(TimeUtils.parseDuration("987654hours").toHours()).isEqualTo(987654);
+ assertThat(TimeUtils.parseDuration("987654 h").toHours()).isEqualTo(987654);
}
@Test
- public void testParseDurationDays() {
- assertEquals(987654, TimeUtils.parseDuration("987654d").toDays());
- assertEquals(987654, TimeUtils.parseDuration("987654day").toDays());
- assertEquals(987654, TimeUtils.parseDuration("987654days").toDays());
- assertEquals(987654, TimeUtils.parseDuration("987654 d").toDays());
+ void testParseDurationDays() {
+ assertThat(TimeUtils.parseDuration("987654d").toDays()).isEqualTo(987654);
+ assertThat(TimeUtils.parseDuration("987654day").toDays()).isEqualTo(987654);
+ assertThat(TimeUtils.parseDuration("987654days").toDays()).isEqualTo(987654);
+ assertThat(TimeUtils.parseDuration("987654 d").toDays()).isEqualTo(987654);
}
@Test
- public void testParseDurationUpperCase() {
- assertEquals(1L, TimeUtils.parseDuration("1 NS").toNanos());
- assertEquals(1000L, TimeUtils.parseDuration("1 MICRO").toNanos());
- assertEquals(1L, TimeUtils.parseDuration("1 MS").toMillis());
- assertEquals(1L, TimeUtils.parseDuration("1 S").getSeconds());
- assertEquals(1L, TimeUtils.parseDuration("1 MIN").toMinutes());
- assertEquals(1L, TimeUtils.parseDuration("1 H").toHours());
- assertEquals(1L, TimeUtils.parseDuration("1 D").toDays());
+ void testParseDurationUpperCase() {
+ assertThat(TimeUtils.parseDuration("1 NS").toNanos()).isOne();
+ assertThat(TimeUtils.parseDuration("1 MICRO").toNanos()).isEqualTo(1000L);
+ assertThat(TimeUtils.parseDuration("1 MS").toMillis()).isOne();
+ assertThat(TimeUtils.parseDuration("1 S").getSeconds()).isOne();
+ assertThat(TimeUtils.parseDuration("1 MIN").toMinutes()).isOne();
+ assertThat(TimeUtils.parseDuration("1 H").toHours()).isOne();
+ assertThat(TimeUtils.parseDuration("1 D").toDays()).isOne();
}
@Test
- public void testParseDurationTrim() {
- assertEquals(155L, TimeUtils.parseDuration(" 155 ").toMillis());
- assertEquals(155L, TimeUtils.parseDuration(" 155 ms ").toMillis());
+ void testParseDurationTrim() {
+ assertThat(TimeUtils.parseDuration(" 155 ").toMillis()).isEqualTo(155L);
+ assertThat(TimeUtils.parseDuration(" 155 ms ").toMillis()).isEqualTo(155L);
}
@Test
- public void testParseDurationInvalid() {
+ void testParseDurationInvalid() {
// null
- try {
- TimeUtils.parseDuration(null);
- fail("exception expected");
- } catch (NullPointerException ignored) {
- }
+ assertThatThrownBy(() -> TimeUtils.parseDuration(null))
+ .isInstanceOf(NullPointerException.class);
// empty
- try {
- TimeUtils.parseDuration("");
- fail("exception expected");
- } catch (IllegalArgumentException ignored) {
- }
+ assertThatThrownBy(() -> TimeUtils.parseDuration(""))
+ .isInstanceOf(IllegalArgumentException.class);
// blank
- try {
- TimeUtils.parseDuration(" ");
- fail("exception expected");
- } catch (IllegalArgumentException ignored) {
- }
+ assertThatThrownBy(() -> TimeUtils.parseDuration(" "))
+ .isInstanceOf(IllegalArgumentException.class);
// no number
- try {
- TimeUtils.parseDuration("foobar or fubar or foo bazz");
- fail("exception expected");
- } catch (IllegalArgumentException ignored) {
- }
+ assertThatThrownBy(() -> TimeUtils.parseDuration("foobar or fubar or foo bazz"))
+ .isInstanceOf(IllegalArgumentException.class);
// wrong unit
- try {
- TimeUtils.parseDuration("16 gjah");
- fail("exception expected");
- } catch (IllegalArgumentException ignored) {
- }
+ assertThatThrownBy(() -> TimeUtils.parseDuration("16 gjah"))
+ .isInstanceOf(IllegalArgumentException.class);
// multiple numbers
- try {
- TimeUtils.parseDuration("16 16 17 18 ms");
- fail("exception expected");
- } catch (IllegalArgumentException ignored) {
- }
+ assertThatThrownBy(() -> TimeUtils.parseDuration("16 16 17 18 ms"))
+ .isInstanceOf(IllegalArgumentException.class);
// negative number
- try {
- TimeUtils.parseDuration("-100 ms");
- fail("exception expected");
- } catch (IllegalArgumentException ignored) {
- }
+ assertThatThrownBy(() -> TimeUtils.parseDuration("-100 ms"))
+ .isInstanceOf(IllegalArgumentException.class);
}
- @Test(expected = IllegalArgumentException.class)
- public void testParseDurationNumberOverflow() {
- TimeUtils.parseDuration("100000000000000000000000000000000 ms");
+ @Test
+ void testParseDurationNumberOverflow() {
+ assertThatThrownBy(() -> TimeUtils.parseDuration("100000000000000000000000000000000 ms"))
+ .isInstanceOf(IllegalArgumentException.class);
}
@Test
- public void testGetStringInMillis() {
- assertEquals("4567ms", TimeUtils.getStringInMillis(Duration.ofMillis(4567L)));
- assertEquals("4567000ms", TimeUtils.getStringInMillis(Duration.ofSeconds(4567L)));
- assertEquals("4ms", TimeUtils.getStringInMillis(Duration.of(4567L, ChronoUnit.MICROS)));
+ void testGetStringInMillis() {
+ assertThat(TimeUtils.getStringInMillis(Duration.ofMillis(4567L))).isEqualTo("4567ms");
+ assertThat(TimeUtils.getStringInMillis(Duration.ofSeconds(4567L))).isEqualTo("4567000ms");
+ assertThat(TimeUtils.getStringInMillis(Duration.of(4567L, ChronoUnit.MICROS)))
+ .isEqualTo("4ms");
}
@Test
- public void testToDuration() {
+ void testToDuration() {
final Time time = Time.of(1337, TimeUnit.MICROSECONDS);
final Duration duration = TimeUtils.toDuration(time);
- assertThat(duration.toNanos(), is(equalTo(time.getUnit().toNanos(time.getSize()))));
+ assertThat(duration.toNanos()).isEqualTo(time.getUnit().toNanos(time.getSize()));
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/UnionIteratorTest.java b/flink-core/src/test/java/org/apache/flink/util/UnionIteratorTest.java
index 66714e8b023..97e82312ce1 100644
--- a/flink-core/src/test/java/org/apache/flink/util/UnionIteratorTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/UnionIteratorTest.java
@@ -18,126 +18,83 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-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;
/** Tests for the {@link UnionIterator}. */
-public class UnionIteratorTest {
+class UnionIteratorTest {
@Test
- public void testUnion() {
- try {
- UnionIterator<Integer> iter = new UnionIterator<>();
-
- // should succeed and be empty
- assertFalse(iter.iterator().hasNext());
-
- iter.clear();
-
- try {
- iter.iterator().next();
- fail("should fail with an exception");
- } catch (NoSuchElementException e) {
- // expected
- }
-
- iter.clear();
- iter.addList(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
- iter.addList(Collections.<Integer>emptyList());
- iter.addList(Arrays.asList(8, 9, 10, 11));
-
- int val = 1;
- for (int i : iter) {
- assertEquals(val++, i);
- }
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
+ void testUnion() {
+ UnionIterator<Integer> iter = new UnionIterator<>();
+
+ // should succeed and be empty
+ assertThat(iter.iterator()).isExhausted();
+
+ iter.clear();
+
+ assertThatThrownBy(() -> iter.iterator().next()).isInstanceOf(NoSuchElementException.class);
+
+ iter.clear();
+ iter.addList(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
+ iter.addList(Collections.emptyList());
+ iter.addList(Arrays.asList(8, 9, 10, 11));
+
+ int val = 1;
+ for (int i : iter) {
+ assertThat(i).isEqualTo(val++);
}
}
@Test
- public void testTraversableOnce() {
- try {
- UnionIterator<Integer> iter = new UnionIterator<>();
-
- // should succeed
- iter.iterator();
-
- // should fail
- try {
- iter.iterator();
- fail("should fail with an exception");
- } catch (TraversableOnceException e) {
- // expected
- }
-
- // should fail again
- try {
- iter.iterator();
- fail("should fail with an exception");
- } catch (TraversableOnceException e) {
- // expected
- }
-
- // reset the thing, keep it empty
- iter.clear();
-
- // should succeed
- iter.iterator();
-
- // should fail
- try {
- iter.iterator();
- fail("should fail with an exception");
- } catch (TraversableOnceException e) {
- // expected
- }
-
- // should fail again
- try {
- iter.iterator();
- fail("should fail with an exception");
- } catch (TraversableOnceException e) {
- // expected
- }
-
- // reset the thing, add some data
- iter.clear();
- iter.addList(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
-
- // should succeed
- Iterator<Integer> ints = iter.iterator();
- assertNotNull(ints.next());
- assertNotNull(ints.next());
- assertNotNull(ints.next());
-
- // should fail if called in the middle of operations
- try {
- iter.iterator();
- fail("should fail with an exception");
- } catch (TraversableOnceException e) {
- // expected
- }
-
- // reset the thing, keep it empty
- iter.clear();
-
- // should succeed again
- assertFalse(iter.iterator().hasNext());
-
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
+ void testTraversableOnce() {
+ UnionIterator<Integer> iter = new UnionIterator<>();
+
+ // should succeed
+ iter.iterator();
+
+ // should fail
+ assertThatThrownBy(iter::iterator).isInstanceOf(TraversableOnceException.class);
+
+ // should fail again
+ assertThatThrownBy(iter::iterator).isInstanceOf(TraversableOnceException.class);
+
+ // reset the thing, keep it empty
+ iter.clear();
+
+ // should succeed
+ iter.iterator();
+
+ // should fail
+ assertThatThrownBy(iter::iterator).isInstanceOf(TraversableOnceException.class);
+
+ // should fail again
+ assertThatThrownBy(iter::iterator).isInstanceOf(TraversableOnceException.class);
+
+ // reset the thing, add some data
+ iter.clear();
+ iter.addList(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
+
+ // should succeed
+ Iterator<Integer> ints = iter.iterator();
+ assertThat(ints.next()).isNotNull();
+ assertThat(ints.next()).isNotNull();
+ assertThat(ints.next()).isNotNull();
+
+ // should fail if called in the middle of operations
+ assertThatThrownBy(iter::iterator).isInstanceOf(TraversableOnceException.class);
+
+ // reset the thing, keep it empty
+ iter.clear();
+
+ // should succeed again
+ assertThat(iter.iterator()).isExhausted();
}
}
diff --git a/flink-core/src/test/java/org/apache/flink/util/WrappingProxyUtilTest.java b/flink-core/src/test/java/org/apache/flink/util/WrappingProxyUtilTest.java
index 363caf76858..6d9f1cb7d77 100644
--- a/flink-core/src/test/java/org/apache/flink/util/WrappingProxyUtilTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/WrappingProxyUtilTest.java
@@ -19,36 +19,31 @@
package org.apache.flink.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link WrappingProxyUtil}. */
-public class WrappingProxyUtilTest {
+class WrappingProxyUtilTest {
@Test
- public void testThrowsExceptionIfTooManyProxies() {
- try {
- WrappingProxyUtil.stripProxy(
- new SelfWrappingProxy(WrappingProxyUtil.SAFETY_NET_MAX_ITERATIONS));
- fail("Expected exception not thrown");
- } catch (final IllegalArgumentException e) {
- assertThat(e.getMessage(), containsString("Are there loops in the object graph?"));
- }
+ void testThrowsExceptionIfTooManyProxies() {
+ assertThatThrownBy(
+ () ->
+ WrappingProxyUtil.stripProxy(
+ new SelfWrappingProxy(
+ WrappingProxyUtil.SAFETY_NET_MAX_ITERATIONS)))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Are there loops in the object graph?");
}
@Test
- public void testStripsAllProxies() {
+ void testStripsAllProxies() {
final SelfWrappingProxy wrappingProxy =
new SelfWrappingProxy(WrappingProxyUtil.SAFETY_NET_MAX_ITERATIONS - 1);
- assertThat(
- WrappingProxyUtil.stripProxy(wrappingProxy),
- is(not(instanceOf(SelfWrappingProxy.class))));
+ assertThat(WrappingProxyUtil.stripProxy(wrappingProxy))
+ .isNotInstanceOf(SelfWrappingProxy.class);
}
private static class Wrapped {}
diff --git a/flink-core/src/test/java/org/apache/flink/util/concurrent/ConjunctFutureTest.java b/flink-core/src/test/java/org/apache/flink/util/concurrent/ConjunctFutureTest.java
index 2cdbbc8a559..de2e35f9bc3 100644
--- a/flink-core/src/test/java/org/apache/flink/util/concurrent/ConjunctFutureTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/concurrent/ConjunctFutureTest.java
@@ -19,12 +19,12 @@
package org.apache.flink.util.concurrent;
import org.apache.flink.api.java.tuple.Tuple2;
-import org.apache.flink.util.TestLogger;
+import org.apache.flink.testutils.junit.extensions.parameterized.ParameterizedTestExtension;
+import org.apache.flink.testutils.junit.extensions.parameterized.Parameters;
import org.apache.flink.util.concurrent.FutureUtils.ConjunctFuture;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
import java.io.IOException;
import java.util.ArrayList;
@@ -37,43 +37,41 @@ import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
-/** Tests for the {@link ConjunctFuture} and its sub classes. */
-@RunWith(Parameterized.class)
-public class ConjunctFutureTest extends TestLogger {
+/** Tests for the {@link ConjunctFuture} and its subclasses. */
+@ExtendWith(ParameterizedTestExtension.class)
+class ConjunctFutureTest {
- @Parameterized.Parameters
- public static Collection<FutureFactory> parameters() {
+ @Parameters
+ private static Collection<FutureFactory> parameters() {
return Arrays.asList(new ConjunctFutureFactory(), new WaitingFutureFactory());
}
- @Parameterized.Parameter public FutureFactory futureFactory;
+ private final FutureFactory futureFactory;
- @Test
- public void testConjunctFutureFailsOnEmptyAndNull() throws Exception {
- try {
- futureFactory.createFuture(null);
- fail();
- } catch (NullPointerException ignored) {
- }
+ ConjunctFutureTest(FutureFactory futureFactory) {
+ this.futureFactory = futureFactory;
+ }
- try {
- futureFactory.createFuture(
- Arrays.asList(new CompletableFuture<>(), null, new CompletableFuture<>()));
- fail();
- } catch (NullPointerException ignored) {
- }
+ @TestTemplate
+ void testConjunctFutureFailsOnEmptyAndNull() {
+ assertThatThrownBy(() -> futureFactory.createFuture(null))
+ .isInstanceOf(NullPointerException.class);
+
+ assertThatThrownBy(
+ () ->
+ futureFactory.createFuture(
+ Arrays.asList(
+ new CompletableFuture<>(),
+ null,
+ new CompletableFuture<>())))
+ .isInstanceOf(NullPointerException.class);
}
- @Test
- public void testConjunctFutureCompletion() throws Exception {
+ @TestTemplate
+ void testConjunctFutureCompletion() {
// some futures that we combine
java.util.concurrent.CompletableFuture<Object> future1 =
new java.util.concurrent.CompletableFuture<>();
@@ -93,37 +91,37 @@ public class ConjunctFutureTest extends TestLogger {
CompletableFuture<?> resultMapped = result.thenAccept(value -> {});
- assertEquals(4, result.getNumFuturesTotal());
- assertEquals(1, result.getNumFuturesCompleted());
- assertFalse(result.isDone());
- assertFalse(resultMapped.isDone());
+ assertThat(result.getNumFuturesTotal()).isEqualTo(4);
+ assertThat(result.getNumFuturesCompleted()).isOne();
+ assertThat(result.isDone()).isFalse();
+ assertThat(resultMapped.isDone()).isFalse();
// complete two more futures
future4.complete(new Object());
- assertEquals(2, result.getNumFuturesCompleted());
- assertFalse(result.isDone());
- assertFalse(resultMapped.isDone());
+ assertThat(result.getNumFuturesCompleted()).isEqualTo(2);
+ assertThat(result.isDone()).isFalse();
+ assertThat(resultMapped.isDone()).isFalse();
future1.complete(new Object());
- assertEquals(3, result.getNumFuturesCompleted());
- assertFalse(result.isDone());
- assertFalse(resultMapped.isDone());
+ assertThat(result.getNumFuturesCompleted()).isEqualTo(3);
+ assertThat(result.isDone()).isFalse();
+ assertThat(resultMapped.isDone()).isFalse();
// complete one future again
future1.complete(new Object());
- assertEquals(3, result.getNumFuturesCompleted());
- assertFalse(result.isDone());
- assertFalse(resultMapped.isDone());
+ assertThat(result.getNumFuturesCompleted()).isEqualTo(3);
+ assertThat(result.isDone()).isFalse();
+ assertThat(resultMapped.isDone()).isFalse();
// complete the final future
future3.complete(new Object());
- assertEquals(4, result.getNumFuturesCompleted());
- assertTrue(result.isDone());
- assertTrue(resultMapped.isDone());
+ assertThat(result.getNumFuturesCompleted()).isEqualTo(4);
+ assertThat(result.isDone()).isTrue();
+ assertThat(resultMapped.isDone()).isTrue();
}
- @Test
- public void testConjunctFutureFailureOnFirst() throws Exception {
+ @TestTemplate
+ void testConjunctFutureFailureOnFirst() {
java.util.concurrent.CompletableFuture<Object> future1 =
new java.util.concurrent.CompletableFuture<>();
@@ -140,34 +138,28 @@ public class ConjunctFutureTest extends TestLogger {
CompletableFuture<?> resultMapped = result.thenAccept(value -> {});
- assertEquals(4, result.getNumFuturesTotal());
- assertEquals(0, result.getNumFuturesCompleted());
- assertFalse(result.isDone());
- assertFalse(resultMapped.isDone());
+ assertThat(result.getNumFuturesTotal()).isEqualTo(4);
+ assertThat(result.getNumFuturesCompleted()).isZero();
+ assertThat(result.isDone()).isFalse();
+ assertThat(resultMapped.isDone()).isFalse();
future2.completeExceptionally(new IOException());
- assertEquals(0, result.getNumFuturesCompleted());
- assertTrue(result.isDone());
- assertTrue(resultMapped.isDone());
+ assertThat(result.getNumFuturesCompleted()).isZero();
+ assertThat(result.isDone()).isTrue();
+ assertThat(resultMapped.isDone()).isTrue();
- try {
- result.get();
- fail();
- } catch (ExecutionException e) {
- assertTrue(e.getCause() instanceof IOException);
- }
+ assertThatThrownBy(result::get)
+ .isInstanceOf(ExecutionException.class)
+ .hasCauseInstanceOf(IOException.class);
- try {
- resultMapped.get();
- fail();
- } catch (ExecutionException e) {
- assertTrue(e.getCause() instanceof IOException);
- }
+ assertThatThrownBy(resultMapped::get)
+ .isInstanceOf(ExecutionException.class)
+ .hasCauseInstanceOf(IOException.class);
}
- @Test
- public void testConjunctFutureFailureOnSuccessive() throws Exception {
+ @TestTemplate
+ void testConjunctFutureFailureOnSuccessive() {
java.util.concurrent.CompletableFuture<Object> future1 =
new java.util.concurrent.CompletableFuture<>();
@@ -181,7 +173,7 @@ public class ConjunctFutureTest extends TestLogger {
// build the conjunct future
ConjunctFuture<?> result =
futureFactory.createFuture(Arrays.asList(future1, future2, future3, future4));
- assertEquals(4, result.getNumFuturesTotal());
+ assertThat(result.getNumFuturesTotal()).isEqualTo(4);
java.util.concurrent.CompletableFuture<?> resultMapped = result.thenAccept(value -> {});
@@ -191,31 +183,25 @@ public class ConjunctFutureTest extends TestLogger {
future2.completeExceptionally(new IOException());
- assertEquals(3, result.getNumFuturesCompleted());
- assertTrue(result.isDone());
- assertTrue(resultMapped.isDone());
+ assertThat(result.getNumFuturesCompleted()).isEqualTo(3);
+ assertThat(result.isDone()).isTrue();
+ assertThat(resultMapped.isDone()).isTrue();
- try {
- result.get();
- fail();
- } catch (ExecutionException e) {
- assertTrue(e.getCause() instanceof IOException);
- }
+ assertThatThrownBy(result::get)
+ .isInstanceOf(ExecutionException.class)
+ .hasCauseInstanceOf(IOException.class);
- try {
- resultMapped.get();
- fail();
- } catch (ExecutionException e) {
- assertTrue(e.getCause() instanceof IOException);
- }
+ assertThatThrownBy(resultMapped::get)
+ .isInstanceOf(ExecutionException.class)
+ .hasCauseInstanceOf(IOException.class);
}
/**
* Tests that the conjunct future returns upon completion the collection of all future values in
* the same order in which the futures were inserted.
*/
- @Test
- public void testConjunctFutureValue() throws Exception {
+ @TestTemplate
+ void testConjunctFutureValue() throws Exception {
final int numberFutures = 10;
final List<CompletableFuture<Integer>> futures = new ArrayList<>(numberFutures);
@@ -232,30 +218,25 @@ public class ConjunctFutureTest extends TestLogger {
Collections.shuffle(shuffledFutures);
for (Tuple2<Integer, CompletableFuture<Integer>> shuffledFuture : shuffledFutures) {
- assertThat(result.isDone(), is(false));
+ assertThat(result.isDone()).isFalse();
shuffledFuture.f1.complete(shuffledFuture.f0);
}
- assertThat(result.isDone(), is(true));
+ assertThat(result.isDone()).isTrue();
- assertThat(
- result.get(),
- is(
- equalTo(
- IntStream.range(0, numberFutures)
- .boxed()
- .collect(Collectors.toList()))));
+ assertThat(result.get())
+ .isEqualTo(IntStream.range(0, numberFutures).boxed().collect(Collectors.toList()));
}
- @Test
- public void testConjunctOfNone() throws Exception {
+ @TestTemplate
+ void testConjunctOfNone() {
final ConjunctFuture<?> result =
futureFactory.createFuture(
Collections.<java.util.concurrent.CompletableFuture<Object>>emptyList());
- assertEquals(0, result.getNumFuturesTotal());
- assertEquals(0, result.getNumFuturesCompleted());
- assertTrue(result.isDone());
+ assertThat(result.getNumFuturesTotal()).isZero();
+ assertThat(result.getNumFuturesCompleted()).isZero();
+ assertThat(result.isDone()).isTrue();
}
/** Factory to create {@link ConjunctFuture} for testing. */
diff --git a/flink-core/src/test/java/org/apache/flink/util/concurrent/ExponentialBackoffRetryStrategyTest.java b/flink-core/src/test/java/org/apache/flink/util/concurrent/ExponentialBackoffRetryStrategyTest.java
index 8430b978e78..77759f6b928 100644
--- a/flink-core/src/test/java/org/apache/flink/util/concurrent/ExponentialBackoffRetryStrategyTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/concurrent/ExponentialBackoffRetryStrategyTest.java
@@ -18,8 +18,6 @@
package org.apache.flink.util.concurrent;
-import org.apache.flink.util.TestLogger;
-
import org.junit.jupiter.api.Test;
import java.time.Duration;
@@ -28,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link ExponentialBackoffRetryStrategy}. */
-public class ExponentialBackoffRetryStrategyTest extends TestLogger {
+class ExponentialBackoffRetryStrategyTest {
@Test
- public void testGettersNotCapped() {
+ void testGettersNotCapped() {
RetryStrategy retryStrategy =
new ExponentialBackoffRetryStrategy(
10, Duration.ofMillis(5L), Duration.ofMillis(20L));
@@ -44,7 +42,7 @@ public class ExponentialBackoffRetryStrategyTest extends TestLogger {
}
@Test
- public void testGettersHitCapped() {
+ void testGettersHitCapped() {
RetryStrategy retryStrategy =
new ExponentialBackoffRetryStrategy(
5, Duration.ofMillis(15L), Duration.ofMillis(20L));
@@ -57,7 +55,7 @@ public class ExponentialBackoffRetryStrategyTest extends TestLogger {
}
@Test
- public void testGettersAtCap() {
+ void testGettersAtCap() {
RetryStrategy retryStrategy =
new ExponentialBackoffRetryStrategy(
5, Duration.ofMillis(20L), Duration.ofMillis(20L));
@@ -71,7 +69,7 @@ public class ExponentialBackoffRetryStrategyTest extends TestLogger {
/** Tests that getting a next RetryStrategy below zero remaining retries fails. */
@Test
- public void testRetryFailure() {
+ void testRetryFailure() {
assertThatThrownBy(
() ->
new ExponentialBackoffRetryStrategy(
diff --git a/flink-core/src/test/java/org/apache/flink/util/concurrent/FixedRetryStrategyTest.java b/flink-core/src/test/java/org/apache/flink/util/concurrent/FixedRetryStrategyTest.java
index e7078d77ce9..87c400910e7 100644
--- a/flink-core/src/test/java/org/apache/flink/util/concurrent/FixedRetryStrategyTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/concurrent/FixedRetryStrategyTest.java
@@ -18,8 +18,6 @@
package org.apache.flink.util.concurrent;
-import org.apache.flink.util.TestLogger;
-
import org.junit.jupiter.api.Test;
import java.time.Duration;
@@ -28,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link FixedRetryStrategy}. */
-public class FixedRetryStrategyTest extends TestLogger {
+class FixedRetryStrategyTest {
@Test
- public void testGetters() {
+ void testGetters() {
RetryStrategy retryStrategy = new FixedRetryStrategy(10, Duration.ofMillis(5L));
assertThat(retryStrategy.getNumRemainingRetries()).isEqualTo(10);
assertThat(retryStrategy.getRetryDelay()).isEqualTo(Duration.ofMillis(5L));
@@ -43,7 +41,7 @@ public class FixedRetryStrategyTest extends TestLogger {
/** Tests that getting a next RetryStrategy below zero remaining retries fails. */
@Test
- public void testRetryFailure() {
+ void testRetryFailure() {
assertThatThrownBy(
() ->
new FixedRetryStrategy(0, Duration.ofMillis(5L))
diff --git a/flink-core/src/test/java/org/apache/flink/util/concurrent/FutureUtilsTest.java b/flink-core/src/test/java/org/apache/flink/util/concurrent/FutureUtilsTest.java
index 46be06f9f93..2485a48cecd 100644
--- a/flink-core/src/test/java/org/apache/flink/util/concurrent/FutureUtilsTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/concurrent/FutureUtilsTest.java
@@ -797,16 +797,15 @@ class FutureUtilsTest {
assertThat(caughtErrorHandlingException)
.hasValueSatisfying(
- actualError -> {
- assertThat(actualError)
- .isInstanceOf(IllegalStateException.class)
- .hasRootCause(errorHandlingException)
- .satisfies(
- cause ->
- assertThat(cause.getSuppressed())
- .containsExactly(
- actualProductionCodeError));
- });
+ actualError ->
+ assertThat(actualError)
+ .isInstanceOf(IllegalStateException.class)
+ .hasRootCause(errorHandlingException)
+ .satisfies(
+ cause ->
+ assertThat(cause.getSuppressed())
+ .containsExactly(
+ actualProductionCodeError)));
}
private static class TestingUncaughtExceptionHandler
diff --git a/flink-core/src/test/java/org/apache/flink/util/concurrent/IncrementalDelayRetryStrategyTest.java b/flink-core/src/test/java/org/apache/flink/util/concurrent/IncrementalDelayRetryStrategyTest.java
index 7920d40a29d..476e243a40e 100644
--- a/flink-core/src/test/java/org/apache/flink/util/concurrent/IncrementalDelayRetryStrategyTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/concurrent/IncrementalDelayRetryStrategyTest.java
@@ -18,8 +18,6 @@
package org.apache.flink.util.concurrent;
-import org.apache.flink.util.TestLogger;
-
import org.junit.jupiter.api.Test;
import java.time.Duration;
@@ -28,10 +26,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** Tests for {@link IncrementalDelayRetryStrategy}. */
-public class IncrementalDelayRetryStrategyTest extends TestLogger {
+class IncrementalDelayRetryStrategyTest {
@Test
- public void testGettersNotCapped() throws Exception {
+ void testGettersNotCapped() {
RetryStrategy retryStrategy =
new IncrementalDelayRetryStrategy(
10, Duration.ofMillis(5L), Duration.ofMillis(4L), Duration.ofMillis(20L));
@@ -44,7 +42,7 @@ public class IncrementalDelayRetryStrategyTest extends TestLogger {
}
@Test
- public void testGettersHitCapped() throws Exception {
+ void testGettersHitCapped() {
RetryStrategy retryStrategy =
new IncrementalDelayRetryStrategy(
5, Duration.ofMillis(15L), Duration.ofMillis(10L), Duration.ofMillis(20L));
@@ -57,7 +55,7 @@ public class IncrementalDelayRetryStrategyTest extends TestLogger {
}
@Test
- public void testGettersAtCap() throws Exception {
+ void testGettersAtCap() {
RetryStrategy retryStrategy =
new IncrementalDelayRetryStrategy(
5, Duration.ofMillis(20L), Duration.ofMillis(5L), Duration.ofMillis(20L));
@@ -71,7 +69,7 @@ public class IncrementalDelayRetryStrategyTest extends TestLogger {
/** Tests that getting a next RetryStrategy below zero remaining retries fails. */
@Test
- public void testRetryFailure() {
+ void testRetryFailure() {
assertThatThrownBy(
() ->
new IncrementalDelayRetryStrategy(
diff --git a/flink-core/src/test/java/org/apache/flink/util/function/CachingSupplierTest.java b/flink-core/src/test/java/org/apache/flink/util/function/CachingSupplierTest.java
index 8826887f37a..c2ed0d7018c 100644
--- a/flink-core/src/test/java/org/apache/flink/util/function/CachingSupplierTest.java
+++ b/flink-core/src/test/java/org/apache/flink/util/function/CachingSupplierTest.java
@@ -22,18 +22,17 @@ import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
+import static org.assertj.core.api.Assertions.assertThat;
class CachingSupplierTest {
@Test
void testCaching() {
final AtomicInteger instantiationCounts = new AtomicInteger();
- final Supplier<Integer> backingSupplier = () -> instantiationCounts.incrementAndGet();
+ final Supplier<Integer> backingSupplier = instantiationCounts::incrementAndGet;
final CachingSupplier<Integer> cachingSupplier = new CachingSupplier<>(backingSupplier);
- assertThat(cachingSupplier.get(), is(cachingSupplier.get()));
- assertThat(instantiationCounts.get(), is(1));
+ assertThat(cachingSupplier.get()).isEqualTo(cachingSupplier.get());
+ assertThat(instantiationCounts.get()).isOne();
}
}