You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by fr...@apache.org on 2026/08/11 09:58:58 UTC
(druid) branch master updated: test: migrate processing batch 1 to JUnit 5 (#19940)
This is an automated email from the ASF dual-hosted git repository.
FrankChen021 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/druid.git
The following commit(s) were added to refs/heads/master by this push:
new 1309686a456 test: migrate processing batch 1 to JUnit 5 (#19940)
1309686a456 is described below
commit 1309686a456817655502182e1e69d4919177080f
Author: Frank Chen <fr...@outlook.com>
AuthorDate: Tue Aug 11 17:58:52 2026 +0800
test: migrate processing batch 1 to JUnit 5 (#19940)
---
AGENTS.md | 17 +
benchmarks/pom.xml | 19 +-
.../benchmark/FlattenJSONBenchmarkUtilTest.java | 120 +++----
.../indexing/OnheapIncrementalIndexBenchmark.java | 18 +-
.../timeline/DimensionRangeShardSpecBenchmark.java | 20 +-
cloud/aws-common/pom.xml | 10 -
.../apache/druid/common/aws/AWSClientUtilTest.java | 26 +-
.../druid/common/aws/AWSCredentialsConfigTest.java | 28 +-
cloud/gcp-common/pom.xml | 9 +-
.../org/apache/druid/common/gcp/GcpModuleTest.java | 8 +-
.../collections/bitmap/BitmapIterationTest.java | 148 ++++----
.../bitmap/WrappedRoaringBitmapTest.java | 39 +--
.../collections/spatial/ImmutableRTreeTest.java | 76 ++---
.../apache/druid/common/guava/FutureUtilsTest.java | 76 ++---
.../common/semantic/SemanticCreatorUsageTest.java | 23 +-
.../apache/druid/common/utils/UUIDUtilsTest.java | 14 +-
.../data/input/impl/CombiningInputSourceTest.java | 25 +-
.../druid/data/input/impl/CsvReaderTest.java | 46 +--
.../druid/data/input/impl/DelimitedReaderTest.java | 50 +--
.../druid/data/input/impl/JsonNodeReaderTest.java | 133 ++++----
.../druid/data/input/impl/JsonReaderTest.java | 161 +++++----
.../data/input/impl/RetryingInputStreamTest.java | 1 +
.../org/apache/druid/data/input/impl/RowsTest.java | 151 ++++----
.../druid/guice/ConditionalMultibindTest.java | 48 +--
.../druid/guice/DruidSecondaryModuleTest.java | 61 ++--
.../apache/druid/guice/ExtensionsLoaderTest.java | 96 +++---
.../apache/druid/guice/JsonConfiguratorTest.java | 99 +++---
.../apache/druid/hll/HyperLogLogCollectorTest.java | 252 +++++++-------
.../druid/hll/HyperLogLogSerdeBenchmarkTest.java | 27 +-
.../druid/indexer/report/TaskReportSerdeTest.java | 76 ++---
.../java/util/common/CompressionUtilsTest.java | 300 ++++++++--------
.../druid/java/util/common/GranularityTest.java | 187 +++++-----
.../java/util/common/HumanReadableBytesTest.java | 379 ++++++++++-----------
.../druid/java/util/common/RetryUtilsTest.java | 6 +-
.../druid/java/util/common/StringUtilsTest.java | 221 ++++++------
.../guava/ParallelMergeCombiningSequenceTest.java | 264 +++++++-------
.../java/util/common/guava/TopNSequenceTest.java | 24 +-
.../druid/java/util/emitter/core/EmitterTest.java | 126 +++----
.../emitter/service/ServiceMetricEventTest.java | 82 +++--
.../java/util/http/client/FriendlyServersTest.java | 48 +--
.../java/util/http/client/JankyServersTest.java | 48 ++-
.../util/http/client/pool/ResourcePoolTest.java | 46 +--
.../ClockDriftSafeMonitorSchedulerTest.java | 24 +-
.../java/util/metrics/OshiSysMonitorTest.java | 248 +++++++-------
.../java/util/metrics/cgroups/CpuAcctTest.java | 59 ++--
.../druid/java/util/metrics/cgroups/CpuV2Test.java | 103 +++---
.../apache/druid/query/NestedDataTestUtils.java | 356 ++++++++++++++++++-
.../org/apache/druid/segment/CloserExtension.java | 110 ++++++
.../druid/testing/TemporaryFolderExtension.java | 145 ++++++++
.../testing/junit/LoggerCaptureExtension.java | 133 ++++++++
.../org/apache/druid/timeline/DataSegmentTest.java | 180 +++++-----
.../VersionedIntervalTimelineSpecificDataTest.java | 78 ++---
.../timeline/VersionedIntervalTimelineTest.java | 317 ++++++++---------
.../partition/DimensionRangeShardSpecTest.java | 54 +--
.../partition/DimensionValueSetShardSpecTest.java | 84 ++---
.../partition/HashBasedNumberedShardSpecTest.java | 100 +++---
.../partition/OvershadowableManagerTest.java | 239 +++++++------
.../partition/PartitionHolderCompletenessTest.java | 21 +-
.../org/apache/druid/utils/CloseableUtilsTest.java | 93 ++---
59 files changed, 3341 insertions(+), 2611 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 05e8c49e71a..54a1ba0ef89 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,6 +41,23 @@ Real-time analytics database. Java, Maven, multi-module project.
- End every file with a newline.
- Don't format changes unnecessarily.
+## Testing
+
+### JUnit 5 test helpers
+
+When adding or migrating tests, reuse these existing test-scope helpers:
+
+- `TemporaryFolderExtension` (`org.apache.druid.testing`) for tests that need a Druid-managed `File` temporary directory:
+
+ ```java
+ @RegisterExtension
+ public final TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();
+ ```
+
+ Use `getRoot()`, `newFolder(...)`, or `newFile(...)`. Prefer `TemporaryFolderExtension` over JUnit 5 `@TempDir` or JUnit 4 `TemporaryFolder`. Do not add new `TempFolderOperations` usages; the existing compatibility bridge is only for tests that have not yet migrated.
+
+- `LoggerCaptureExtension` (`org.apache.druid.testing.junit`) for capturing Log4j events. Register it with the target class and use `getLogEvents()`, `clearLogEvents()`, or `awaitLogEvents()` as needed.
+
## Pull Requests
- Before opening a PR, self-review the complete diff against the target branch. Verify that every change is intentional and in scope, check for correctness and regressions, and run the relevant tests or checks.
diff --git a/benchmarks/pom.xml b/benchmarks/pom.xml
index 8469572c77d..ecd7d983752 100644
--- a/benchmarks/pom.xml
+++ b/benchmarks/pom.xml
@@ -190,11 +190,6 @@
<groupId>com.github.seancfoley</groupId>
<artifactId>ipaddress</artifactId>
</dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
@@ -205,19 +200,19 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.junit.jupiter</groupId>
- <artifactId>junit-jupiter-migrationsupport</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
+ <!--
+ Required by test-jar helpers consumed by benchmark tests. Those helpers still reference
+ Hamcrest types even though the benchmark sources do not import Hamcrest directly. Remove
+ this dependency after all consumed test-jar helpers have migrated away from Hamcrest.
+ -->
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest</artifactId>
<scope>test</scope>
</dependency>
<dependency>
diff --git a/benchmarks/src/test/java/org/apache/druid/benchmark/FlattenJSONBenchmarkUtilTest.java b/benchmarks/src/test/java/org/apache/druid/benchmark/FlattenJSONBenchmarkUtilTest.java
index c356885b444..b533393ad90 100644
--- a/benchmarks/src/test/java/org/apache/druid/benchmark/FlattenJSONBenchmarkUtilTest.java
+++ b/benchmarks/src/test/java/org/apache/druid/benchmark/FlattenJSONBenchmarkUtilTest.java
@@ -29,8 +29,8 @@ import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.parsers.CloseableIterator;
import org.apache.druid.utils.JvmUtils;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class FlattenJSONBenchmarkUtilTest
{
@@ -87,77 +87,77 @@ public class FlattenJSONBenchmarkUtilTest
public void checkEvent1(InputRow event)
{
- Assert.assertEquals("2015-09-12T12:10:53.155Z", event.getRaw("ts").toString());
- Assert.assertEquals("-1170723877", event.getRaw("d1").toString());
- Assert.assertEquals("238976084", event.getRaw("d2").toString());
- Assert.assertEquals("0.9818780016507468", event.getRaw("m3").toString());
- Assert.assertEquals("-3.8218837693501747E18", event.getRaw("m4").toString());
- Assert.assertEquals("-509091100", event.getRaw("e1.d1").toString());
- Assert.assertEquals("274706327", event.getRaw("e1.d2").toString());
- Assert.assertEquals("870378185", event.getRaw("e2.d3").toString());
- Assert.assertEquals("-377775321", event.getRaw("e2.d4").toString());
- Assert.assertEquals("-1797988763", event.getRaw("e2.d5").toString());
- Assert.assertEquals("1309474524", event.getRaw("e2.d6").toString());
- Assert.assertEquals("129047958", event.getRaw("e2.ad1[0]").toString());
- Assert.assertEquals("1658972185", event.getRaw("e2.ad1[1]").toString());
- Assert.assertEquals("-997010830", event.getRaw("e2.ad1[2]").toString());
+ Assertions.assertEquals("2015-09-12T12:10:53.155Z", event.getRaw("ts").toString());
+ Assertions.assertEquals("-1170723877", event.getRaw("d1").toString());
+ Assertions.assertEquals("238976084", event.getRaw("d2").toString());
+ Assertions.assertEquals("0.9818780016507468", event.getRaw("m3").toString());
+ Assertions.assertEquals("-3.8218837693501747E18", event.getRaw("m4").toString());
+ Assertions.assertEquals("-509091100", event.getRaw("e1.d1").toString());
+ Assertions.assertEquals("274706327", event.getRaw("e1.d2").toString());
+ Assertions.assertEquals("870378185", event.getRaw("e2.d3").toString());
+ Assertions.assertEquals("-377775321", event.getRaw("e2.d4").toString());
+ Assertions.assertEquals("-1797988763", event.getRaw("e2.d5").toString());
+ Assertions.assertEquals("1309474524", event.getRaw("e2.d6").toString());
+ Assertions.assertEquals("129047958", event.getRaw("e2.ad1[0]").toString());
+ Assertions.assertEquals("1658972185", event.getRaw("e2.ad1[1]").toString());
+ Assertions.assertEquals("-997010830", event.getRaw("e2.ad1[2]").toString());
// Java 19 changes some floating point string representation
// https://bugs.openjdk.org/browse/JDK-8291475
if (JvmUtils.majorVersion() < 19) {
- Assert.assertEquals("-5.8772014847368817E18", event.getRaw("e3.m1").toString());
+ Assertions.assertEquals("-5.8772014847368817E18", event.getRaw("e3.m1").toString());
} else {
- Assert.assertEquals("-5.877201484736882E18", event.getRaw("e3.m1").toString());
+ Assertions.assertEquals("-5.877201484736882E18", event.getRaw("e3.m1").toString());
}
- Assert.assertEquals("0.4375433369079904", event.getRaw("e3.m2").toString());
- Assert.assertEquals("0.8510482953607659", event.getRaw("e3.m3").toString());
- Assert.assertEquals("-2.3832626488759337E18", event.getRaw("e3.m4").toString());
+ Assertions.assertEquals("0.4375433369079904", event.getRaw("e3.m2").toString());
+ Assertions.assertEquals("0.8510482953607659", event.getRaw("e3.m3").toString());
+ Assertions.assertEquals("-2.3832626488759337E18", event.getRaw("e3.m4").toString());
if (JvmUtils.majorVersion() < 19) {
- Assert.assertEquals("7.9789762132607068E18", event.getRaw("e3.am1[0]").toString());
- Assert.assertEquals("-7.8634787235005573E18", event.getRaw("e3.am1[1]").toString());
- Assert.assertEquals("8.7372945568982446E18", event.getRaw("e3.am1[2]").toString());
- Assert.assertEquals("3.1928124802414899E18", event.getRaw("e3.am1[3]").toString());
- Assert.assertEquals("-3.9806631713718011E18", event.getRaw("e4.e4.m4").toString());
+ Assertions.assertEquals("7.9789762132607068E18", event.getRaw("e3.am1[0]").toString());
+ Assertions.assertEquals("-7.8634787235005573E18", event.getRaw("e3.am1[1]").toString());
+ Assertions.assertEquals("8.7372945568982446E18", event.getRaw("e3.am1[2]").toString());
+ Assertions.assertEquals("3.1928124802414899E18", event.getRaw("e3.am1[3]").toString());
+ Assertions.assertEquals("-3.9806631713718011E18", event.getRaw("e4.e4.m4").toString());
} else {
- Assert.assertEquals("7.978976213260707E18", event.getRaw("e3.am1[0]").toString());
- Assert.assertEquals("-7.863478723500557E18", event.getRaw("e3.am1[1]").toString());
- Assert.assertEquals("8.737294556898245E18", event.getRaw("e3.am1[2]").toString());
- Assert.assertEquals("3.19281248024149E18", event.getRaw("e3.am1[3]").toString());
- Assert.assertEquals("-3.980663171371801E18", event.getRaw("e4.e4.m4").toString());
+ Assertions.assertEquals("7.978976213260707E18", event.getRaw("e3.am1[0]").toString());
+ Assertions.assertEquals("-7.863478723500557E18", event.getRaw("e3.am1[1]").toString());
+ Assertions.assertEquals("8.737294556898245E18", event.getRaw("e3.am1[2]").toString());
+ Assertions.assertEquals("3.19281248024149E18", event.getRaw("e3.am1[3]").toString());
+ Assertions.assertEquals("-3.980663171371801E18", event.getRaw("e4.e4.m4").toString());
}
- Assert.assertEquals("-1915243040", event.getRaw("ae1[0].d1").toString());
- Assert.assertEquals("-2020543641", event.getRaw("ae1[1].d1").toString());
- Assert.assertEquals("1414285347", event.getRaw("ae1[2].e1.d2").toString());
+ Assertions.assertEquals("-1915243040", event.getRaw("ae1[0].d1").toString());
+ Assertions.assertEquals("-2020543641", event.getRaw("ae1[1].d1").toString());
+ Assertions.assertEquals("1414285347", event.getRaw("ae1[2].e1.d2").toString());
}
public void checkEvent2(InputRow event2)
{
- Assert.assertEquals("728062074", event2.getRaw("ae1[0].d1").toString());
- Assert.assertEquals("1701675101", event2.getRaw("ae1[1].d1").toString());
- Assert.assertEquals("1887775139", event2.getRaw("ae1[2].e1.d2").toString());
- Assert.assertEquals("1375814994", event2.getRaw("e1.d1").toString());
- Assert.assertEquals("-1747933975", event2.getRaw("e1.d2").toString());
- Assert.assertEquals("1616761116", event2.getRaw("e2.ad1[0]").toString());
- Assert.assertEquals("7645432", event2.getRaw("e2.ad1[1]").toString());
- Assert.assertEquals("679897970", event2.getRaw("e2.ad1[2]").toString());
- Assert.assertEquals("-1797792200", event2.getRaw("e2.d3").toString());
- Assert.assertEquals("142582995", event2.getRaw("e2.d4").toString());
- Assert.assertEquals("-1341994709", event2.getRaw("e2.d5").toString());
- Assert.assertEquals("-889954295", event2.getRaw("e2.d6").toString());
- Assert.assertEquals("678995794", event2.getRaw("d1").toString());
- Assert.assertEquals("-1744549866", event2.getRaw("d2").toString());
- Assert.assertEquals("2015-09-12T12:10:53.155Z", event2.getRaw("ts").toString());
- Assert.assertEquals("0.7279915615037622", event2.getRaw("m3").toString());
- Assert.assertEquals("977083178034247050", event2.getRaw("m4").toString());
- Assert.assertEquals("1940993614184952155", event2.getRaw("e3.m1").toString());
- Assert.assertEquals("0.55936084127688", event2.getRaw("e3.m2").toString());
- Assert.assertEquals("0.22821798320943232", event2.getRaw("e3.m3").toString());
- Assert.assertEquals("8176144126231114468", event2.getRaw("e3.m4").toString());
- Assert.assertEquals("-7405674050450245158", event2.getRaw("e3.am1[0]").toString());
- Assert.assertEquals("150970357863018887", event2.getRaw("e3.am1[1]").toString());
- Assert.assertEquals("3261802881806411610", event2.getRaw("e3.am1[2]").toString());
- Assert.assertEquals("8492292414932401114", event2.getRaw("e3.am1[3]").toString());
- Assert.assertEquals("-1192952196729165097", event2.getRaw("e4.e4.m4").toString());
+ Assertions.assertEquals("728062074", event2.getRaw("ae1[0].d1").toString());
+ Assertions.assertEquals("1701675101", event2.getRaw("ae1[1].d1").toString());
+ Assertions.assertEquals("1887775139", event2.getRaw("ae1[2].e1.d2").toString());
+ Assertions.assertEquals("1375814994", event2.getRaw("e1.d1").toString());
+ Assertions.assertEquals("-1747933975", event2.getRaw("e1.d2").toString());
+ Assertions.assertEquals("1616761116", event2.getRaw("e2.ad1[0]").toString());
+ Assertions.assertEquals("7645432", event2.getRaw("e2.ad1[1]").toString());
+ Assertions.assertEquals("679897970", event2.getRaw("e2.ad1[2]").toString());
+ Assertions.assertEquals("-1797792200", event2.getRaw("e2.d3").toString());
+ Assertions.assertEquals("142582995", event2.getRaw("e2.d4").toString());
+ Assertions.assertEquals("-1341994709", event2.getRaw("e2.d5").toString());
+ Assertions.assertEquals("-889954295", event2.getRaw("e2.d6").toString());
+ Assertions.assertEquals("678995794", event2.getRaw("d1").toString());
+ Assertions.assertEquals("-1744549866", event2.getRaw("d2").toString());
+ Assertions.assertEquals("2015-09-12T12:10:53.155Z", event2.getRaw("ts").toString());
+ Assertions.assertEquals("0.7279915615037622", event2.getRaw("m3").toString());
+ Assertions.assertEquals("977083178034247050", event2.getRaw("m4").toString());
+ Assertions.assertEquals("1940993614184952155", event2.getRaw("e3.m1").toString());
+ Assertions.assertEquals("0.55936084127688", event2.getRaw("e3.m2").toString());
+ Assertions.assertEquals("0.22821798320943232", event2.getRaw("e3.m3").toString());
+ Assertions.assertEquals("8176144126231114468", event2.getRaw("e3.m4").toString());
+ Assertions.assertEquals("-7405674050450245158", event2.getRaw("e3.am1[0]").toString());
+ Assertions.assertEquals("150970357863018887", event2.getRaw("e3.am1[1]").toString());
+ Assertions.assertEquals("3261802881806411610", event2.getRaw("e3.am1[2]").toString());
+ Assertions.assertEquals("8492292414932401114", event2.getRaw("e3.am1[3]").toString());
+ Assertions.assertEquals("-1192952196729165097", event2.getRaw("e4.e4.m4").toString());
}
}
diff --git a/benchmarks/src/test/java/org/apache/druid/benchmark/indexing/OnheapIncrementalIndexBenchmark.java b/benchmarks/src/test/java/org/apache/druid/benchmark/indexing/OnheapIncrementalIndexBenchmark.java
index bdc91ce314c..b20388fa6b4 100644
--- a/benchmarks/src/test/java/org/apache/druid/benchmark/indexing/OnheapIncrementalIndexBenchmark.java
+++ b/benchmarks/src/test/java/org/apache/druid/benchmark/indexing/OnheapIncrementalIndexBenchmark.java
@@ -53,7 +53,7 @@ import org.apache.druid.segment.incremental.IncrementalIndex;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.incremental.OnheapIncrementalIndex;
import org.joda.time.Interval;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
@@ -278,7 +278,7 @@ public class OnheapIncrementalIndexBenchmark
List<Result<TimeseriesResultValue>> results = runner.run(QueryPlus.wrap(query)).toList();
for (Result<TimeseriesResultValue> result : results) {
if (someoneRan.get()) {
- Assert.assertTrue(result.getValue().getDoubleMetric("doubleSumResult0") > 0);
+ Assertions.assertTrue(result.getValue().getDoubleMetric("doubleSumResult0") > 0);
}
}
if (currentlyRunning.get() > 0) {
@@ -306,17 +306,17 @@ public class OnheapIncrementalIndexBenchmark
List<Result<TimeseriesResultValue>> results = runner.run(QueryPlus.wrap(query)).toList();
final int expectedVal = elementsPerAddTask * taskCount;
for (Result<TimeseriesResultValue> result : results) {
- Assert.assertEquals(elementsPerAddTask, result.getValue().getLongMetric("rows").intValue());
+ Assertions.assertEquals(elementsPerAddTask, result.getValue().getLongMetric("rows").intValue());
for (int i = 0; i < DIMENSION_COUNT; ++i) {
- Assert.assertEquals(
- StringUtils.format("Failed long sum on dimension %d", i),
+ Assertions.assertEquals(
expectedVal,
- result.getValue().getLongMetric(StringUtils.format("sumResult%s", i)).intValue()
+ result.getValue().getLongMetric(StringUtils.format("sumResult%s", i)).intValue(),
+ StringUtils.format("Failed long sum on dimension %d", i)
);
- Assert.assertEquals(
- StringUtils.format("Failed double sum on dimension %d", i),
+ Assertions.assertEquals(
expectedVal,
- result.getValue().getDoubleMetric(StringUtils.format("doubleSumResult%s", i)).intValue()
+ result.getValue().getDoubleMetric(StringUtils.format("doubleSumResult%s", i)).intValue(),
+ StringUtils.format("Failed double sum on dimension %d", i)
);
}
}
diff --git a/benchmarks/src/test/java/org/apache/druid/timeline/DimensionRangeShardSpecBenchmark.java b/benchmarks/src/test/java/org/apache/druid/timeline/DimensionRangeShardSpecBenchmark.java
index df1bd027a9a..ac62e937e32 100644
--- a/benchmarks/src/test/java/org/apache/druid/timeline/DimensionRangeShardSpecBenchmark.java
+++ b/benchmarks/src/test/java/org/apache/druid/timeline/DimensionRangeShardSpecBenchmark.java
@@ -28,7 +28,7 @@ import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.query.filter.InDimFilter;
import org.apache.druid.segment.VirtualColumns;
import org.apache.druid.timeline.partition.DimensionRangeShardSpec;
-import org.junit.Assert;
+import org.junit.jupiter.api.Assertions;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
@@ -124,24 +124,24 @@ public class DimensionRangeShardSpecBenchmark
@Benchmark
public void benchSinglePrunable()
{
- Assert.assertFalse(shardSpec0.possibleInDomain(domainSinglePrunable));
- Assert.assertTrue(shardSpec1.possibleInDomain(domainSinglePrunable));
- Assert.assertFalse(shardSpec2.possibleInDomain(domainSinglePrunable));
+ Assertions.assertFalse(shardSpec0.possibleInDomain(domainSinglePrunable));
+ Assertions.assertTrue(shardSpec1.possibleInDomain(domainSinglePrunable));
+ Assertions.assertFalse(shardSpec2.possibleInDomain(domainSinglePrunable));
}
@Benchmark
public void bench5kPrunable()
{
- Assert.assertTrue(shardSpec0.possibleInDomain(domain5kPrunable));
- Assert.assertTrue(shardSpec1.possibleInDomain(domain5kPrunable));
- Assert.assertTrue(shardSpec2.possibleInDomain(domain5kPrunable));
+ Assertions.assertTrue(shardSpec0.possibleInDomain(domain5kPrunable));
+ Assertions.assertTrue(shardSpec1.possibleInDomain(domain5kPrunable));
+ Assertions.assertTrue(shardSpec2.possibleInDomain(domain5kPrunable));
}
@Benchmark
public void benchSingleNonPrunable()
{
- Assert.assertTrue(shardSpec0.possibleInDomain(domainSingleNonPrunable));
- Assert.assertTrue(shardSpec1.possibleInDomain(domainSingleNonPrunable));
- Assert.assertTrue(shardSpec2.possibleInDomain(domainSingleNonPrunable));
+ Assertions.assertTrue(shardSpec0.possibleInDomain(domainSingleNonPrunable));
+ Assertions.assertTrue(shardSpec1.possibleInDomain(domainSingleNonPrunable));
+ Assertions.assertTrue(shardSpec2.possibleInDomain(domainSingleNonPrunable));
}
}
diff --git a/cloud/aws-common/pom.xml b/cloud/aws-common/pom.xml
index ab664679924..756d53a20bf 100644
--- a/cloud/aws-common/pom.xml
+++ b/cloud/aws-common/pom.xml
@@ -106,16 +106,6 @@
</dependency>
<!-- Tests -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
diff --git a/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSClientUtilTest.java b/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSClientUtilTest.java
index 535bfcc8b39..d8b500a84c1 100644
--- a/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSClientUtilTest.java
+++ b/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSClientUtilTest.java
@@ -19,8 +19,8 @@
package org.apache.druid.common.aws;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.exception.SdkClientException;
@@ -32,7 +32,7 @@ public class AWSClientUtilTest
@Test
public void testRecoverableException_IOException()
{
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(SdkClientException.builder().cause(new IOException()).build()));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(SdkClientException.builder().cause(new IOException()).build()));
}
@Test
@@ -44,7 +44,7 @@ public class AWSClientUtilTest
.errorCode("RequestTimeout")
.build())
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -54,7 +54,7 @@ public class AWSClientUtilTest
.message("Internal Server Error")
.statusCode(500)
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -64,7 +64,7 @@ public class AWSClientUtilTest
.message("Bad Gateway")
.statusCode(502)
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -74,7 +74,7 @@ public class AWSClientUtilTest
.message("Service Unavailable")
.statusCode(503)
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -86,7 +86,7 @@ public class AWSClientUtilTest
.errorCode("ProvisionedThroughputExceededException")
.build())
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -95,7 +95,7 @@ public class AWSClientUtilTest
final SdkClientException ex = SdkClientException.builder()
.message("Unable to load credentials from any of the providers in the chain AwsCredentialsProviderChain")
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -104,7 +104,7 @@ public class AWSClientUtilTest
final SdkClientException ex = SdkClientException.builder()
.message("LazyFileSessionCredentialsProvider(): cannot refresh AWS credentials")
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -113,7 +113,7 @@ public class AWSClientUtilTest
final SdkClientException ex = SdkClientException.builder()
.message("InstanceProfileCredentialsProvider(): Failed to load credentials from IMDS.")
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
@@ -125,13 +125,13 @@ public class AWSClientUtilTest
.errorCode("RequestExpired")
.build())
.build();
- Assert.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertTrue(AWSClientUtil.isClientExceptionRecoverable(ex));
}
@Test
public void testNonRecoverableException_RuntimeException()
{
SdkClientException ex = SdkClientException.builder().cause(new RuntimeException()).build();
- Assert.assertFalse(AWSClientUtil.isClientExceptionRecoverable(ex));
+ Assertions.assertFalse(AWSClientUtil.isClientExceptionRecoverable(ex));
}
}
diff --git a/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSCredentialsConfigTest.java b/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSCredentialsConfigTest.java
index 6d811d30d43..cf99c67c46c 100644
--- a/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSCredentialsConfigTest.java
+++ b/cloud/aws-common/src/test/java/org/apache/druid/common/aws/AWSCredentialsConfigTest.java
@@ -28,10 +28,10 @@ import org.apache.druid.guice.JsonConfigProvider;
import org.apache.druid.guice.JsonConfigurator;
import org.apache.druid.guice.LazySingleton;
import org.apache.druid.metadata.DefaultPasswordProvider;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.validation.Validation;
import javax.validation.Validator;
@@ -44,13 +44,13 @@ public class AWSCredentialsConfigTest
private static final String SOME_SECRET = "someSecret";
private final Properties properties = new Properties();
- @Before
+ @BeforeEach
public void setUp()
{
cleanProperties();
}
- @After
+ @AfterEach
public void tearDown()
{
cleanProperties();
@@ -82,8 +82,8 @@ public class AWSCredentialsConfigTest
{
final Injector injector = createInjector();
final AWSCredentialsConfig credentialsConfig = injector.getInstance(AWSCredentialsConfig.class);
- Assert.assertEquals("", credentialsConfig.getAccessKey().getPassword());
- Assert.assertEquals("", credentialsConfig.getSecretKey().getPassword());
+ Assertions.assertEquals("", credentialsConfig.getAccessKey().getPassword());
+ Assertions.assertEquals("", credentialsConfig.getSecretKey().getPassword());
}
@Test
@@ -96,9 +96,9 @@ public class AWSCredentialsConfigTest
final Injector injector = createInjector();
final AWSCredentialsConfig credentialsConfig = injector.getInstance(AWSCredentialsConfig.class);
- Assert.assertEquals(filePath, credentialsConfig.getFileSessionCredentials());
- Assert.assertEquals(SOME_SECRET, credentialsConfig.getAccessKey().getPassword());
- Assert.assertEquals(SOME_SECRET, credentialsConfig.getSecretKey().getPassword());
+ Assertions.assertEquals(filePath, credentialsConfig.getFileSessionCredentials());
+ Assertions.assertEquals(SOME_SECRET, credentialsConfig.getAccessKey().getPassword());
+ Assertions.assertEquals(SOME_SECRET, credentialsConfig.getSecretKey().getPassword());
}
@Test
@@ -112,8 +112,8 @@ public class AWSCredentialsConfigTest
final Injector injector = createInjector();
final AWSCredentialsConfig credentialsConfig = injector.getInstance(AWSCredentialsConfig.class);
- Assert.assertEquals(filePath, credentialsConfig.getFileSessionCredentials());
- Assert.assertEquals(SOME_SECRET, credentialsConfig.getAccessKey().getPassword());
- Assert.assertEquals(SOME_SECRET, credentialsConfig.getSecretKey().getPassword());
+ Assertions.assertEquals(filePath, credentialsConfig.getFileSessionCredentials());
+ Assertions.assertEquals(SOME_SECRET, credentialsConfig.getAccessKey().getPassword());
+ Assertions.assertEquals(SOME_SECRET, credentialsConfig.getSecretKey().getPassword());
}
}
diff --git a/cloud/gcp-common/pom.xml b/cloud/gcp-common/pom.xml
index 813342849f1..649b98a4d31 100644
--- a/cloud/gcp-common/pom.xml
+++ b/cloud/gcp-common/pom.xml
@@ -63,8 +63,13 @@
<!-- Tests -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/cloud/gcp-common/src/test/java/org/apache/druid/common/gcp/GcpModuleTest.java b/cloud/gcp-common/src/test/java/org/apache/druid/common/gcp/GcpModuleTest.java
index 3813ef55b27..7095eeedc3f 100644
--- a/cloud/gcp-common/src/test/java/org/apache/druid/common/gcp/GcpModuleTest.java
+++ b/cloud/gcp-common/src/test/java/org/apache/druid/common/gcp/GcpModuleTest.java
@@ -30,8 +30,8 @@ import com.google.inject.Injector;
import com.google.inject.util.Modules;
import org.apache.druid.guice.DruidScopes;
import org.apache.druid.guice.LazySingleton;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
public class GcpModuleTest
{
@@ -55,7 +55,7 @@ public class GcpModuleTest
return new MockGoogleCredential.Builder().setTransport(transport).setJsonFactory(factory).build();
}
}));
- Assert.assertTrue(injector.getInstance(HttpRequestInitializer.class) instanceof MockGoogleCredential);
- Assert.assertTrue(injector.getInstance(HttpTransport.class) instanceof MockHttpTransport);
+ Assertions.assertTrue(injector.getInstance(HttpRequestInitializer.class) instanceof MockGoogleCredential);
+ Assertions.assertTrue(injector.getInstance(HttpTransport.class) instanceof MockHttpTransport);
}
}
diff --git a/processing/src/test/java/org/apache/druid/collections/bitmap/BitmapIterationTest.java b/processing/src/test/java/org/apache/druid/collections/bitmap/BitmapIterationTest.java
index 94a9b3a9540..bf9a567726a 100644
--- a/processing/src/test/java/org/apache/druid/collections/bitmap/BitmapIterationTest.java
+++ b/processing/src/test/java/org/apache/druid/collections/bitmap/BitmapIterationTest.java
@@ -19,77 +19,88 @@
package org.apache.druid.collections.bitmap;
-import com.google.common.collect.UnmodifiableIterator;
-import com.google.common.collect.testing.CollectionTestSuiteBuilder;
-import com.google.common.collect.testing.SampleElements;
-import com.google.common.collect.testing.TestCollectionGenerator;
-import com.google.common.collect.testing.features.CollectionFeature;
-import com.google.common.collect.testing.features.CollectionSize;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import org.roaringbitmap.IntIterator;
import java.util.AbstractCollection;
-import java.util.Arrays;
-import java.util.Collections;
+import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
-public class BitmapIterationTest extends TestCase
+public class BitmapIterationTest
{
- public static Test suite()
+ public static List<BitmapFactory> factories()
{
- List<BitmapFactory> factories = Arrays.asList(
- new BitSetBitmapFactory(),
- new ConciseBitmapFactory()
- // Roaring iteration fails because it doesn't throw NoSuchElementException on next() call when there are no more
- // elements. Instead, it either throws NullPointerException or returns some unspecified value. If bitmap
- // iterators are always used correctly in shouldn't be a problem, but if next() is occasionally called after
- // hasNext() returned false and it returns some unspecified value, and everything continues to work without
- // indication that there was a error, it would be a bug that is very hard to catch.
- //
- // This line should be uncommented when Druid updates RoaringBitmap dependency to a version which includes a fix
- // for https://github.com/RoaringBitmap/RoaringBitmap/issues/129, or when RoaringBitmap is included into Druid
- // as a module and the issue is fixed there.
-
- //new RoaringBitmapFactory()
+ return List.of(new BitSetBitmapFactory(), new ConciseBitmapFactory());
+ }
+
+ public static Stream<Arguments> factoriesAndElements()
+ {
+ final List<List<Integer>> elementSets = List.of(
+ List.of(),
+ List.of(1),
+ List.of(1, 0, 2, 3, 4),
+ List.of(4, 3, 2, 1, 0, 5, 6, 7, 8, 9),
+ List.of(1, 0, 2, 3, 4, 1, 0),
+ IntStream.range(0, 128).boxed().collect(Collectors.toList())
);
- TestSuite suite = new TestSuite();
- for (BitmapFactory factory : factories) {
- suite.addTest(suiteForFactory(factory));
+ return factories().stream()
+ .flatMap(factory -> elementSets.stream().map(elements -> Arguments.of(factory, elements)));
+ }
+
+ @ParameterizedTest
+ @MethodSource("factoriesAndElements")
+ public void testIteration(final BitmapFactory factory, final List<Integer> elements)
+ {
+ final MutableBitmap mutableBitmap = factory.makeEmptyMutableBitmap();
+ elements.forEach(mutableBitmap::add);
+
+ final BitmapCollection collection = new BitmapCollection(factory.makeImmutableBitmap(mutableBitmap));
+ final List<Integer> expectedElements = elements.stream().distinct().sorted().collect(Collectors.toList());
+ final List<Integer> actualElements = new ArrayList<>();
+ final Iterator<Integer> iterator = collection.iterator();
+ while (iterator.hasNext()) {
+ actualElements.add(iterator.next());
}
- return suite;
+
+ Assertions.assertEquals(expectedElements, actualElements);
+ Assertions.assertEquals(expectedElements.size(), collection.size());
+ Assertions.assertFalse(iterator.hasNext());
+ Assertions.assertThrows(NoSuchElementException.class, iterator::next);
}
- private static Test suiteForFactory(BitmapFactory factory)
+ @ParameterizedTest
+ @MethodSource("factories")
+ public void testRestrictedElements(final BitmapFactory factory)
{
- return CollectionTestSuiteBuilder
- .using(new BitmapCollectionGenerator(factory))
- .named("bitmap iteration tests of " + factory)
- .withFeatures(CollectionFeature.KNOWN_ORDER)
- .withFeatures(CollectionFeature.REJECTS_DUPLICATES_AT_CREATION)
- .withFeatures(CollectionFeature.RESTRICTS_ELEMENTS)
- .withFeatures(CollectionSize.ANY)
- .createTestSuite();
+ final BitmapCollection collection = new BitmapCollection(factory.makeEmptyImmutableBitmap());
+ Assertions.assertThrows(UnsupportedOperationException.class, () -> collection.add(0));
+ Assertions.assertThrows(UnsupportedOperationException.class, () -> collection.addAll(List.of(0)));
+ Assertions.assertThrows(UnsupportedOperationException.class, collection.iterator()::remove);
}
private static class BitmapCollection extends AbstractCollection<Integer>
{
private final ImmutableBitmap bitmap;
- private final int size;
- private BitmapCollection(ImmutableBitmap bitmap, int size)
+ private BitmapCollection(final ImmutableBitmap bitmap)
{
this.bitmap = bitmap;
- this.size = size;
}
@Override
- public UnmodifiableIterator<Integer> iterator()
+ public Iterator<Integer> iterator()
{
final IntIterator iterator = bitmap.iterator();
- return new UnmodifiableIterator<>()
+ return new Iterator<>()
{
@Override
public boolean hasNext()
@@ -102,52 +113,19 @@ public class BitmapIterationTest extends TestCase
{
return iterator.next();
}
+
+ @Override
+ public void remove()
+ {
+ throw new UnsupportedOperationException();
+ }
};
}
@Override
public int size()
{
- return size;
- }
- }
-
- private static class BitmapCollectionGenerator implements TestCollectionGenerator<Integer>
- {
- private final BitmapFactory factory;
-
- private BitmapCollectionGenerator(BitmapFactory factory)
- {
- this.factory = factory;
- }
-
- @Override
- public SampleElements<Integer> samples()
- {
- return new SampleElements.Ints();
- }
-
- @Override
- public BitmapCollection create(Object... objects)
- {
- MutableBitmap mutableBitmap = factory.makeEmptyMutableBitmap();
- for (Object element : objects) {
- mutableBitmap.add(((Integer) element));
- }
- return new BitmapCollection(factory.makeImmutableBitmap(mutableBitmap), objects.length);
- }
-
- @Override
- public Integer[] createArray(int n)
- {
- return new Integer[n];
- }
-
- @Override
- public Iterable<Integer> order(List<Integer> list)
- {
- Collections.sort(list);
- return list;
+ return bitmap.size();
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/collections/bitmap/WrappedRoaringBitmapTest.java b/processing/src/test/java/org/apache/druid/collections/bitmap/WrappedRoaringBitmapTest.java
index 059ff91de03..2459b67779f 100644
--- a/processing/src/test/java/org/apache/druid/collections/bitmap/WrappedRoaringBitmapTest.java
+++ b/processing/src/test/java/org/apache/druid/collections/bitmap/WrappedRoaringBitmapTest.java
@@ -19,18 +19,20 @@
package org.apache.druid.collections.bitmap;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.MethodSource;
import org.roaringbitmap.IntIterator;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
-@RunWith(Parameterized.class)
+@ParameterizedClass
+
+@MethodSource("constructorFeeder")
public class WrappedRoaringBitmapTest
{
private static final int[] DATA = new int[]{1, 3, 5, 7, 9, 10, 11, 100, 122};
@@ -43,7 +45,6 @@ public class WrappedRoaringBitmapTest
this.cardinality = cardinality;
}
- @Parameterized.Parameters
public static List<Object[]> constructorFeeder()
{
final List<Object[]> constructors = new ArrayList<>();
@@ -53,7 +54,7 @@ public class WrappedRoaringBitmapTest
return constructors;
}
- @Before
+ @BeforeEach
public void setUp()
{
bitmap = (WrappedRoaringBitmap) RoaringBitmapFactory.INSTANCE.makeEmptyMutableBitmap();
@@ -66,28 +67,28 @@ public class WrappedRoaringBitmapTest
public void testGet()
{
for (int i = 0; i < DATA.length; i++) {
- Assert.assertEquals(String.valueOf(i), i < cardinality, bitmap.get(DATA[i]));
+ Assertions.assertEquals(i < cardinality, bitmap.get(DATA[i]), String.valueOf(i));
}
- Assert.assertFalse(bitmap.get(-1));
- Assert.assertFalse(bitmap.get(Integer.MAX_VALUE));
+ Assertions.assertFalse(bitmap.get(-1));
+ Assertions.assertFalse(bitmap.get(Integer.MAX_VALUE));
}
@Test
public void testSize()
{
- Assert.assertEquals(cardinality, bitmap.size());
+ Assertions.assertEquals(cardinality, bitmap.size());
}
@Test
public void testRemove()
{
bitmap.remove(Integer.MAX_VALUE);
- Assert.assertEquals(cardinality, bitmap.size());
+ Assertions.assertEquals(cardinality, bitmap.size());
if (cardinality > 0) {
bitmap.remove(DATA[0]);
- Assert.assertEquals(cardinality - 1, bitmap.size());
+ Assertions.assertEquals(cardinality - 1, bitmap.size());
}
}
@@ -95,7 +96,7 @@ public class WrappedRoaringBitmapTest
public void testClear()
{
bitmap.clear();
- Assert.assertEquals(0, bitmap.size());
+ Assertions.assertEquals(0, bitmap.size());
}
@Test
@@ -106,10 +107,10 @@ public class WrappedRoaringBitmapTest
int i = 0;
while (iterator.hasNext()) {
final int n = iterator.next();
- Assert.assertEquals(String.valueOf(i), DATA[i], n);
+ Assertions.assertEquals(DATA[i], n, String.valueOf(i));
i++;
}
- Assert.assertEquals("number of elements", i, cardinality);
+ Assertions.assertEquals(i, cardinality, "number of elements");
}
@Test
@@ -120,13 +121,13 @@ public class WrappedRoaringBitmapTest
bitmap.serialize(byteBuffer);
byteBuffer.flip();
ImmutableBitmap immutableBitmap = new RoaringBitmapFactory().mapImmutableBitmap(byteBuffer);
- Assert.assertEquals(cardinality, immutableBitmap.size());
+ Assertions.assertEquals(cardinality, immutableBitmap.size());
}
@Test
public void testToByteArray()
{
ImmutableBitmap immutableBitmap = new RoaringBitmapFactory().mapImmutableBitmap(ByteBuffer.wrap(bitmap.toBytes()));
- Assert.assertEquals(cardinality, immutableBitmap.size());
+ Assertions.assertEquals(cardinality, immutableBitmap.size());
}
}
diff --git a/processing/src/test/java/org/apache/druid/collections/spatial/ImmutableRTreeTest.java b/processing/src/test/java/org/apache/druid/collections/spatial/ImmutableRTreeTest.java
index 6a1228f7a0e..8054c188840 100644
--- a/processing/src/test/java/org/apache/druid/collections/spatial/ImmutableRTreeTest.java
+++ b/processing/src/test/java/org/apache/druid/collections/spatial/ImmutableRTreeTest.java
@@ -24,7 +24,6 @@ import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.primitives.Bytes;
-import junit.framework.Assert;
import org.apache.druid.collections.bitmap.BitmapFactory;
import org.apache.druid.collections.bitmap.ConciseBitmapFactory;
import org.apache.druid.collections.bitmap.ImmutableBitmap;
@@ -35,7 +34,8 @@ import org.apache.druid.collections.spatial.search.RectangularBound;
import org.apache.druid.collections.spatial.split.LinearGutmanSplitStrategy;
import org.apache.druid.segment.data.GenericIndexed;
import org.apache.druid.segment.data.ImmutableRTreeObjectStrategy;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import org.roaringbitmap.IntIterator;
import java.nio.ByteBuffer;
@@ -70,11 +70,11 @@ public class ImmutableRTreeTest
ImmutableRTree secondTree = new ImmutableRTree(buffer, bf);
Iterable<ImmutableBitmap> points = secondTree.search(new RadiusBound(new float[]{0, 0}, 10));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -96,12 +96,12 @@ public class ImmutableRTreeTest
Iterable<ImmutableBitmap> points = secondTree.search(new RadiusBound(new float[]{0, 0}, 10));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -121,17 +121,17 @@ public class ImmutableRTreeTest
tree.insert(new float[]{-4, -3}, 5);
tree.insert(new float[]{119, -78}, 50);
- Assert.assertEquals(tree.getRoot().getChildren().size(), 10);
+ Assertions.assertEquals(tree.getRoot().getChildren().size(), 10);
ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{0, 0}, 5));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -151,17 +151,17 @@ public class ImmutableRTreeTest
tree.insert(new float[]{-4, -3}, 5);
tree.insert(new float[]{119, -78}, 50);
- Assert.assertEquals(tree.getRoot().getChildren().size(), 10);
+ Assertions.assertEquals(tree.getRoot().getChildren().size(), 10);
ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{0, 0}, 5));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -187,12 +187,12 @@ public class ImmutableRTreeTest
ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{0, 0}, 5));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -218,12 +218,12 @@ public class ImmutableRTreeTest
ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{0, 0}, 5));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -255,12 +255,12 @@ public class ImmutableRTreeTest
)
);
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(0, 1, 2, 3, 4);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -291,12 +291,12 @@ public class ImmutableRTreeTest
)
);
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(0, 1, 2, 3, 4);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -324,12 +324,12 @@ public class ImmutableRTreeTest
new RadiusBound(new float[]{0.0f, 0.0f}, 5)
);
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 3);
+ Assertions.assertTrue(finalSet.size() >= 3);
Set<Integer> expected = Sets.newHashSet(0, 1, 2);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -357,12 +357,12 @@ public class ImmutableRTreeTest
new RadiusBound(new float[]{0.0f, 0.0f}, 5)
);
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 3);
+ Assertions.assertTrue(finalSet.size() >= 3);
Set<Integer> expected = Sets.newHashSet(0, 1, 2);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -400,7 +400,7 @@ public class ImmutableRTreeTest
new float[]{1.0f, 2.0f, 2.0f, 3.0f, 3.0f, 1.0f}
));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() == 500);
+ Assertions.assertTrue(finalSet.size() == 500);
Set<Integer> expected = new HashSet<>();
for (int i = 0; i < 500; i++) {
@@ -408,7 +408,7 @@ public class ImmutableRTreeTest
}
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -446,7 +446,7 @@ public class ImmutableRTreeTest
new float[]{1.0f, 2.0f, 2.0f, 3.0f, 3.0f, 1.0f}
));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() == 500);
+ Assertions.assertTrue(finalSet.size() == 500);
Set<Integer> expected = new HashSet<>();
for (int i = 0; i < 500; i++) {
@@ -454,7 +454,7 @@ public class ImmutableRTreeTest
}
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -470,7 +470,7 @@ public class ImmutableRTreeTest
new RadiusBound(new float[]{0.0f, 0.0f}, 5)
);
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertEquals(finalSet.size(), 0);
+ Assertions.assertEquals(finalSet.size(), 0);
}
@Test
@@ -485,8 +485,8 @@ public class ImmutableRTreeTest
new RadiusBound(new float[]{0.0f, 0.0f}, 5)
);
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertEquals(finalSet.size(), 0);
- Assert.assertTrue(finalSet.isEmpty());
+ Assertions.assertEquals(finalSet.size(), 0);
+ Assertions.assertTrue(finalSet.isEmpty());
}
@Test
@@ -511,12 +511,12 @@ public class ImmutableRTreeTest
ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{0, 0}, 5, 2));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -543,12 +543,12 @@ public class ImmutableRTreeTest
ImmutableRTree searchTree = ImmutableRTree.newImmutableFromMutable(tree);
Iterable<ImmutableBitmap> points = searchTree.search(new RadiusBound(new float[]{0, 0}, 5, 2));
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() >= 5);
+ Assertions.assertTrue(finalSet.size() >= 5);
Set<Integer> expected = Sets.newHashSet(1, 2, 3, 4, 5);
IntIterator iter = finalSet.iterator();
while (iter.hasNext()) {
- Assert.assertTrue(expected.contains(iter.next()));
+ Assertions.assertTrue(expected.contains(iter.next()));
}
}
@@ -674,7 +674,7 @@ public class ImmutableRTreeTest
ImmutableRTree deserializedTree = genericIndexed.get(0);
byte[] bytes2 = deserializedTree.toBytes();
- org.junit.Assert.assertEquals(Bytes.asList(bytes1), Bytes.asList(bytes2));
+ org.junit.jupiter.api.Assertions.assertEquals(Bytes.asList(bytes1), Bytes.asList(bytes2));
}
@Test
@@ -699,9 +699,9 @@ public class ImmutableRTreeTest
2,
RadiusBound.RadiusUnit.meters
));
- org.junit.Assert.assertTrue(((FluentIterable) points).toList().size() == 100);
+ org.junit.jupiter.api.Assertions.assertTrue(((FluentIterable) points).toList().size() == 100);
ImmutableBitmap finalSet = bf.union(points);
- Assert.assertTrue(finalSet.size() == 100);
+ Assertions.assertTrue(finalSet.size() == 100);
}
@Test
diff --git a/processing/src/test/java/org/apache/druid/common/guava/FutureUtilsTest.java b/processing/src/test/java/org/apache/druid/common/guava/FutureUtilsTest.java
index 9c261c7935f..f54c7409a9e 100644
--- a/processing/src/test/java/org/apache/druid/common/guava/FutureUtilsTest.java
+++ b/processing/src/test/java/org/apache/druid/common/guava/FutureUtilsTest.java
@@ -29,12 +29,12 @@ import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
import org.junit.internal.matchers.ThrowableCauseMatcher;
import org.junit.internal.matchers.ThrowableMessageMatcher;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -52,13 +52,13 @@ public class FutureUtilsTest
{
private ExecutorService exec;
- @Before
+ @BeforeEach
public void setUp()
{
exec = Execs.singleThreaded(StringUtils.encodeForFormat(getClass().getName()) + "-%d");
}
- @After
+ @AfterEach
public void tearDown()
{
if (exec != null) {
@@ -71,13 +71,13 @@ public class FutureUtilsTest
public void test_get_ok() throws Exception
{
final String s = FutureUtils.get(Futures.immediateFuture("x"), true);
- Assert.assertEquals("x", s);
+ Assertions.assertEquals("x", s);
}
@Test
public void test_get_failed()
{
- final ExecutionException e = Assert.assertThrows(
+ final ExecutionException e = Assertions.assertThrows(
ExecutionException.class,
() -> FutureUtils.get(Futures.immediateFailedFuture(new ISE("oh no")), true)
);
@@ -105,13 +105,13 @@ public class FutureUtilsTest
});
runningLatch.await();
- Assert.assertTrue(execResult.cancel(true));
+ Assertions.assertTrue(execResult.cancel(true));
exec.shutdown();
- Assert.assertTrue(exec.awaitTermination(1, TimeUnit.MINUTES));
+ Assertions.assertTrue(exec.awaitTermination(1, TimeUnit.MINUTES));
exec = null;
- Assert.assertTrue(neverGoingToResolve.isCancelled());
+ Assertions.assertTrue(neverGoingToResolve.isCancelled());
final Throwable e = exceptionFromOtherThread.get();
MatcherAssert.assertThat(e, CoreMatchers.instanceOf(RuntimeException.class));
@@ -137,14 +137,14 @@ public class FutureUtilsTest
});
runningLatch.await();
- Assert.assertTrue(execResult.cancel(true));
+ Assertions.assertTrue(execResult.cancel(true));
exec.shutdown();
- Assert.assertTrue(exec.awaitTermination(1, TimeUnit.MINUTES));
+ Assertions.assertTrue(exec.awaitTermination(1, TimeUnit.MINUTES));
exec = null;
- Assert.assertFalse(neverGoingToResolve.isCancelled());
- Assert.assertFalse(neverGoingToResolve.isDone());
+ Assertions.assertFalse(neverGoingToResolve.isCancelled());
+ Assertions.assertFalse(neverGoingToResolve.isDone());
final Throwable e = exceptionFromOtherThread.get();
MatcherAssert.assertThat(e, CoreMatchers.instanceOf(RuntimeException.class));
@@ -155,13 +155,13 @@ public class FutureUtilsTest
public void test_getUnchecked_ok()
{
final String s = FutureUtils.getUnchecked(Futures.immediateFuture("x"), true);
- Assert.assertEquals("x", s);
+ Assertions.assertEquals("x", s);
}
@Test
public void test_getUnchecked_failed()
{
- final RuntimeException e = Assert.assertThrows(
+ final RuntimeException e = Assertions.assertThrows(
RuntimeException.class,
() -> FutureUtils.getUnchecked(Futures.immediateFailedFuture(new ISE("oh no")), true)
);
@@ -174,13 +174,13 @@ public class FutureUtilsTest
public void test_getUncheckedImmediately_ok()
{
final String s = FutureUtils.getUncheckedImmediately(Futures.immediateFuture("x"));
- Assert.assertEquals("x", s);
+ Assertions.assertEquals("x", s);
}
@Test
public void test_getUncheckedImmediately_failed()
{
- final RuntimeException e = Assert.assertThrows(
+ final RuntimeException e = Assertions.assertThrows(
RuntimeException.class,
() -> FutureUtils.getUncheckedImmediately(Futures.immediateFailedFuture(new ISE("oh no")))
);
@@ -192,7 +192,7 @@ public class FutureUtilsTest
@Test
public void test_getUncheckedImmediately_notResolved()
{
- Assert.assertThrows(
+ Assertions.assertThrows(
IllegalStateException.class,
() -> FutureUtils.getUncheckedImmediately(SettableFuture.create())
);
@@ -201,7 +201,7 @@ public class FutureUtilsTest
@Test
public void test_transform() throws Exception
{
- Assert.assertEquals(
+ Assertions.assertEquals(
"xy",
FutureUtils.transform(Futures.immediateFuture("x"), s -> s + "y").get()
);
@@ -217,8 +217,8 @@ public class FutureUtilsTest
}
);
- Assert.assertTrue(future.isDone());
- final ExecutionException e = Assert.assertThrows(
+ Assertions.assertTrue(future.isDone());
+ final ExecutionException e = Assertions.assertThrows(
ExecutionException.class,
future::get
);
@@ -237,7 +237,7 @@ public class FutureUtilsTest
@Test
public void test_transformAsync() throws Exception
{
- Assert.assertEquals(
+ Assertions.assertEquals(
"xy",
FutureUtils.transformAsync(Futures.immediateFuture("x"), s -> Futures.immediateFuture(s + "y")).get()
);
@@ -253,7 +253,7 @@ public class FutureUtilsTest
}
);
- final ExecutionException e = Assert.assertThrows(
+ final ExecutionException e = Assertions.assertThrows(
ExecutionException.class,
f::get
);
@@ -278,7 +278,7 @@ public class FutureUtilsTest
futures.add(Futures.immediateFuture("bar"));
futures.add(Futures.immediateFuture(null));
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(Either.value("foo"), Either.value("bar"), Either.value(null)),
FutureUtils.coalesce(futures).get()
);
@@ -294,7 +294,7 @@ public class FutureUtilsTest
futures.add(Futures.immediateFailedFuture(e));
futures.add(Futures.immediateFuture(null));
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(Either.value("foo"), Either.error(e), Either.value(null)),
FutureUtils.coalesce(futures).get()
);
@@ -310,10 +310,10 @@ public class FutureUtilsTest
futures.add(Futures.immediateFuture(null));
final List<Either<Throwable, String>> results = FutureUtils.coalesce(futures).get();
- Assert.assertEquals(3, results.size());
- Assert.assertEquals(Either.value("foo"), results.get(0));
- Assert.assertTrue(results.get(1).isError());
- Assert.assertEquals(Either.value(null), results.get(2));
+ Assertions.assertEquals(3, results.size());
+ Assertions.assertEquals(Either.value("foo"), results.get(0));
+ Assertions.assertTrue(results.get(1).isError());
+ Assertions.assertEquals(Either.value(null), results.get(2));
MatcherAssert.assertThat(
results.get(1).error(),
@@ -333,7 +333,7 @@ public class FutureUtilsTest
final ListenableFuture<List<Either<Throwable, String>>> coalesced = FutureUtils.coalesce(futures);
- Assert.assertThrows(
+ Assertions.assertThrows(
TimeoutException.class,
() -> coalesced.get(10, TimeUnit.MILLISECONDS)
);
@@ -352,10 +352,10 @@ public class FutureUtilsTest
final ListenableFuture<List<Either<Throwable, String>>> coalesced = FutureUtils.coalesce(futures);
coalesced.cancel(true);
- Assert.assertTrue(coalesced.isCancelled());
+ Assertions.assertTrue(coalesced.isCancelled());
// All input futures are canceled too.
- Assert.assertTrue(unresolvedFuture.isCancelled());
+ Assertions.assertTrue(unresolvedFuture.isCancelled());
}
@Test
@@ -368,8 +368,8 @@ public class FutureUtilsTest
baggageHandled::incrementAndGet
);
future.set(3L);
- Assert.assertEquals(3L, (long) futureWithBaggage.get());
- Assert.assertEquals(1, baggageHandled.get());
+ Assertions.assertEquals(3L, (long) futureWithBaggage.get());
+ Assertions.assertEquals(1, baggageHandled.get());
}
@Test
@@ -383,9 +383,9 @@ public class FutureUtilsTest
);
future.setException(new ISE("error!"));
- final ExecutionException e = Assert.assertThrows(ExecutionException.class, futureWithBaggage::get);
+ final ExecutionException e = Assertions.assertThrows(ExecutionException.class, futureWithBaggage::get);
MatcherAssert.assertThat(e.getCause(), CoreMatchers.instanceOf(IllegalStateException.class));
MatcherAssert.assertThat(e.getCause(), ThrowableMessageMatcher.hasMessage(CoreMatchers.equalTo("error!")));
- Assert.assertEquals(1, baggageHandled.get());
+ Assertions.assertEquals(1, baggageHandled.get());
}
}
diff --git a/processing/src/test/java/org/apache/druid/common/semantic/SemanticCreatorUsageTest.java b/processing/src/test/java/org/apache/druid/common/semantic/SemanticCreatorUsageTest.java
index e5cebcb9c52..0be7e220187 100644
--- a/processing/src/test/java/org/apache/druid/common/semantic/SemanticCreatorUsageTest.java
+++ b/processing/src/test/java/org/apache/druid/common/semantic/SemanticCreatorUsageTest.java
@@ -20,10 +20,9 @@
package org.apache.druid.common.semantic;
import org.apache.druid.java.util.common.StringUtils;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.MethodSource;
import org.reflections.Reflections;
import org.reflections.scanners.MethodAnnotationsScanner;
@@ -34,19 +33,19 @@ import java.util.Comparator;
import java.util.List;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Ensures that the usage of the {@link SemanticCreator} annotations follows some basic rules.
*/
-@RunWith(Parameterized.class)
+@ParameterizedClass
+@MethodSource("getParameters")
public class SemanticCreatorUsageTest
{
private final Method method;
- @Parameters(name = "{0}")
public static List<Object[]> getParameters()
{
List<Object[]> params = new ArrayList<>();
@@ -74,7 +73,7 @@ public class SemanticCreatorUsageTest
public void testPublic()
{
int modifiers = method.getModifiers();
- assertTrue(StringUtils.format("method [%s] is not public", method), Modifier.isPublic(modifiers));
+ assertTrue(Modifier.isPublic(modifiers), StringUtils.format("method [%s] is not public", method));
}
/**
@@ -87,8 +86,8 @@ public class SemanticCreatorUsageTest
{
Class<?> returnType = method.getReturnType();
assertTrue(
- returnType + " is not an interface; this method must return with an interface; ",
- returnType.isInterface()
+ returnType.isInterface(),
+ returnType + " is not an interface; this method must return with an interface; "
);
}
@@ -103,7 +102,7 @@ public class SemanticCreatorUsageTest
Class<?> returnType = method.getReturnType();
String desiredMethodName = "to" + returnType.getSimpleName();
- assertEquals("should be named as " + desiredMethodName, desiredMethodName, method.getName());
+ assertEquals(desiredMethodName, method.getName(), "should be named as " + desiredMethodName);
}
}
diff --git a/processing/src/test/java/org/apache/druid/common/utils/UUIDUtilsTest.java b/processing/src/test/java/org/apache/druid/common/utils/UUIDUtilsTest.java
index 7a3f7fcb387..8185e19c75f 100644
--- a/processing/src/test/java/org/apache/druid/common/utils/UUIDUtilsTest.java
+++ b/processing/src/test/java/org/apache/druid/common/utils/UUIDUtilsTest.java
@@ -25,10 +25,10 @@ import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import org.apache.druid.java.util.common.StringUtils;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.Collection;
@@ -38,10 +38,10 @@ import java.util.UUID;
/**
*
*/
-@RunWith(Parameterized.class)
+@ParameterizedClass
+@MethodSource("constructorFeeder")
public class UUIDUtilsTest
{
- @Parameterized.Parameters
public static Collection<Object[]> constructorFeeder()
{
final ArrayList<String[]> args = new ArrayList<>();
@@ -103,7 +103,7 @@ public class UUIDUtilsTest
strings.add(uuidString.substring(16, 20));
strings.add(uuidString.substring(20, 32));
UUID uuid = UUID.fromString(Joiner.on('-').join(strings));
- Assert.assertEquals(StringUtils.removeChar(uuid.toString(), '-'), uuidString);
+ Assertions.assertEquals(StringUtils.removeChar(uuid.toString(), '-'), uuidString);
}
@Test
diff --git a/processing/src/test/java/org/apache/druid/data/input/impl/CombiningInputSourceTest.java b/processing/src/test/java/org/apache/druid/data/input/impl/CombiningInputSourceTest.java
index 32c8117a9a5..19ac54b6bb6 100644
--- a/processing/src/test/java/org/apache/druid/data/input/impl/CombiningInputSourceTest.java
+++ b/processing/src/test/java/org/apache/druid/data/input/impl/CombiningInputSourceTest.java
@@ -35,10 +35,11 @@ import org.apache.druid.data.input.SplitHintSpec;
import org.apache.druid.java.util.common.HumanReadableBytes;
import org.apache.druid.java.util.common.Pair;
import org.easymock.EasyMock;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import javax.annotation.Nullable;
+
import java.io.File;
import java.io.IOException;
import java.net.URI;
@@ -67,7 +68,7 @@ public class CombiningInputSourceTest
));
final byte[] json = mapper.writeValueAsBytes(combiningInputSource);
final CombiningInputSource fromJson = (CombiningInputSource) mapper.readValue(json, InputSource.class);
- Assert.assertEquals(combiningInputSource, fromJson);
+ Assertions.assertEquals(combiningInputSource, fromJson);
}
@Test
@@ -85,7 +86,7 @@ public class CombiningInputSourceTest
Set<String> expectedTypes = new HashSet<>();
expectedTypes.addAll(fileSource.getTypes());
expectedTypes.addAll(uriInputSource.getTypes());
- Assert.assertEquals(expectedTypes, combiningInputSource.getTypes());
+ Assertions.assertEquals(expectedTypes, combiningInputSource.getTypes());
}
@Test
@@ -106,7 +107,7 @@ public class CombiningInputSourceTest
fileSource,
uriInputSource
));
- Assert.assertEquals(combiningInputSource.estimateNumSplits(
+ Assertions.assertEquals(combiningInputSource.estimateNumSplits(
new NoopInputFormat(),
new MaxSizeSplitHintSpec(
new HumanReadableBytes(5L),
@@ -141,18 +142,18 @@ public class CombiningInputSourceTest
null
)
).collect(Collectors.toList());
- Assert.assertEquals(6, combinedInputSplits.size());
+ Assertions.assertEquals(6, combinedInputSplits.size());
for (int i = 0; i < 3; i++) {
Pair<SplittableInputSource, InputSplit> splitPair = (Pair) combinedInputSplits.get(i).get();
InputSplit<File> fileSplits = splitPair.rhs;
- Assert.assertTrue(splitPair.lhs instanceof TestFileInputSource);
- Assert.assertEquals(5, fileSplits.get().length());
+ Assertions.assertTrue(splitPair.lhs instanceof TestFileInputSource);
+ Assertions.assertEquals(5, fileSplits.get().length());
}
for (int i = 3; i < combinedInputSplits.size(); i++) {
Pair<SplittableInputSource, InputSplit> splitPair = (Pair) combinedInputSplits.get(i).get();
InputSplit<URI> fileSplits = splitPair.rhs;
- Assert.assertTrue(splitPair.lhs instanceof TestUriInputSource);
- Assert.assertEquals(URI.create("http://test.com/http-test" + i), fileSplits.get());
+ Assertions.assertTrue(splitPair.lhs instanceof TestUriInputSource);
+ Assertions.assertEquals(URI.create("http://test.com/http-test" + i), fileSplits.get());
}
}
@@ -170,7 +171,7 @@ public class CombiningInputSourceTest
TestUriInputSource urlInputSourceWithSplit = (TestUriInputSource) combiningInputSource.withSplit(new InputSplit(Pair.of(
uriInputSource,
testUriSplit)));
- Assert.assertEquals(uriInputSource, urlInputSourceWithSplit);
+ Assertions.assertEquals(uriInputSource, urlInputSourceWithSplit);
}
@@ -188,7 +189,7 @@ public class CombiningInputSourceTest
uriInputSource,
fileSource
));
- Assert.assertTrue(combiningInputSource.needsFormat());
+ Assertions.assertTrue(combiningInputSource.needsFormat());
}
diff --git a/processing/src/test/java/org/apache/druid/data/input/impl/CsvReaderTest.java b/processing/src/test/java/org/apache/druid/data/input/impl/CsvReaderTest.java
index 6d186df9adf..474805547d0 100644
--- a/processing/src/test/java/org/apache/druid/data/input/impl/CsvReaderTest.java
+++ b/processing/src/test/java/org/apache/druid/data/input/impl/CsvReaderTest.java
@@ -30,8 +30,8 @@ import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.parsers.CloseableIterator;
import org.apache.druid.segment.column.RowSignature;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -147,21 +147,21 @@ public class CsvReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
while (iterator.hasNext()) {
final InputRow row = iterator.next();
- Assert.assertEquals(
+ Assertions.assertEquals(
DateTimes.of(StringUtils.format("2019-01-01T00:00:%02dZ", (numResults + 1) * 10)),
row.getTimestamp()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
StringUtils.format("name_%d", numResults + 1),
Iterables.getOnlyElement(row.getDimension("name"))
);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(Integer.toString((numResults + 1) * 5), Integer.toString(numResults + 1)),
row.getDimension("score")
);
numResults++;
}
- Assert.assertEquals(3, numResults);
+ Assertions.assertEquals(3, numResults);
}
}
@@ -257,8 +257,8 @@ public class CsvReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
final Iterator<InputRow> expectedRowIterator = expectedResults.iterator();
while (iterator.hasNext()) {
- Assert.assertTrue(expectedRowIterator.hasNext());
- Assert.assertEquals(expectedRowIterator.next(), iterator.next());
+ Assertions.assertTrue(expectedRowIterator.hasNext());
+ Assertions.assertEquals(expectedRowIterator.next(), iterator.next());
}
}
}
@@ -373,8 +373,8 @@ public class CsvReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
final Iterator<InputRow> expectedRowIterator = expectedResults.iterator();
while (iterator.hasNext()) {
- Assert.assertTrue(expectedRowIterator.hasNext());
- Assert.assertEquals(expectedRowIterator.next(), iterator.next());
+ Assertions.assertTrue(expectedRowIterator.hasNext());
+ Assertions.assertEquals(expectedRowIterator.next(), iterator.next());
}
}
}
@@ -390,15 +390,15 @@ public class CsvReaderTest
final CsvInputFormat format = new CsvInputFormat(ImmutableList.of("ts", "name", "Comment"), null, null, false, 0, null);
final InputEntityReader reader = format.createReader(INPUT_ROW_SCHEMA, source, null);
try (CloseableIterator<InputRow> iterator = reader.read()) {
- Assert.assertTrue(iterator.hasNext());
+ Assertions.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
- Assert.assertEquals(DateTimes.of("2019-01-01T00:00:10Z"), row.getTimestamp());
- Assert.assertEquals("name_1", Iterables.getOnlyElement(row.getDimension("name")));
- Assert.assertEquals(
+ Assertions.assertEquals(DateTimes.of("2019-01-01T00:00:10Z"), row.getTimestamp());
+ Assertions.assertEquals("name_1", Iterables.getOnlyElement(row.getDimension("name")));
+ Assertions.assertEquals(
"Как говорится: \\\"всё течет, всё изменяется\\\". Украина как всегда обвиняет Россию в собственных проблемах. #ПровокацияКиева",
Iterables.getOnlyElement(row.getDimension("Comment"))
);
- Assert.assertFalse(iterator.hasNext());
+ Assertions.assertFalse(iterator.hasNext());
}
}
@@ -423,32 +423,32 @@ public class CsvReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
while (iterator.hasNext()) {
final InputRow row = iterator.next();
- Assert.assertEquals(
+ Assertions.assertEquals(
DateTimes.of(StringUtils.format("2019-01-01T00:00:%02dZ", (numResults + 1) * 10)),
row.getTimestamp()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
StringUtils.format("name_%d", numResults + 1),
Iterables.getOnlyElement(row.getDimension("name"))
);
if (format.shouldTryParseNumbers()) {
- Assert.assertEquals(((numResults + 1) * 5L), row.getRaw("score"));
+ Assertions.assertEquals(((numResults + 1) * 5L), row.getRaw("score"));
if (format.getColumns().contains("rating_dbl")) {
- Assert.assertEquals(numResults * 1.0, row.getRaw("rating_dbl"));
+ Assertions.assertEquals(numResults * 1.0, row.getRaw("rating_dbl"));
}
} else {
- Assert.assertEquals(Integer.toString((numResults + 1) * 5), row.getRaw("score"));
+ Assertions.assertEquals(Integer.toString((numResults + 1) * 5), row.getRaw("score"));
if (format.getColumns().contains("rating_dbl")) {
- Assert.assertEquals(Double.toString(numResults * 1.0), row.getRaw("rating_dbl"));
+ Assertions.assertEquals(Double.toString(numResults * 1.0), row.getRaw("rating_dbl"));
}
}
- Assert.assertEquals(
+ Assertions.assertEquals(
Integer.toString((numResults + 1) * 5),
Iterables.getOnlyElement(row.getDimension("score"))
);
numResults++;
}
- Assert.assertEquals(3, numResults);
+ Assertions.assertEquals(3, numResults);
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/data/input/impl/DelimitedReaderTest.java b/processing/src/test/java/org/apache/druid/data/input/impl/DelimitedReaderTest.java
index c04f3a8f3f2..ccf2818f36e 100644
--- a/processing/src/test/java/org/apache/druid/data/input/impl/DelimitedReaderTest.java
+++ b/processing/src/test/java/org/apache/druid/data/input/impl/DelimitedReaderTest.java
@@ -30,8 +30,8 @@ import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.parsers.CloseableIterator;
import org.apache.druid.segment.column.RowSignature;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -163,21 +163,21 @@ public class DelimitedReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
while (iterator.hasNext()) {
final InputRow row = iterator.next();
- Assert.assertEquals(
+ Assertions.assertEquals(
DateTimes.of(StringUtils.format("2019-01-01T00:00:%02dZ", (numResults + 1) * 10)),
row.getTimestamp()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
StringUtils.format("name_%d", numResults + 1),
Iterables.getOnlyElement(row.getDimension("name"))
);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(Integer.toString((numResults + 1) * 5), Integer.toString(numResults + 1)),
row.getDimension("score")
);
numResults++;
}
- Assert.assertEquals(3, numResults);
+ Assertions.assertEquals(3, numResults);
}
}
@@ -292,8 +292,8 @@ public class DelimitedReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
final Iterator<InputRow> expectedRowIterator = expectedResults.iterator();
while (iterator.hasNext()) {
- Assert.assertTrue(expectedRowIterator.hasNext());
- Assert.assertEquals(expectedRowIterator.next(), iterator.next());
+ Assertions.assertTrue(expectedRowIterator.hasNext());
+ Assertions.assertEquals(expectedRowIterator.next(), iterator.next());
}
}
}
@@ -315,21 +315,21 @@ public class DelimitedReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
while (iterator.hasNext()) {
final InputRow row = iterator.next();
- Assert.assertEquals(
+ Assertions.assertEquals(
DateTimes.of(StringUtils.format("2019-01-01T00:00:%02dZ", (numResults + 1) * 10)),
row.getTimestamp()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
StringUtils.format("name_%d", numResults + 1),
Iterables.getOnlyElement(row.getDimension("name"))
);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(Integer.toString((numResults + 1) * 5), Integer.toString(numResults + 1)),
row.getDimension("score")
);
numResults++;
}
- Assert.assertEquals(3, numResults);
+ Assertions.assertEquals(3, numResults);
}
}
@@ -352,15 +352,15 @@ public class DelimitedReaderTest
);
final InputEntityReader reader = format.createReader(INPUT_ROW_SCHEMA, source, null);
try (CloseableIterator<InputRow> iterator = reader.read()) {
- Assert.assertTrue(iterator.hasNext());
+ Assertions.assertTrue(iterator.hasNext());
final InputRow row = iterator.next();
- Assert.assertEquals(DateTimes.of("2019-01-01T00:00:10Z"), row.getTimestamp());
- Assert.assertEquals("name_1", Iterables.getOnlyElement(row.getDimension("name")));
- Assert.assertEquals(
+ Assertions.assertEquals(DateTimes.of("2019-01-01T00:00:10Z"), row.getTimestamp());
+ Assertions.assertEquals("name_1", Iterables.getOnlyElement(row.getDimension("name")));
+ Assertions.assertEquals(
"Как говорится: \\\"всё течет всё изменяется\\\". Украина как всегда обвиняет Россию в собственных проблемах. #ПровокацияКиева",
Iterables.getOnlyElement(row.getDimension("Comment"))
);
- Assert.assertFalse(iterator.hasNext());
+ Assertions.assertFalse(iterator.hasNext());
}
}
@@ -385,32 +385,32 @@ public class DelimitedReaderTest
try (CloseableIterator<InputRow> iterator = reader.read()) {
while (iterator.hasNext()) {
final InputRow row = iterator.next();
- Assert.assertEquals(
+ Assertions.assertEquals(
DateTimes.of(StringUtils.format("2019-01-01T00:00:%02dZ", (numResults + 1) * 10)),
row.getTimestamp()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
StringUtils.format("name_%d", numResults + 1),
Iterables.getOnlyElement(row.getDimension("name"))
);
if (format.shouldTryParseNumbers()) {
- Assert.assertEquals(((numResults + 1) * 5L), row.getRaw("score"));
+ Assertions.assertEquals(((numResults + 1) * 5L), row.getRaw("score"));
if (format.getColumns().contains("rating_dbl")) {
- Assert.assertEquals(numResults * 1.0, row.getRaw("rating_dbl"));
+ Assertions.assertEquals(numResults * 1.0, row.getRaw("rating_dbl"));
}
} else {
- Assert.assertEquals(Integer.toString((numResults + 1) * 5), row.getRaw("score"));
+ Assertions.assertEquals(Integer.toString((numResults + 1) * 5), row.getRaw("score"));
if (format.getColumns().contains("rating_dbl")) {
- Assert.assertEquals(Double.toString(numResults * 1.0), row.getRaw("rating_dbl"));
+ Assertions.assertEquals(Double.toString(numResults * 1.0), row.getRaw("rating_dbl"));
}
}
- Assert.assertEquals(
+ Assertions.assertEquals(
Integer.toString((numResults + 1) * 5),
Iterables.getOnlyElement(row.getDimension("score"))
);
numResults++;
}
- Assert.assertEquals(3, numResults);
+ Assertions.assertEquals(3, numResults);
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/data/input/impl/JsonNodeReaderTest.java b/processing/src/test/java/org/apache/druid/data/input/impl/JsonNodeReaderTest.java
index 50c372ff3d6..83d9c6a294a 100644
--- a/processing/src/test/java/org/apache/druid/data/input/impl/JsonNodeReaderTest.java
+++ b/processing/src/test/java/org/apache/druid/data/input/impl/JsonNodeReaderTest.java
@@ -33,18 +33,13 @@ import org.apache.druid.java.util.common.parsers.JSONPathFieldSpec;
import org.apache.druid.java.util.common.parsers.JSONPathFieldType;
import org.apache.druid.java.util.common.parsers.JSONPathSpec;
import org.apache.druid.java.util.common.parsers.ParseException;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
public class JsonNodeReaderTest
{
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
public void testParseMultipleRows() throws IOException
{
@@ -91,19 +86,19 @@ public class JsonNodeReaderTest
final InputRow row = iterator.next();
final String msgId = String.valueOf(++numActualIterations);
- Assert.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
- Assert.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
-
- Assert.assertTrue(row.getDimension("root_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("path_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("jq_omg2").isEmpty());
+ Assertions.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
+ Assertions.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
+
+ Assertions.assertTrue(row.getDimension("root_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("path_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("jq_omg2").isEmpty());
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
@@ -158,21 +153,21 @@ public class JsonNodeReaderTest
final InputRow row = iterator.next();
- Assert.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
- Assert.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
- Assert.assertEquals("1", Iterables.getOnlyElement(row.getDimension("path_omg")));
- Assert.assertEquals("1", Iterables.getOnlyElement(row.getDimension("jq_omg")));
+ Assertions.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
+ Assertions.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
+ Assertions.assertEquals("1", Iterables.getOnlyElement(row.getDimension("path_omg")));
+ Assertions.assertEquals("1", Iterables.getOnlyElement(row.getDimension("jq_omg")));
- Assert.assertTrue(row.getDimension("root_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("path_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("jq_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("root_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("path_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("jq_omg2").isEmpty());
numActualIterations++;
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
@@ -215,21 +210,23 @@ public class JsonNodeReaderTest
null
);
- //expect a ParseException on the following `next` call on iterator
- expectedException.expect(ParseException.class);
-
// the 2nd line is ill-formed, so the parse of this text chunk aborts
final int numExpectedIterations = 0;
- try (CloseableIterator<InputRow> iterator = reader.read()) {
- int numActualIterations = 0;
- while (iterator.hasNext()) {
- iterator.next();
- ++numActualIterations;
- }
-
- Assert.assertEquals(numExpectedIterations, numActualIterations);
- }
+ Assertions.assertThrows(
+ ParseException.class,
+ () -> {
+ try (CloseableIterator<InputRow> iterator = reader.read()) {
+ int numActualIterations = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ ++numActualIterations;
+ }
+
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
+ }
+ }
+ );
}
@Test
@@ -277,25 +274,25 @@ public class JsonNodeReaderTest
final InputRowListPlusRawValues rawValues = iterator.next();
// 1 row returned 3 times
- Assert.assertEquals(1, rawValues.getInputRows().size());
+ Assertions.assertEquals(1, rawValues.getInputRows().size());
InputRow row = rawValues.getInputRows().get(0);
final String msgId = String.valueOf(++acturalRowCount);
- Assert.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
- Assert.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
+ Assertions.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
+ Assertions.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
- Assert.assertTrue(row.getDimension("root_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("path_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("jq_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("root_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("path_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("jq_omg2").isEmpty());
}
}
- Assert.assertEquals(3, acturalRowCount);
+ Assertions.assertEquals(3, acturalRowCount);
}
@Test
@@ -353,11 +350,11 @@ public class JsonNodeReaderTest
final InputRowListPlusRawValues rawValues = iterator.next();
if (numActualIterations == 2 || numActualIterations == 3) {
- Assert.assertNotNull(rawValues.getParseException());
+ Assertions.assertNotNull(rawValues.getParseException());
}
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
@@ -400,21 +397,23 @@ public class JsonNodeReaderTest
null
);
- //expect a ParseException on the following `next` call on iterator
- expectedException.expect(ParseException.class);
-
// the 2nd line is ill-formed, so the parse of this text chunk aborts
final int numExpectedIterations = 0;
- try (CloseableIterator<InputRow> iterator = reader.read()) {
- int numActualIterations = 0;
- while (iterator.hasNext()) {
- iterator.next();
- ++numActualIterations;
- }
-
- Assert.assertEquals(numExpectedIterations, numActualIterations);
- }
+ Assertions.assertThrows(
+ ParseException.class,
+ () -> {
+ try (CloseableIterator<InputRow> iterator = reader.read()) {
+ int numActualIterations = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ ++numActualIterations;
+ }
+
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
+ }
+ }
+ );
}
@@ -466,10 +465,10 @@ public class JsonNodeReaderTest
final InputRowListPlusRawValues rawValues = iterator.next();
- Assert.assertNotNull(rawValues.getParseException());
+ Assertions.assertNotNull(rawValues.getParseException());
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/data/input/impl/JsonReaderTest.java b/processing/src/test/java/org/apache/druid/data/input/impl/JsonReaderTest.java
index 2a6e204e900..aa781ffd65a 100644
--- a/processing/src/test/java/org/apache/druid/data/input/impl/JsonReaderTest.java
+++ b/processing/src/test/java/org/apache/druid/data/input/impl/JsonReaderTest.java
@@ -33,10 +33,8 @@ import org.apache.druid.java.util.common.parsers.JSONPathFieldSpec;
import org.apache.druid.java.util.common.parsers.JSONPathFieldType;
import org.apache.druid.java.util.common.parsers.JSONPathSpec;
import org.apache.druid.java.util.common.parsers.ParseException;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
@@ -44,9 +42,6 @@ import java.util.Collections;
public class JsonReaderTest
{
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
public void testParseMultipleRows() throws IOException
{
@@ -97,23 +92,23 @@ public class JsonReaderTest
final InputRow row = iterator.next();
final String msgId = String.valueOf(++numActualIterations);
- Assert.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
- Assert.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("tree_baz")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("tree_omg")));
-
- Assert.assertTrue(row.getDimension("root_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("tree_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("path_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("jq_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("tree_omg2").isEmpty());
+ Assertions.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
+ Assertions.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("tree_baz")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("tree_omg")));
+
+ Assertions.assertTrue(row.getDimension("root_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("tree_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("path_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("jq_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("tree_omg2").isEmpty());
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
@@ -172,25 +167,25 @@ public class JsonReaderTest
final InputRow row = iterator.next();
- Assert.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
- Assert.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("tree_baz")));
- Assert.assertEquals("1", Iterables.getOnlyElement(row.getDimension("path_omg")));
- Assert.assertEquals("1", Iterables.getOnlyElement(row.getDimension("jq_omg")));
- Assert.assertEquals("1", Iterables.getOnlyElement(row.getDimension("tree_omg")));
-
- Assert.assertTrue(row.getDimension("root_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("tree_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("path_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("jq_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("tree_omg2").isEmpty());
+ Assertions.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
+ Assertions.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("tree_baz")));
+ Assertions.assertEquals("1", Iterables.getOnlyElement(row.getDimension("path_omg")));
+ Assertions.assertEquals("1", Iterables.getOnlyElement(row.getDimension("jq_omg")));
+ Assertions.assertEquals("1", Iterables.getOnlyElement(row.getDimension("tree_omg")));
+
+ Assertions.assertTrue(row.getDimension("root_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("tree_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("path_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("jq_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("tree_omg2").isEmpty());
numActualIterations++;
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
@@ -237,21 +232,23 @@ public class JsonReaderTest
null
);
- //expect a ParseException on the following `next` call on iterator
- expectedException.expect(ParseException.class);
-
// the 2nd line is ill-formed, so the parse of this text chunk aborts
final int numExpectedIterations = 0;
- try (CloseableIterator<InputRow> iterator = reader.read()) {
- int numActualIterations = 0;
- while (iterator.hasNext()) {
- iterator.next();
- ++numActualIterations;
- }
-
- Assert.assertEquals(numExpectedIterations, numActualIterations);
- }
+ Assertions.assertThrows(
+ ParseException.class,
+ () -> {
+ try (CloseableIterator<InputRow> iterator = reader.read()) {
+ int numActualIterations = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ ++numActualIterations;
+ }
+
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
+ }
+ }
+ );
}
@Test
@@ -303,31 +300,31 @@ public class JsonReaderTest
final InputRowListPlusRawValues rawValues = iterator.next();
// 3 rows returned together
- Assert.assertEquals(3, rawValues.getInputRows().size());
+ Assertions.assertEquals(3, rawValues.getInputRows().size());
for (int i = 0; i < 3; i++) {
InputRow row = rawValues.getInputRows().get(i);
final String msgId = String.valueOf(++acturalRowCount);
- Assert.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
- Assert.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
- Assert.assertEquals("4", Iterables.getOnlyElement(row.getDimension("tree_baz")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
- Assert.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("tree_omg")));
-
- Assert.assertTrue(row.getDimension("root_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("tree_baz2").isEmpty());
- Assert.assertTrue(row.getDimension("path_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("jq_omg2").isEmpty());
- Assert.assertTrue(row.getDimension("tree_omg2").isEmpty());
+ Assertions.assertEquals(DateTimes.of("2019-01-01"), row.getTimestamp());
+ Assertions.assertEquals("x", Iterables.getOnlyElement(row.getDimension("foo")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("root_baz")));
+ Assertions.assertEquals("4", Iterables.getOnlyElement(row.getDimension("tree_baz")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("path_omg")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("jq_omg")));
+ Assertions.assertEquals(msgId, Iterables.getOnlyElement(row.getDimension("tree_omg")));
+
+ Assertions.assertTrue(row.getDimension("root_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("tree_baz2").isEmpty());
+ Assertions.assertTrue(row.getDimension("path_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("jq_omg2").isEmpty());
+ Assertions.assertTrue(row.getDimension("tree_omg2").isEmpty());
}
}
}
- Assert.assertEquals(3, acturalRowCount);
+ Assertions.assertEquals(3, acturalRowCount);
}
@Test
@@ -385,10 +382,10 @@ public class JsonReaderTest
final InputRowListPlusRawValues rawValues = iterator.next();
- Assert.assertNotNull(rawValues.getParseException());
+ Assertions.assertNotNull(rawValues.getParseException());
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
@@ -435,21 +432,23 @@ public class JsonReaderTest
null
);
- //expect a ParseException on the following `next` call on iterator
- expectedException.expect(ParseException.class);
-
// the 2nd line is ill-formed, so the parse of this text chunk aborts
final int numExpectedIterations = 0;
- try (CloseableIterator<InputRow> iterator = reader.read()) {
- int numActualIterations = 0;
- while (iterator.hasNext()) {
- iterator.next();
- ++numActualIterations;
- }
-
- Assert.assertEquals(numExpectedIterations, numActualIterations);
- }
+ Assertions.assertThrows(
+ ParseException.class,
+ () -> {
+ try (CloseableIterator<InputRow> iterator = reader.read()) {
+ int numActualIterations = 0;
+ while (iterator.hasNext()) {
+ iterator.next();
+ ++numActualIterations;
+ }
+
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
+ }
+ }
+ );
}
@@ -505,10 +504,10 @@ public class JsonReaderTest
final InputRowListPlusRawValues rawValues = iterator.next();
- Assert.assertNotNull(rawValues.getParseException());
+ Assertions.assertNotNull(rawValues.getParseException());
}
- Assert.assertEquals(numExpectedIterations, numActualIterations);
+ Assertions.assertEquals(numExpectedIterations, numActualIterations);
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/data/input/impl/RetryingInputStreamTest.java b/processing/src/test/java/org/apache/druid/data/input/impl/RetryingInputStreamTest.java
index a4855b91d58..52decf71376 100644
--- a/processing/src/test/java/org/apache/druid/data/input/impl/RetryingInputStreamTest.java
+++ b/processing/src/test/java/org/apache/druid/data/input/impl/RetryingInputStreamTest.java
@@ -34,6 +34,7 @@ import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import javax.annotation.Nonnull;
+
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
diff --git a/processing/src/test/java/org/apache/druid/data/input/impl/RowsTest.java b/processing/src/test/java/org/apache/druid/data/input/impl/RowsTest.java
index 9d6671089e2..b18f4e162c1 100644
--- a/processing/src/test/java/org/apache/druid/data/input/impl/RowsTest.java
+++ b/processing/src/test/java/org/apache/druid/data/input/impl/RowsTest.java
@@ -30,10 +30,10 @@ import org.apache.druid.segment.column.ValueType;
import org.apache.druid.testing.InitializedNullHandlingTest;
import org.hamcrest.CoreMatchers;
import org.hamcrest.MatcherAssert;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
import org.junit.internal.matchers.ThrowableMessageMatcher;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -51,7 +51,7 @@ public class RowsTest extends InitializedNullHandlingTest
private final Map<Object, Number> validCases = new LinkedHashMap<>();
private final List<Object> invalidCases = new ArrayList<>();
- @Before
+ @BeforeEach
public void setUp()
{
// Null
@@ -107,23 +107,24 @@ public class RowsTest extends InitializedNullHandlingTest
public void test_objectToNumber_typeUnknown_noThrow()
{
for (final Map.Entry<Object, Number> entry : validCases.entrySet()) {
- Assert.assertEquals(
+ Assertions.assertEquals(
+ entry.getValue(),
+ Rows.objectToNumber(FIELD_NAME, entry.getKey(), null, false),
StringUtils.format(
"%s (%s)",
entry.getKey(),
entry.getKey() == null ? null : entry.getKey().getClass().getSimpleName()
- ),
- entry.getValue(), Rows.objectToNumber(FIELD_NAME, entry.getKey(), null, false)
+ )
);
}
for (final Object o : invalidCases) {
- Assert.assertNull(o + " (nothrow)", Rows.objectToNumber(FIELD_NAME, o, null, false));
+ Assertions.assertNull(Rows.objectToNumber(FIELD_NAME, o, null, false), o + " (nothrow)");
- final ParseException e = Assert.assertThrows(
- o + " (throw)",
+ final ParseException e = Assertions.assertThrows(
ParseException.class,
- () -> Rows.objectToNumber(FIELD_NAME, o, null, true)
+ () -> Rows.objectToNumber(FIELD_NAME, o, null, true),
+ o + " (throw)"
);
MatcherAssert.assertThat(
@@ -137,24 +138,24 @@ public class RowsTest extends InitializedNullHandlingTest
public void test_objectToNumber_typeLong_noThrow()
{
for (final Map.Entry<Object, Number> entry : validCases.entrySet()) {
- Assert.assertEquals(
+ Assertions.assertEquals(
+ entry.getValue() != null ? entry.getValue().longValue() : null,
+ Rows.objectToNumber(FIELD_NAME, entry.getKey(), ValueType.LONG, false),
StringUtils.format(
"%s (%s)",
entry.getKey(),
entry.getKey() == null ? null : entry.getKey().getClass().getSimpleName()
- ),
- entry.getValue() != null ? entry.getValue().longValue() : null,
- Rows.objectToNumber(FIELD_NAME, entry.getKey(), ValueType.LONG, false)
+ )
);
}
for (final Object o : invalidCases) {
- Assert.assertNull(o + " (nothrow)", Rows.objectToNumber(FIELD_NAME, o, ValueType.LONG, false));
+ Assertions.assertNull(Rows.objectToNumber(FIELD_NAME, o, ValueType.LONG, false), o + " (nothrow)");
- final ParseException e = Assert.assertThrows(
- o + " (throw)",
+ final ParseException e = Assertions.assertThrows(
ParseException.class,
- () -> Rows.objectToNumber(FIELD_NAME, o, ValueType.LONG, true)
+ () -> Rows.objectToNumber(FIELD_NAME, o, ValueType.LONG, true),
+ o + " (throw)"
);
MatcherAssert.assertThat(
@@ -168,24 +169,24 @@ public class RowsTest extends InitializedNullHandlingTest
public void test_objectToNumber_typeFloat_noThrow()
{
for (final Map.Entry<Object, Number> entry : validCases.entrySet()) {
- Assert.assertEquals(
+ Assertions.assertEquals(
+ entry.getValue() != null ? entry.getValue().floatValue() : null,
+ Rows.objectToNumber(FIELD_NAME, entry.getKey(), ValueType.FLOAT, false),
StringUtils.format(
"%s (%s)",
entry.getKey(),
entry.getKey() == null ? null : entry.getKey().getClass().getSimpleName()
- ),
- entry.getValue() != null ? entry.getValue().floatValue() : null,
- Rows.objectToNumber(FIELD_NAME, entry.getKey(), ValueType.FLOAT, false)
+ )
);
}
for (final Object o : invalidCases) {
- Assert.assertNull(o + " (nothrow)", Rows.objectToNumber(FIELD_NAME, o, ValueType.FLOAT, false));
+ Assertions.assertNull(Rows.objectToNumber(FIELD_NAME, o, ValueType.FLOAT, false), o + " (nothrow)");
- final ParseException e = Assert.assertThrows(
- o + " (throw)",
+ final ParseException e = Assertions.assertThrows(
ParseException.class,
- () -> Rows.objectToNumber(FIELD_NAME, o, ValueType.FLOAT, true)
+ () -> Rows.objectToNumber(FIELD_NAME, o, ValueType.FLOAT, true),
+ o + " (throw)"
);
MatcherAssert.assertThat(
@@ -199,24 +200,24 @@ public class RowsTest extends InitializedNullHandlingTest
public void test_objectToNumber_typeDouble_noThrow()
{
for (final Map.Entry<Object, Number> entry : validCases.entrySet()) {
- Assert.assertEquals(
+ Assertions.assertEquals(
+ entry.getValue() != null ? entry.getValue().doubleValue() : null,
+ Rows.objectToNumber(FIELD_NAME, entry.getKey(), ValueType.DOUBLE, false),
StringUtils.format(
"%s (%s)",
entry.getKey(),
entry.getKey() == null ? null : entry.getKey().getClass().getSimpleName()
- ),
- entry.getValue() != null ? entry.getValue().doubleValue() : null,
- Rows.objectToNumber(FIELD_NAME, entry.getKey(), ValueType.DOUBLE, false)
+ )
);
}
for (final Object o : invalidCases) {
- Assert.assertNull(o + " (nothrow)", Rows.objectToNumber(FIELD_NAME, o, ValueType.DOUBLE, false));
+ Assertions.assertNull(Rows.objectToNumber(FIELD_NAME, o, ValueType.DOUBLE, false), o + " (nothrow)");
- final ParseException e = Assert.assertThrows(
- o + " (throw)",
+ final ParseException e = Assertions.assertThrows(
ParseException.class,
- () -> Rows.objectToNumber(FIELD_NAME, o, ValueType.DOUBLE, true)
+ () -> Rows.objectToNumber(FIELD_NAME, o, ValueType.DOUBLE, true),
+ o + " (throw)"
);
MatcherAssert.assertThat(
@@ -230,19 +231,19 @@ public class RowsTest extends InitializedNullHandlingTest
public void test_objectToStrings_nullInput()
{
// Null input should return empty list
- Assert.assertEquals(Collections.emptyList(), Rows.objectToStrings(null));
+ Assertions.assertEquals(Collections.emptyList(), Rows.objectToStrings(null));
}
@Test
public void test_objectToStrings_singleString()
{
- Assert.assertEquals(Collections.singletonList("foo"), Rows.objectToStrings("foo"));
+ Assertions.assertEquals(Collections.singletonList("foo"), Rows.objectToStrings("foo"));
}
@Test
public void test_objectToStrings_listWithStrings()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
Arrays.asList("a", "b", "c"),
Rows.objectToStrings(Arrays.asList("a", "b", "c"))
);
@@ -253,30 +254,30 @@ public class RowsTest extends InitializedNullHandlingTest
{
// After the fix, null values in lists are preserved as actual null, not converted to "null" string
List<String> result = Rows.objectToStrings(Arrays.asList("a", null, "b"));
- Assert.assertEquals(3, result.size());
- Assert.assertEquals("a", result.get(0));
- Assert.assertNull(result.get(1));
- Assert.assertEquals("b", result.get(2));
+ Assertions.assertEquals(3, result.size());
+ Assertions.assertEquals("a", result.get(0));
+ Assertions.assertNull(result.get(1));
+ Assertions.assertEquals("b", result.get(2));
}
@Test
public void test_objectToStrings_listWithOnlyNull()
{
List<String> result = Rows.objectToStrings(Collections.singletonList(null));
- Assert.assertEquals(1, result.size());
- Assert.assertNull(result.get(0));
+ Assertions.assertEquals(1, result.size());
+ Assertions.assertNull(result.get(0));
}
@Test
public void test_objectToStrings_listWithMultipleNulls()
{
List<String> result = Rows.objectToStrings(Arrays.asList(null, "a", null, "b", null));
- Assert.assertEquals(5, result.size());
- Assert.assertNull(result.get(0));
- Assert.assertEquals("a", result.get(1));
- Assert.assertNull(result.get(2));
- Assert.assertEquals("b", result.get(3));
- Assert.assertNull(result.get(4));
+ Assertions.assertEquals(5, result.size());
+ Assertions.assertNull(result.get(0));
+ Assertions.assertEquals("a", result.get(1));
+ Assertions.assertNull(result.get(2));
+ Assertions.assertEquals("b", result.get(3));
+ Assertions.assertNull(result.get(4));
}
@Test
@@ -284,17 +285,17 @@ public class RowsTest extends InitializedNullHandlingTest
{
// Arrays should also preserve null values
List<String> result = Rows.objectToStrings(new Object[]{"a", null, "b"});
- Assert.assertEquals(3, result.size());
- Assert.assertEquals("a", result.get(0));
- Assert.assertNull(result.get(1));
- Assert.assertEquals("b", result.get(2));
+ Assertions.assertEquals(3, result.size());
+ Assertions.assertEquals("a", result.get(0));
+ Assertions.assertNull(result.get(1));
+ Assertions.assertEquals("b", result.get(2));
}
@Test
public void test_objectToStrings_numberConversion()
{
- Assert.assertEquals(Collections.singletonList("123"), Rows.objectToStrings(123));
- Assert.assertEquals(Collections.singletonList("123.45"), Rows.objectToStrings(123.45));
+ Assertions.assertEquals(Collections.singletonList("123"), Rows.objectToStrings(123));
+ Assertions.assertEquals(Collections.singletonList("123.45"), Rows.objectToStrings(123.45));
}
@Test
@@ -302,8 +303,8 @@ public class RowsTest extends InitializedNullHandlingTest
{
byte[] bytes = new byte[]{1, 2, 3};
List<String> result = Rows.objectToStrings(bytes);
- Assert.assertEquals(1, result.size());
- Assert.assertEquals(StringUtils.encodeBase64String(bytes), result.get(0));
+ Assertions.assertEquals(1, result.size());
+ Assertions.assertEquals(StringUtils.encodeBase64String(bytes), result.get(0));
}
@Test
@@ -321,12 +322,12 @@ public class RowsTest extends InitializedNullHandlingTest
);
List<Object> groupKey = Rows.toGroupKey(timestamp, inputRow);
- Assert.assertEquals(2, groupKey.size());
- Assert.assertEquals(timestamp, groupKey.get(0));
+ Assertions.assertEquals(2, groupKey.size());
+ Assertions.assertEquals(timestamp, groupKey.get(0));
@SuppressWarnings("unchecked")
Map<String, Set<String>> dimensions = (Map<String, Set<String>>) groupKey.get(1);
- Assert.assertNotNull(dimensions);
+ Assertions.assertNotNull(dimensions);
}
@Test
@@ -345,18 +346,18 @@ public class RowsTest extends InitializedNullHandlingTest
// This should not throw NPE after the fix
List<Object> groupKey = Rows.toGroupKey(timestamp, inputRow);
- Assert.assertEquals(2, groupKey.size());
- Assert.assertEquals(timestamp, groupKey.get(0));
+ Assertions.assertEquals(2, groupKey.size());
+ Assertions.assertEquals(timestamp, groupKey.get(0));
@SuppressWarnings("unchecked")
Map<String, Set<String>> dimensions = (Map<String, Set<String>>) groupKey.get(1);
Set<String> dim1Values = dimensions.get("dim1");
// The set should contain null, "a", "b" (with null sorted first due to naturalNullsFirst comparator)
- Assert.assertEquals(3, dim1Values.size());
- Assert.assertTrue(dim1Values.contains(null));
- Assert.assertTrue(dim1Values.contains("a"));
- Assert.assertTrue(dim1Values.contains("b"));
+ Assertions.assertEquals(3, dim1Values.size());
+ Assertions.assertTrue(dim1Values.contains(null));
+ Assertions.assertTrue(dim1Values.contains("a"));
+ Assertions.assertTrue(dim1Values.contains("b"));
}
@Test
@@ -373,14 +374,14 @@ public class RowsTest extends InitializedNullHandlingTest
);
List<Object> groupKey = Rows.toGroupKey(timestamp, inputRow);
- Assert.assertEquals(2, groupKey.size());
+ Assertions.assertEquals(2, groupKey.size());
@SuppressWarnings("unchecked")
Map<String, Set<String>> dimensions = (Map<String, Set<String>>) groupKey.get(1);
Set<String> dim1Values = dimensions.get("dim1");
- Assert.assertEquals(1, dim1Values.size());
- Assert.assertTrue(dim1Values.contains(null));
+ Assertions.assertEquals(1, dim1Values.size());
+ Assertions.assertTrue(dim1Values.contains(null));
}
@Test
@@ -405,11 +406,11 @@ public class RowsTest extends InitializedNullHandlingTest
// Convert to list to check ordering
List<String> valuesList = new ArrayList<>(dim1Values);
- Assert.assertEquals(4, valuesList.size());
+ Assertions.assertEquals(4, valuesList.size());
// Null should be first due to naturalNullsFirst comparator
- Assert.assertNull(valuesList.get(0));
- Assert.assertEquals("a", valuesList.get(1));
- Assert.assertEquals("b", valuesList.get(2));
- Assert.assertEquals("c", valuesList.get(3));
+ Assertions.assertNull(valuesList.get(0));
+ Assertions.assertEquals("a", valuesList.get(1));
+ Assertions.assertEquals("b", valuesList.get(2));
+ Assertions.assertEquals("c", valuesList.get(3));
}
}
diff --git a/processing/src/test/java/org/apache/druid/guice/ConditionalMultibindTest.java b/processing/src/test/java/org/apache/druid/guice/ConditionalMultibindTest.java
index 7343e2879b1..612c4c5d272 100644
--- a/processing/src/test/java/org/apache/druid/guice/ConditionalMultibindTest.java
+++ b/processing/src/test/java/org/apache/druid/guice/ConditionalMultibindTest.java
@@ -29,9 +29,9 @@ import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.TypeLiteral;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -50,7 +50,7 @@ public class ConditionalMultibindTest
private Properties props;
- @Before
+ @BeforeEach
public void setUp()
{
props = new Properties();
@@ -74,8 +74,8 @@ public class ConditionalMultibindTest
Set<Animal> animalSet = injector.getInstance(Key.get(new TypeLiteral<>() {}));
- Assert.assertEquals(1, animalSet.size());
- Assert.assertEquals(animalSet, ImmutableSet.<Animal>of(new Cat()));
+ Assertions.assertEquals(1, animalSet.size());
+ Assertions.assertEquals(animalSet, ImmutableSet.<Animal>of(new Cat()));
}
@Test
@@ -96,8 +96,8 @@ public class ConditionalMultibindTest
Set<Animal> animalSet = injector.getInstance(Key.get(new TypeLiteral<>() {}));
- Assert.assertEquals(2, animalSet.size());
- Assert.assertEquals(animalSet, ImmutableSet.of(new Cat(), new Dog()));
+ Assertions.assertEquals(2, animalSet.size());
+ Assertions.assertEquals(animalSet, ImmutableSet.of(new Cat(), new Dog()));
}
@Test
@@ -121,8 +121,8 @@ public class ConditionalMultibindTest
Set<Animal> animalSet = injector.getInstance(Key.get(new TypeLiteral<>() {}));
- Assert.assertEquals(2, animalSet.size());
- Assert.assertEquals(animalSet, ImmutableSet.of(new Cat(), new Dog()));
+ Assertions.assertEquals(2, animalSet.size());
+ Assertions.assertEquals(animalSet, ImmutableSet.of(new Cat(), new Dog()));
}
@Test
@@ -155,8 +155,8 @@ public class ConditionalMultibindTest
Set<Animal> animalSet = injector.getInstance(Key.get(new TypeLiteral<>() {}));
- Assert.assertEquals(3, animalSet.size());
- Assert.assertEquals(animalSet, ImmutableSet.of(new Cat(), new Dog(), new Fish()));
+ Assertions.assertEquals(3, animalSet.size());
+ Assertions.assertEquals(animalSet, ImmutableSet.of(new Cat(), new Dog(), new Fish()));
}
@Test
@@ -191,12 +191,12 @@ public class ConditionalMultibindTest
);
Set<Animal> animalSet_1 = injector.getInstance(Key.get(new TypeLiteral<>() {}, SanDiego.class));
- Assert.assertEquals(4, animalSet_1.size());
- Assert.assertEquals(animalSet_1, ImmutableSet.of(new Bird(), new Cat(), new Dog(), new Tiger()));
+ Assertions.assertEquals(4, animalSet_1.size());
+ Assertions.assertEquals(animalSet_1, ImmutableSet.of(new Bird(), new Cat(), new Dog(), new Tiger()));
Set<Animal> animalSet_2 = injector.getInstance(Key.get(new TypeLiteral<>() {}, SanJose.class));
- Assert.assertEquals(1, animalSet_2.size());
- Assert.assertEquals(animalSet_2, ImmutableSet.<Animal>of(new Fish()));
+ Assertions.assertEquals(1, animalSet_2.size());
+ Assertions.assertEquals(animalSet_2, ImmutableSet.<Animal>of(new Fish()));
}
@Test
@@ -231,8 +231,8 @@ public class ConditionalMultibindTest
PetShotAvails shop = new PetShotAvails();
injector.injectMembers(shop);
- Assert.assertEquals(4, shop.animals.size());
- Assert.assertEquals(shop.animals, ImmutableSet.of(new Bird(), new Cat(), new Dog(), new Fish()));
+ Assertions.assertEquals(4, shop.animals.size());
+ Assertions.assertEquals(shop.animals, ImmutableSet.of(new Bird(), new Cat(), new Dog(), new Fish()));
}
@Test
@@ -288,16 +288,16 @@ public class ConditionalMultibindTest
);
Set<Set<Animal>> actualAnimalSet = injector.getInstance(Key.get(new TypeLiteral<>() {}));
- Assert.assertEquals(3, actualAnimalSet.size());
- Assert.assertEquals(ImmutableSet.of(set1, set2, set3), actualAnimalSet);
+ Assertions.assertEquals(3, actualAnimalSet.size());
+ Assertions.assertEquals(ImmutableSet.of(set1, set2, set3), actualAnimalSet);
actualAnimalSet = injector.getInstance(Key.get(new TypeLiteral<>() {}, SanDiego.class));
- Assert.assertEquals(1, actualAnimalSet.size());
- Assert.assertEquals(ImmutableSet.of(union), actualAnimalSet);
+ Assertions.assertEquals(1, actualAnimalSet.size());
+ Assertions.assertEquals(ImmutableSet.of(union), actualAnimalSet);
final Set<Zoo<Animal>> actualZooSet = injector.getInstance(Key.get(new TypeLiteral<>() {}));
- Assert.assertEquals(2, actualZooSet.size());
- Assert.assertEquals(ImmutableSet.of(zoo1, zoo2), actualZooSet);
+ Assertions.assertEquals(2, actualZooSet.size());
+ Assertions.assertEquals(ImmutableSet.of(zoo1, zoo2), actualZooSet);
}
abstract static class Animal
diff --git a/processing/src/test/java/org/apache/druid/guice/DruidSecondaryModuleTest.java b/processing/src/test/java/org/apache/druid/guice/DruidSecondaryModuleTest.java
index 5ea346d88b6..3ab502949b5 100644
--- a/processing/src/test/java/org/apache/druid/guice/DruidSecondaryModuleTest.java
+++ b/processing/src/test/java/org/apache/druid/guice/DruidSecondaryModuleTest.java
@@ -40,12 +40,13 @@ import org.apache.druid.query.rowsandcols.concrete.ColumnBasedFrameRowsAndColumn
import org.apache.druid.query.rowsandcols.concrete.RowBasedFrameRowsAndColumns;
import org.apache.druid.query.rowsandcols.concrete.RowBasedFrameRowsAndColumnsTest;
import org.apache.druid.query.rowsandcols.semantic.WireTransferable;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import javax.annotation.Nullable;
import javax.validation.Validation;
import javax.validation.Validator;
+
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
@@ -70,8 +71,8 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "{\"test\": \"this is an injection test\", \"\": \"nice try\" }";
final ClassWithJacksonInject object = mapper.readValue(json, ClassWithJacksonInject.class);
- Assert.assertEquals("this is an injection test", object.test);
- Assert.assertEquals(PROPERTY_VALUE, object.injected.val);
+ Assertions.assertEquals("this is an injection test", object.test);
+ Assertions.assertEquals(PROPERTY_VALUE, object.injected.val);
}
@Test
@@ -84,8 +85,8 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "{\"test\": \"this is an injection test\" }";
final ClassWithJacksonInject object = mapper.readValue(json, ClassWithJacksonInject.class);
- Assert.assertEquals("this is an injection test", object.test);
- Assert.assertEquals(PROPERTY_VALUE, object.injected.val);
+ Assertions.assertEquals("this is an injection test", object.test);
+ Assertions.assertEquals(PROPERTY_VALUE, object.injected.val);
}
@Test
@@ -98,8 +99,8 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "{\"test\": \"this is an injection test\", \"\": \"nice try\" }";
final ClassWithEmptyProperty object = mapper.readValue(json, ClassWithEmptyProperty.class);
- Assert.assertEquals("this is an injection test", object.test);
- Assert.assertEquals(PROPERTY_VALUE, object.injected.val);
+ Assertions.assertEquals("this is an injection test", object.test);
+ Assertions.assertEquals(PROPERTY_VALUE, object.injected.val);
}
@Test
@@ -129,10 +130,10 @@ public class DruidSecondaryModuleTest
"", new ClassWithJacksonInject("value2", injector.getInstance(InjectedParameter.class)))
);
final String jsonWritten = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
- Assert.assertEquals(json, jsonWritten);
+ Assertions.assertEquals(json, jsonWritten);
final ClassWithMapAndJacksonInject objectRead = mapper.readValue(json, ClassWithMapAndJacksonInject.class);
- Assert.assertEquals(object, objectRead);
- Assert.assertEquals("empty", objectRead.getStringStringMap().get(""));
+ Assertions.assertEquals(object, objectRead);
+ Assertions.assertEquals("empty", objectRead.getStringStringMap().get(""));
}
@Test
@@ -179,10 +180,10 @@ public class DruidSecondaryModuleTest
"", new ClassWithJacksonInject("value2", injector.getInstance(InjectedParameter.class)))
);
final String jsonWritten = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
- Assert.assertEquals(expectedSerializedJson, jsonWritten);
+ Assertions.assertEquals(expectedSerializedJson, jsonWritten);
final ClassWithMapAndJacksonInject objectRead = mapper.readValue(json, ClassWithMapAndJacksonInject.class);
- Assert.assertEquals(object, objectRead);
- Assert.assertEquals("empty", objectRead.getStringStringMap().get(""));
+ Assertions.assertEquals(object, objectRead);
+ Assertions.assertEquals("empty", objectRead.getStringStringMap().get(""));
}
private static class ClassWithJacksonInject
@@ -312,7 +313,7 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "[\"this is\", \"an injection test\"]";
final ClassWithConstructorOfEmptyName object = mapper.readValue(json, ClassWithConstructorOfEmptyName.class);
- Assert.assertEquals(ImmutableList.of("this is", "an injection test"), object.getTest());
+ Assertions.assertEquals(ImmutableList.of("this is", "an injection test"), object.getTest());
}
@Test
@@ -324,7 +325,7 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "[]";
final ClassWithConstructorOfEmptyName object = mapper.readValue(json, ClassWithConstructorOfEmptyName.class);
- Assert.assertEquals(ImmutableList.of(), object.getTest());
+ Assertions.assertEquals(ImmutableList.of(), object.getTest());
}
@Test
@@ -336,7 +337,7 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "[\"this is\", \"an injection test\"]";
final ClassWithFactoryMethodOfEmptyName object = mapper.readValue(json, ClassWithFactoryMethodOfEmptyName.class);
- Assert.assertEquals(ImmutableList.of("this is", "an injection test"), object.getTest());
+ Assertions.assertEquals(ImmutableList.of("this is", "an injection test"), object.getTest());
}
@Test
@@ -348,7 +349,7 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "[]";
final ClassWithFactoryMethodOfEmptyName object = mapper.readValue(json, ClassWithFactoryMethodOfEmptyName.class);
- Assert.assertEquals(ImmutableList.of(), object.getTest());
+ Assertions.assertEquals(ImmutableList.of(), object.getTest());
}
@Test
@@ -361,7 +362,7 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "{}";
final ClassOfEmptyConstructor object = mapper.readValue(json, ClassOfEmptyConstructor.class);
- Assert.assertEquals("empty constructor", object.val);
+ Assertions.assertEquals("empty constructor", object.val);
}
private static class ClassWithConstructorOfEmptyName
@@ -427,10 +428,10 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "{\"val\": \"this is an injection test\", \"valLen\": 5, \"\": \"nice try\" }";
final ClassOfMultipleJsonCreators object = mapper.readValue(json, ClassOfMultipleJsonCreators.class);
- Assert.assertEquals("this is an injection test", object.val);
- Assert.assertEquals(5, object.valLen);
- Assert.assertNotNull(object.injected);
- Assert.assertEquals(PROPERTY_VALUE, object.injected.val);
+ Assertions.assertEquals("this is an injection test", object.val);
+ Assertions.assertEquals(5, object.valLen);
+ Assertions.assertNotNull(object.injected);
+ Assertions.assertEquals(PROPERTY_VALUE, object.injected.val);
}
@Test
@@ -443,9 +444,9 @@ public class DruidSecondaryModuleTest
final ObjectMapper mapper = makeObjectMapper(injector);
final String json = "\"this is an injection test\"";
final ClassOfMultipleJsonCreators object = mapper.readValue(json, ClassOfMultipleJsonCreators.class);
- Assert.assertEquals("this is an injection test", object.val);
- Assert.assertEquals(object.val.length(), object.valLen);
- Assert.assertNull(object.injected);
+ Assertions.assertEquals("this is an injection test", object.val);
+ Assertions.assertEquals(object.val.length(), object.valLen);
+ Assertions.assertNull(object.injected);
}
private static class ClassOfMultipleJsonCreators
@@ -547,7 +548,7 @@ public class DruidSecondaryModuleTest
final byte[] bytes = om.writeValueAsBytes(frc);
final ColumnBasedFrameRowsAndColumns frc2 = (ColumnBasedFrameRowsAndColumns) om.readValue(bytes, RowsAndColumns.class);
- Assert.assertEquals(frc, frc2);
+ Assertions.assertEquals(frc, frc2);
}
@Test
@@ -566,7 +567,7 @@ public class DruidSecondaryModuleTest
final byte[] bytes = om.writeValueAsBytes(frc);
final RowBasedFrameRowsAndColumns frc2 = (RowBasedFrameRowsAndColumns) om.readValue(bytes, RowsAndColumns.class);
- Assert.assertEquals(frc, frc2);
+ Assertions.assertEquals(frc, frc2);
}
@Test
@@ -604,7 +605,7 @@ public class DruidSecondaryModuleTest
bytes,
RowsAndColumns.class
);
- Assert.assertEquals(frc, frc2);
+ Assertions.assertEquals(frc, frc2);
}
@Test
@@ -642,7 +643,7 @@ public class DruidSecondaryModuleTest
bytes,
RowsAndColumns.class
);
- Assert.assertEquals(frc, frc2);
+ Assertions.assertEquals(frc, frc2);
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/guice/ExtensionsLoaderTest.java b/processing/src/test/java/org/apache/druid/guice/ExtensionsLoaderTest.java
index 642a4c44051..7ed12199362 100644
--- a/processing/src/test/java/org/apache/druid/guice/ExtensionsLoaderTest.java
+++ b/processing/src/test/java/org/apache/druid/guice/ExtensionsLoaderTest.java
@@ -29,10 +29,10 @@ import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.RE;
import org.apache.druid.java.util.common.StringUtils;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.apache.druid.testing.TemporaryFolderExtension;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.File;
import java.io.FileOutputStream;
@@ -57,8 +57,8 @@ import java.util.jar.JarOutputStream;
*/
public class ExtensionsLoaderTest
{
- @Rule
- public final TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @RegisterExtension
+ public final TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();
private final ObjectMapper objectMapper = new ObjectMapper();
private final Map<String, byte[]> jarFileContents = ImmutableMap.of(
@@ -78,11 +78,11 @@ public class ExtensionsLoaderTest
public void test02MakeStartupInjector()
{
Injector startupInjector = startupInjector();
- Assert.assertNotNull(startupInjector);
- Assert.assertNotNull(startupInjector.getInstance(ObjectMapper.class));
+ Assertions.assertNotNull(startupInjector);
+ Assertions.assertNotNull(startupInjector.getInstance(ObjectMapper.class));
ExtensionsLoader extnLoader = ExtensionsLoader.instance(startupInjector);
- Assert.assertNotNull(extnLoader);
- Assert.assertSame(extnLoader, ExtensionsLoader.instance(startupInjector));
+ Assertions.assertNotNull(extnLoader);
+ Assertions.assertSame(extnLoader, ExtensionsLoader.instance(startupInjector));
}
@Test
@@ -100,7 +100,7 @@ public class ExtensionsLoaderTest
Set<String> loadedModuleNames = new HashSet<>();
for (DruidModule module : modules) {
- Assert.assertFalse("Duplicate extensions are loaded", loadedModuleNames.contains(module.getClass().getName()));
+ Assertions.assertFalse(loadedModuleNames.contains(module.getClass().getName()), "Duplicate extensions are loaded");
loadedModuleNames.add(module.getClass().getName());
}
}
@@ -123,7 +123,7 @@ public class ExtensionsLoaderTest
final URL[] expectedURLs = new URL[]{a_jar.toURI().toURL(), b_jar.toURI().toURL(), c_jar.toURI().toURL()};
final URL[] actualURLs = loader.getURLs();
Arrays.sort(actualURLs, Comparator.comparing(URL::getPath));
- Assert.assertArrayEquals(expectedURLs, actualURLs);
+ Assertions.assertArrayEquals(expectedURLs, actualURLs);
}
@Test
@@ -134,19 +134,19 @@ public class ExtensionsLoaderTest
HashSet<DruidModule> moduleSet = new HashSet<>(modules);
Collection<DruidModule> loadedModules = extnLoader.getModules();
- Assert.assertEquals("Set from loaded modules #1 should be same!", modules.size(), loadedModules.size());
- Assert.assertEquals("Set from loaded modules #1 should be same!", moduleSet, new HashSet<>(loadedModules));
+ Assertions.assertEquals(modules.size(), loadedModules.size(), "Set from loaded modules #1 should be same!");
+ Assertions.assertEquals(moduleSet, new HashSet<>(loadedModules), "Set from loaded modules #1 should be same!");
Collection<DruidModule> loadedModules2 = extnLoader.getModules();
- Assert.assertEquals("Set from loaded modules #2 should be same!", modules.size(), loadedModules2.size());
- Assert.assertEquals("Set from loaded modules #2 should be same!", moduleSet, new HashSet<>(loadedModules2));
+ Assertions.assertEquals(modules.size(), loadedModules2.size(), "Set from loaded modules #2 should be same!");
+ Assertions.assertEquals(moduleSet, new HashSet<>(loadedModules2), "Set from loaded modules #2 should be same!");
}
@Test
public void testGetExtensionFilesToLoad_non_exist_extensions_dir() throws IOException
{
final File tmpDir = temporaryFolder.newFolder();
- Assert.assertTrue("could not create missing folder", !tmpDir.exists() || tmpDir.delete());
+ Assertions.assertTrue(!tmpDir.exists() || tmpDir.delete(), "could not create missing folder");
final ExtensionsLoader extnLoader = new ExtensionsLoader(new ExtensionsConfig()
{
@Override
@@ -155,15 +155,15 @@ public class ExtensionsLoaderTest
return tmpDir.getAbsolutePath();
}
}, objectMapper);
- Assert.assertArrayEquals(
- "Non-exist root extensionsDir should return an empty array of File",
+ Assertions.assertArrayEquals(
new File[]{},
- extnLoader.getExtensionFilesToLoad()
+ extnLoader.getExtensionFilesToLoad(),
+ "Non-exist root extensionsDir should return an empty array of File"
);
}
- @Test(expected = ISE.class)
+ @Test
public void testGetExtensionFilesToLoad_wrong_type_extensions_dir() throws IOException
{
final File extensionsDir = temporaryFolder.newFile();
@@ -176,7 +176,7 @@ public class ExtensionsLoaderTest
}
};
final ExtensionsLoader extnLoader = new ExtensionsLoader(config, objectMapper);
- extnLoader.getExtensionFilesToLoad();
+ Assertions.assertThrows(ISE.class, extnLoader::getExtensionFilesToLoad);
}
@Test
@@ -193,10 +193,10 @@ public class ExtensionsLoaderTest
};
final ExtensionsLoader extnLoader = new ExtensionsLoader(config, objectMapper);
- Assert.assertArrayEquals(
- "Empty root extensionsDir should return an empty array of File",
+ Assertions.assertArrayEquals(
new File[]{},
- extnLoader.getExtensionFilesToLoad()
+ extnLoader.getExtensionFilesToLoad(),
+ "Empty root extensionsDir should return an empty array of File"
);
}
@@ -223,7 +223,7 @@ public class ExtensionsLoaderTest
final File[] expectedFileList = new File[]{mysql_metadata_storage};
final File[] actualFileList = extnLoader.getExtensionFilesToLoad();
Arrays.sort(actualFileList);
- Assert.assertArrayEquals(expectedFileList, actualFileList);
+ Assertions.assertArrayEquals(expectedFileList, actualFileList);
}
/**
@@ -260,14 +260,14 @@ public class ExtensionsLoaderTest
final File[] expectedFileList = new File[]{mysql_metadata_storage, absolutePathExtension};
final File[] actualFileList = extnLoader.getExtensionFilesToLoad();
- Assert.assertArrayEquals(expectedFileList, actualFileList);
+ Assertions.assertArrayEquals(expectedFileList, actualFileList);
}
/**
* druid.extension.load is specified, but contains an extension that is not prepared under root extension directory.
* Initialization.getExtensionFilesToLoad is supposed to throw ISE.
*/
- @Test(expected = ISE.class)
+ @Test
public void testGetExtensionFilesToLoad_with_non_exist_item_in_load_list() throws IOException
{
final File extensionsDir = temporaryFolder.newFolder();
@@ -288,7 +288,7 @@ public class ExtensionsLoaderTest
final File random_extension = new File(extensionsDir, "random-extensions");
random_extension.mkdir();
final ExtensionsLoader extnLoader = new ExtensionsLoader(config, objectMapper);
- extnLoader.getExtensionFilesToLoad();
+ Assertions.assertThrows(ISE.class, extnLoader::getExtensionFilesToLoad);
}
@Test
@@ -320,10 +320,10 @@ public class ExtensionsLoaderTest
// getURLsForClasspath uses listFiles which does NOT guarantee any ordering for the name strings.
List<URL> urLsForClasspath = ExtensionsLoader.getURLsForClasspath(cp);
- Assert.assertEquals(Sets.newHashSet(tmpDir1a.toURI().toURL(), tmpDir1b.toURI().toURL()),
+ Assertions.assertEquals(Sets.newHashSet(tmpDir1a.toURI().toURL(), tmpDir1b.toURI().toURL()),
Sets.newHashSet(urLsForClasspath.subList(0, 2)));
- Assert.assertEquals(tmpDir3.toURI().toURL(), urLsForClasspath.get(2));
- Assert.assertEquals(Sets.newHashSet(tmpDir2c.toURI().toURL(), tmpDir2d.toURI().toURL(), tmpDir2e.toURI().toURL()),
+ Assertions.assertEquals(tmpDir3.toURI().toURL(), urLsForClasspath.get(2));
+ Assertions.assertEquals(Sets.newHashSet(tmpDir2c.toURI().toURL(), tmpDir2d.toURI().toURL(), tmpDir2e.toURI().toURL()),
Sets.newHashSet(urLsForClasspath.subList(3, 6)));
}
@@ -335,8 +335,8 @@ public class ExtensionsLoaderTest
final File tmpDir2 = temporaryFolder.newFolder();
final File extension1 = new File(tmpDir1, extensionName);
final File extension2 = new File(tmpDir2, extensionName);
- Assert.assertTrue(extension1.mkdir());
- Assert.assertTrue(extension2.mkdir());
+ Assertions.assertTrue(extension1.mkdir());
+ Assertions.assertTrue(extension2.mkdir());
final File jar1 = new File(extension1, "jar1.jar");
final File jar2 = new File(extension2, "jar2.jar");
@@ -347,8 +347,8 @@ public class ExtensionsLoaderTest
final ClassLoader classLoader1 = extnLoader.getClassLoaderForExtension(extension1, false);
final ClassLoader classLoader2 = extnLoader.getClassLoaderForExtension(extension2, false);
- Assert.assertArrayEquals(new URL[]{jar1.toURI().toURL()}, ((StandardURLClassLoader) classLoader1).getURLs());
- Assert.assertArrayEquals(new URL[]{jar2.toURI().toURL()}, ((StandardURLClassLoader) classLoader2).getURLs());
+ Assertions.assertArrayEquals(new URL[]{jar1.toURI().toURL()}, ((StandardURLClassLoader) classLoader1).getURLs());
+ Assertions.assertArrayEquals(new URL[]{jar2.toURI().toURL()}, ((StandardURLClassLoader) classLoader2).getURLs());
}
@Test
@@ -362,11 +362,11 @@ public class ExtensionsLoaderTest
final File extensionJar = new File(extensionDir, "a.jar");
createNewJar(extensionJar, ImmutableMap.of("druid-extension-dependencies.json", objectMapper.writeValueAsBytes(druidExtensionDependencies)));
- RE exception = Assert.assertThrows(RE.class, () -> {
+ RE exception = Assertions.assertThrows(RE.class, () -> {
extnLoader.getClassLoaderForExtension(extensionDir, false);
});
- Assert.assertEquals(
+ Assertions.assertEquals(
StringUtils.format("Extension [%s] depends on [%s] which is not a valid extension or not loaded.", extensionDir.getName(), druidExtensionDependency),
exception.getMessage()
);
@@ -389,8 +389,8 @@ public class ExtensionsLoaderTest
StandardURLClassLoader classLoader = extnLoader.getClassLoaderForExtension(extensionDir, false);
StandardURLClassLoader dependendentClassLoader = extnLoader.getClassLoaderForExtension(dependentExtensionDir, false);
- Assert.assertTrue(dependendentClassLoader.getExtensionDependencyClassLoaders().contains(classLoader));
- Assert.assertEquals(0, classLoader.getExtensionDependencyClassLoaders().size());
+ Assertions.assertTrue(dependendentClassLoader.getExtensionDependencyClassLoaders().contains(classLoader));
+ Assertions.assertEquals(0, classLoader.getExtensionDependencyClassLoaders().size());
}
@@ -411,11 +411,11 @@ public class ExtensionsLoaderTest
final DruidExtensionDependencies druidExtensionDependenciesCircular = new DruidExtensionDependencies(ImmutableList.of(extensionDir.getName()));
createNewJar(dependentExtensionJar, ImmutableMap.of("druid-extension-dependencies.json", objectMapper.writeValueAsBytes(druidExtensionDependenciesCircular)));
- RE exception = Assert.assertThrows(RE.class, () -> {
+ RE exception = Assertions.assertThrows(RE.class, () -> {
extnLoader.getClassLoaderForExtension(extensionDir, false);
});
- Assert.assertTrue(exception.getMessage().contains("has a circular druid extension dependency."));
+ Assertions.assertTrue(exception.getMessage().contains("has a circular druid extension dependency."));
}
@Test
@@ -434,11 +434,11 @@ public class ExtensionsLoaderTest
createNewJar(extensionJar2, ImmutableMap.of("druid-extension-dependencies.json", objectMapper.writeValueAsBytes(druidExtensionDependencies)));
- RE exception = Assert.assertThrows(RE.class, () -> {
+ RE exception = Assertions.assertThrows(RE.class, () -> {
extnLoader.getClassLoaderForExtension(extensionDir, false);
});
- Assert.assertTrue(
+ Assertions.assertTrue(
exception.getMessage().contains("Each jar should be in a separate extension directory.")
);
}
@@ -457,8 +457,8 @@ public class ExtensionsLoaderTest
final ExtensionsLoader loaderWithAllowedModules = new ExtensionsLoader(configWithAllowedModules, objectMapper);
final List<DruidModule> modules = List.copyOf(loaderWithAllowedModules.getModules());
- Assert.assertEquals(1, modules.size());
- Assert.assertEquals(TestDruidModule.class, modules.get(0).getClass());
+ Assertions.assertEquals(1, modules.size());
+ Assertions.assertEquals(TestDruidModule.class, modules.get(0).getClass());
// Verify with no modules configured
final ExtensionsConfig configWithNoModules = new ExtensionsConfig() {
@@ -470,12 +470,12 @@ public class ExtensionsLoaderTest
};
final ExtensionsLoader loaderWithNoModules = new ExtensionsLoader(configWithNoModules, objectMapper);
- Assert.assertTrue(loaderWithNoModules.getModules().isEmpty());
+ Assertions.assertTrue(loaderWithNoModules.getModules().isEmpty());
}
private void createNewJar(File jarFileLocation, Map<String, byte[]> jarFileContents) throws IOException
{
- Assert.assertTrue(jarFileLocation.createNewFile());
+ Assertions.assertTrue(jarFileLocation.createNewFile());
FileOutputStream fos = new FileOutputStream(jarFileLocation.getPath());
JarOutputStream jarOut = new JarOutputStream(fos);
for (Map.Entry<String, byte[]> fileNameToContents : jarFileContents.entrySet()) {
diff --git a/processing/src/test/java/org/apache/druid/guice/JsonConfiguratorTest.java b/processing/src/test/java/org/apache/druid/guice/JsonConfiguratorTest.java
index 85873e09ea0..bd4a4f9908f 100644
--- a/processing/src/test/java/org/apache/druid/guice/JsonConfiguratorTest.java
+++ b/processing/src/test/java/org/apache/druid/guice/JsonConfiguratorTest.java
@@ -25,18 +25,19 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.apache.druid.jackson.DefaultObjectMapper;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.contrib.java.lang.system.EnvironmentVariables;
-import org.junit.contrib.java.lang.system.RestoreSystemProperties;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.executable.ExecutableValidator;
import javax.validation.metadata.BeanDescriptor;
+
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Properties;
import java.util.Set;
@@ -45,17 +46,27 @@ public class JsonConfiguratorTest
private static final String PROP_PREFIX = "test.property.prefix.";
private final ObjectMapper jsonMapper = new DefaultObjectMapper();
private final Properties properties = new Properties();
+ private final Map<String, String> originalSystemProperties = new HashMap<>();
- @Rule
- public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
-
- @Rule
- public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
-
- @Before
+ @BeforeEach
public void setUp()
{
jsonMapper.registerSubtypes(MappableObject.class);
+ for (String property : ImmutableList.of("my.property", "json.path", "sys.prop.name", "env.var.name")) {
+ originalSystemProperties.put(property, System.getProperty(property));
+ }
+ }
+
+ @AfterEach
+ public void tearDown()
+ {
+ originalSystemProperties.forEach((property, value) -> {
+ if (value == null) {
+ System.clearProperty(property);
+ } else {
+ System.setProperty(property, value);
+ }
+ });
}
final Validator validator = new Validator()
@@ -105,11 +116,11 @@ public class JsonConfiguratorTest
@Test
public void testTest()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
new MappableObject("p1", ImmutableList.of("p2"), "p2"),
new MappableObject("p1", ImmutableList.of("p2"), "p2")
);
- Assert.assertEquals(
+ Assertions.assertEquals(
new MappableObject("p1", null, null),
new MappableObject("p1", ImmutableList.of(), null)
);
@@ -122,8 +133,8 @@ public class JsonConfiguratorTest
properties.setProperty(PROP_PREFIX + "prop1", "prop1");
properties.setProperty(PROP_PREFIX + "prop1List", "[\"prop2\"]");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertEquals("prop1", obj.prop1);
- Assert.assertEquals(ImmutableList.of("prop2"), obj.prop1List);
+ Assertions.assertEquals("prop1", obj.prop1);
+ Assertions.assertEquals(ImmutableList.of("prop2"), obj.prop1List);
}
@Test
@@ -132,8 +143,8 @@ public class JsonConfiguratorTest
final JsonConfigurator configurator = new JsonConfigurator(jsonMapper, validator);
properties.setProperty(PROP_PREFIX + "prop1", "prop1");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertEquals("prop1", obj.prop1);
- Assert.assertEquals(ImmutableList.of(), obj.prop1List);
+ Assertions.assertEquals("prop1", obj.prop1);
+ Assertions.assertEquals(ImmutableList.of(), obj.prop1List);
}
@Test
@@ -142,8 +153,8 @@ public class JsonConfiguratorTest
final JsonConfigurator configurator = new JsonConfigurator(jsonMapper, validator);
properties.setProperty(PROP_PREFIX + "prop1List", "[\"prop2\"]");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertNull(obj.prop1);
- Assert.assertEquals(ImmutableList.of("prop2"), obj.prop1List);
+ Assertions.assertNull(obj.prop1);
+ Assertions.assertEquals(ImmutableList.of("prop2"), obj.prop1List);
}
@Test
@@ -152,8 +163,8 @@ public class JsonConfiguratorTest
final JsonConfigurator configurator = new JsonConfigurator(jsonMapper, validator);
properties.setProperty(PROP_PREFIX + "prop1", "testing \"prop1\"");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertEquals("testing \"prop1\"", obj.prop1);
- Assert.assertEquals(ImmutableList.of(), obj.prop1List);
+ Assertions.assertEquals("testing \"prop1\"", obj.prop1);
+ Assertions.assertEquals(ImmutableList.of(), obj.prop1List);
}
@Test
@@ -163,9 +174,9 @@ public class JsonConfiguratorTest
properties.setProperty(PROP_PREFIX + "prop2.prop.2", "testing");
properties.setProperty(PROP_PREFIX + "prop1", "prop1");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertEquals("testing", obj.prop2);
- Assert.assertEquals(ImmutableList.of(), obj.prop1List);
- Assert.assertEquals("prop1", obj.prop1);
+ Assertions.assertEquals("testing", obj.prop2);
+ Assertions.assertEquals(ImmutableList.of(), obj.prop1List);
+ Assertions.assertEquals("prop1", obj.prop1);
}
@@ -173,38 +184,36 @@ public class JsonConfiguratorTest
public void testPropertyInterpolation()
{
System.setProperty("my.property", "value1");
- List<String> list = ImmutableList.of("list", "of", "strings");
- environmentVariables.set("MY_VAR", "value2");
+ final List<String> list = ImmutableList.of("list", "of", "strings");
final JsonConfigurator configurator = new JsonConfigurator(jsonMapper, validator);
properties.setProperty(PROP_PREFIX + "prop1", "${sys:my.property}");
properties.setProperty(PROP_PREFIX + "prop1List", "${file:UTF-8:src/test/resources/list.json}");
- properties.setProperty(PROP_PREFIX + "prop2.prop.2", "${env:MY_VAR}");
+ properties.setProperty(PROP_PREFIX + "prop2.prop.2", "${env:PATH}");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertEquals(System.getProperty("my.property"), obj.prop1);
- Assert.assertEquals(list, obj.prop1List);
- Assert.assertEquals("value2", obj.prop2);
+ Assertions.assertEquals(System.getProperty("my.property"), obj.prop1);
+ Assertions.assertEquals(list, obj.prop1List);
+ Assertions.assertEquals(System.getenv("PATH"), obj.prop2);
}
@Test
public void testPropertyInterpolationInName()
{
System.setProperty("my.property", "value1");
- List<String> list = ImmutableList.of("list", "of", "strings");
- environmentVariables.set("MY_VAR", "value2");
+ final List<String> list = ImmutableList.of("list", "of", "strings");
- environmentVariables.set("SYS_PROP", "my.property");
+ System.setProperty("sys.prop.name", "my.property");
System.setProperty("json.path", "src/test/resources/list.json");
- environmentVariables.set("PROP2_NAME", "MY_VAR");
+ System.setProperty("env.var.name", "PATH");
final JsonConfigurator configurator = new JsonConfigurator(jsonMapper, validator);
- properties.setProperty(PROP_PREFIX + "prop1", "${sys:${env:SYS_PROP}}");
+ properties.setProperty(PROP_PREFIX + "prop1", "${sys:${sys:sys.prop.name}}");
properties.setProperty(PROP_PREFIX + "prop1List", "${file:UTF-8:${sys:json.path}}");
- properties.setProperty(PROP_PREFIX + "prop2.prop.2", "${env:${env:PROP2_NAME}}");
+ properties.setProperty(PROP_PREFIX + "prop2.prop.2", "${env:${sys:env.var.name}}");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertEquals(System.getProperty("my.property"), obj.prop1);
- Assert.assertEquals(list, obj.prop1List);
- Assert.assertEquals("value2", obj.prop2);
+ Assertions.assertEquals(System.getProperty("my.property"), obj.prop1);
+ Assertions.assertEquals(list, obj.prop1List);
+ Assertions.assertEquals(System.getenv("PATH"), obj.prop2);
}
@Test
@@ -217,9 +226,9 @@ public class JsonConfiguratorTest
properties.setProperty(PROP_PREFIX + "prop1List", "${unknown:-[\"list\", \"of\", \"strings\"]}");
properties.setProperty(PROP_PREFIX + "prop2.prop.2", "${MY_VAR:-value2}");
final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
- Assert.assertEquals("value1", obj.prop1);
- Assert.assertEquals(list, obj.prop1List);
- Assert.assertEquals("value2", obj.prop2);
+ Assertions.assertEquals("value1", obj.prop1);
+ Assertions.assertEquals(list, obj.prop1List);
+ Assertions.assertEquals("value2", obj.prop2);
}
@Test
@@ -228,7 +237,7 @@ public class JsonConfiguratorTest
final JsonConfigurator configurator = new JsonConfigurator(jsonMapper, validator);
properties.setProperty(PROP_PREFIX + "prop1", "${sys:my.property}");
- Assert.assertThrows(
+ Assertions.assertThrows(
IllegalArgumentException.class,
() -> configurator.configurate(properties, PROP_PREFIX, MappableObject.class)
);
diff --git a/processing/src/test/java/org/apache/druid/hll/HyperLogLogCollectorTest.java b/processing/src/test/java/org/apache/druid/hll/HyperLogLogCollectorTest.java
index 45a0116fa81..fc4d97a9fd6 100644
--- a/processing/src/test/java/org/apache/druid/hll/HyperLogLogCollectorTest.java
+++ b/processing/src/test/java/org/apache/druid/hll/HyperLogLogCollectorTest.java
@@ -26,9 +26,9 @@ import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -85,12 +85,12 @@ public class HyperLogLogCollectorTest
HyperLogLogCollector folded = HyperLogLogCollector.makeLatestCollector();
folded.fold(oneHalf);
- Assert.assertEquals(oneHalf, folded);
- Assert.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(oneHalf, folded);
+ Assertions.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
folded.fold(otherHalf);
- Assert.assertEquals(allCombined, folded);
- Assert.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(allCombined, folded);
+ Assertions.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
}
}
@@ -105,7 +105,7 @@ public class HyperLogLogCollectorTest
* with 100 values, requiring a floating max as described in
* https://druid.apache.org/blog/2014/02/18/hyperloglog-optimizations-for-real-world-systems.html
*/
- @Ignore
+ @Disabled
@Test
public void testHighCardinalityRollingFold() throws Exception
{
@@ -137,11 +137,11 @@ public class HyperLogLogCollectorTest
log.info("Simple buffer cardinality " + simple.estimateCardinality());
log.info("Rolling cardinality estimate off by %4.1f%%", 100 * (1 - rolling.estimateCardinality() / n));
- Assert.assertEquals(n, simple.estimateCardinality(), n * 0.05);
- Assert.assertEquals(n, rolling.estimateCardinality(), n * 0.05);
+ Assertions.assertEquals(n, simple.estimateCardinality(), n * 0.05);
+ Assertions.assertEquals(n, rolling.estimateCardinality(), n * 0.05);
}
- @Ignore
+ @Disabled
@Test
public void testHighCardinalityRollingFold2()
{
@@ -162,7 +162,7 @@ public class HyperLogLogCollectorTest
log.info("Rolling buffer cardinality " + rolling.estimateCardinality());
log.info("Rolling cardinality estimate off by %4.1f%%", 100 * (1 - rolling.estimateCardinality() / n));
- Assert.assertEquals(n, rolling.estimateCardinality(), n * 0.05);
+ Assertions.assertEquals(n, rolling.estimateCardinality(), n * 0.05);
}
@Test
@@ -189,12 +189,12 @@ public class HyperLogLogCollectorTest
HyperLogLogCollector folded = HyperLogLogCollector.makeLatestCollector();
folded.fold(oneHalf.toByteBuffer());
- Assert.assertEquals(oneHalf, folded);
- Assert.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(oneHalf, folded);
+ Assertions.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
folded.fold(otherHalf.toByteBuffer());
- Assert.assertEquals(allCombined, folded);
- Assert.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(allCombined, folded);
+ Assertions.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
}
}
@@ -225,12 +225,12 @@ public class HyperLogLogCollectorTest
);
folded.fold(oneHalf.toByteBuffer());
- Assert.assertEquals(oneHalf, folded);
- Assert.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(oneHalf, folded);
+ Assertions.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
folded.fold(otherHalf.toByteBuffer());
- Assert.assertEquals(allCombined, folded);
- Assert.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(allCombined, folded);
+ Assertions.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
}
}
@@ -264,12 +264,12 @@ public class HyperLogLogCollectorTest
);
folded.fold(oneHalf.toByteBuffer());
- Assert.assertEquals(oneHalf, folded);
- Assert.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(oneHalf, folded);
+ Assertions.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);
folded.fold(otherHalf.toByteBuffer());
- Assert.assertEquals(allCombined, folded);
- Assert.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(allCombined, folded);
+ Assertions.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
}
}
@@ -285,14 +285,14 @@ public class HyperLogLogCollectorTest
ByteBuffer outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 1);
- Assert.assertEquals(outBuffer.getShort(), 2047);
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 1);
+ Assertions.assertEquals(outBuffer.getShort(), 2047);
outBuffer.get();
outBuffer.getShort();
- Assert.assertEquals(outBuffer.get(), 0x10);
+ Assertions.assertEquals(outBuffer.get(), 0x10);
while (outBuffer.hasRemaining()) {
- Assert.assertEquals(outBuffer.get(), 0x11);
+ Assertions.assertEquals(outBuffer.get(), 0x11);
}
collector = HyperLogLogCollector.makeLatestCollector();
@@ -301,14 +301,14 @@ public class HyperLogLogCollectorTest
outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 1);
- Assert.assertEquals(outBuffer.getShort(), 2047);
- Assert.assertEquals(outBuffer.get(), 0);
- Assert.assertEquals(outBuffer.getShort(), 0);
- Assert.assertEquals(outBuffer.get(), 0x10);
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 1);
+ Assertions.assertEquals(outBuffer.getShort(), 2047);
+ Assertions.assertEquals(outBuffer.get(), 0);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertEquals(outBuffer.get(), 0x10);
while (outBuffer.hasRemaining()) {
- Assert.assertEquals(outBuffer.get(), 0x11);
+ Assertions.assertEquals(outBuffer.get(), 0x11);
}
}
@@ -323,11 +323,11 @@ public class HyperLogLogCollectorTest
// make sure the original buffer gets modified
collector.fold(biggerOffset);
- Assert.assertEquals(collector, HyperLogLogCollector.makeCollector(buffer.duplicate()));
+ Assertions.assertEquals(collector, HyperLogLogCollector.makeCollector(buffer.duplicate()));
// make sure the original buffer gets modified
collector.fold(smallerOffset);
- Assert.assertEquals(collector, HyperLogLogCollector.makeCollector(buffer.duplicate()));
+ Assertions.assertEquals(collector, HyperLogLogCollector.makeCollector(buffer.duplicate()));
}
@Test
@@ -342,14 +342,14 @@ public class HyperLogLogCollectorTest
ByteBuffer outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 1);
- Assert.assertEquals(outBuffer.getShort(), 2047);
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 1);
+ Assertions.assertEquals(outBuffer.getShort(), 2047);
outBuffer.get();
outBuffer.getShort();
- Assert.assertEquals(outBuffer.get(), 0x10);
+ Assertions.assertEquals(outBuffer.get(), 0x10);
while (outBuffer.hasRemaining()) {
- Assert.assertEquals(outBuffer.get(), 0x11);
+ Assertions.assertEquals(outBuffer.get(), 0x11);
}
collector = HyperLogLogCollector.makeLatestCollector();
@@ -358,14 +358,14 @@ public class HyperLogLogCollectorTest
outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 1);
- Assert.assertEquals(outBuffer.getShort(), 2047);
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 1);
+ Assertions.assertEquals(outBuffer.getShort(), 2047);
outBuffer.get();
outBuffer.getShort();
- Assert.assertEquals(outBuffer.get(), 0x10);
+ Assertions.assertEquals(outBuffer.get(), 0x10);
while (outBuffer.hasRemaining()) {
- Assert.assertEquals(outBuffer.get(), 0x11);
+ Assertions.assertEquals(outBuffer.get(), 0x11);
}
}
@@ -390,12 +390,12 @@ public class HyperLogLogCollectorTest
ByteBuffer outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 2);
- Assert.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 2);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
outBuffer.get();
outBuffer.getShort();
- Assert.assertFalse(outBuffer.hasRemaining());
+ Assertions.assertFalse(outBuffer.hasRemaining());
collector = HyperLogLogCollector.makeLatestCollector();
collector.fold(smallerOffset);
@@ -403,12 +403,12 @@ public class HyperLogLogCollectorTest
outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 2);
- Assert.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 2);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
outBuffer.get();
outBuffer.getShort();
- Assert.assertFalse(outBuffer.hasRemaining());
+ Assertions.assertFalse(outBuffer.hasRemaining());
}
@Test
@@ -434,12 +434,12 @@ public class HyperLogLogCollectorTest
ByteBuffer outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), VersionOneHyperLogLogCollector.VERSION);
- Assert.assertEquals(outBuffer.get(), 1);
- Assert.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertEquals(outBuffer.get(), VersionOneHyperLogLogCollector.VERSION);
+ Assertions.assertEquals(outBuffer.get(), 1);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
outBuffer.get();
outBuffer.getShort();
- Assert.assertFalse(outBuffer.hasRemaining());
+ Assertions.assertFalse(outBuffer.hasRemaining());
}
@Test
@@ -455,12 +455,12 @@ public class HyperLogLogCollectorTest
ByteBuffer outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 2);
- Assert.assertEquals(outBuffer.getShort(), 0);
- Assert.assertEquals(outBuffer.get(), 0);
- Assert.assertEquals(outBuffer.getShort(), 0);
- Assert.assertFalse(outBuffer.hasRemaining());
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 2);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertEquals(outBuffer.get(), 0);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertFalse(outBuffer.hasRemaining());
collector = HyperLogLogCollector.makeLatestCollector();
collector.fold(sparse);
@@ -468,12 +468,12 @@ public class HyperLogLogCollectorTest
outBuffer = collector.toByteBuffer();
- Assert.assertEquals(outBuffer.get(), collector.getVersion());
- Assert.assertEquals(outBuffer.get(), 2);
- Assert.assertEquals(outBuffer.getShort(), 0);
- Assert.assertEquals(outBuffer.get(), 0);
- Assert.assertEquals(outBuffer.getShort(), 0);
- Assert.assertFalse(outBuffer.hasRemaining());
+ Assertions.assertEquals(outBuffer.get(), collector.getVersion());
+ Assertions.assertEquals(outBuffer.get(), 2);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertEquals(outBuffer.get(), 0);
+ Assertions.assertEquals(outBuffer.getShort(), 0);
+ Assertions.assertFalse(outBuffer.hasRemaining());
}
private ByteBuffer makeCollectorBuffer(int offset, byte initialBytes, int remainingBytes)
@@ -517,7 +517,7 @@ public class HyperLogLogCollectorTest
return retVal;
}
- @Ignore
+ @Disabled
@Test // This test can help when finding potential combinations that are weird, but it's non-deterministic
public void testFoldingwithDifferentOffsets()
{
@@ -544,12 +544,12 @@ public class HyperLogLogCollectorTest
folded.fold(smallVals);
folded.fold(bigVals);
final double expected = all.estimateCardinality();
- Assert.assertEquals(expected, folded.estimateCardinality(), expected * 0.025);
- Assert.assertEquals(numThings, folded.estimateCardinality(), numThings * 0.05);
+ Assertions.assertEquals(expected, folded.estimateCardinality(), expected * 0.025);
+ Assertions.assertEquals(numThings, folded.estimateCardinality(), numThings * 0.05);
}
}
- @Ignore
+ @Disabled
@Test
public void testFoldingwithDifferentOffsets2() throws Exception
{
@@ -578,8 +578,8 @@ public class HyperLogLogCollectorTest
folded.fold(evenVals);
folded.fold(oddVals);
final double expected = all.estimateCardinality();
- Assert.assertEquals(expected, folded.estimateCardinality(), expected * 0.025);
- Assert.assertEquals(numThings, folded.estimateCardinality(), numThings * 0.05);
+ Assertions.assertEquals(expected, folded.estimateCardinality(), expected * 0.025);
+ Assertions.assertEquals(numThings, folded.estimateCardinality(), numThings * 0.05);
}
}
@@ -601,12 +601,12 @@ public class HyperLogLogCollectorTest
for (int i = 0; i < valsToCheck[valsToCheck.length - 1]; ++i) {
collector.add(fn.hashLong(random.nextLong()).asBytes());
if (i == valsToCheck[valsToCheckIndex]) {
- Assert.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
++valsToCheckIndex;
}
}
- Assert.assertEquals(expectedVals.length, valsToCheckIndex + 1);
- Assert.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(expectedVals.length, valsToCheckIndex + 1);
+ Assertions.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
}
@Test
@@ -631,12 +631,12 @@ public class HyperLogLogCollectorTest
for (int i = 0; i < valsToCheck[valsToCheck.length - 1]; ++i) {
collector.add(fn.hashLong(random.nextLong()).asBytes());
if (i == valsToCheck[valsToCheckIndex]) {
- Assert.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
++valsToCheckIndex;
}
}
- Assert.assertEquals(expectedVals.length, valsToCheckIndex + 1);
- Assert.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(expectedVals.length, valsToCheckIndex + 1);
+ Assertions.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
}
@Test
@@ -661,12 +661,12 @@ public class HyperLogLogCollectorTest
for (int i = 0; i < valsToCheck[valsToCheck.length - 1]; ++i) {
collector.add(fn.hashLong(random.nextLong()).asBytes());
if (i == valsToCheck[valsToCheckIndex]) {
- Assert.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
++valsToCheckIndex;
}
}
- Assert.assertEquals(expectedVals.length, valsToCheckIndex + 1);
- Assert.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
+ Assertions.assertEquals(expectedVals.length, valsToCheckIndex + 1);
+ Assertions.assertEquals(expectedVals[valsToCheckIndex], collector.estimateCardinality(), 0.0d);
}
@Test
@@ -679,7 +679,7 @@ public class HyperLogLogCollectorTest
collector.add(fn.hashLong(random.nextLong()).asBytes());
}
- Assert.assertEquals(
+ Assertions.assertEquals(
collector.estimateCardinality(), HyperLogLogCollector.estimateByteBuffer(collector.toByteBuffer()), 0.0d
);
}
@@ -694,13 +694,13 @@ public class HyperLogLogCollectorTest
// highest possible bit position is 64
collector.add(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
- Assert.assertEquals(8.5089685793441677E17, collector.estimateCardinality(), 1000);
+ Assertions.assertEquals(8.5089685793441677E17, collector.estimateCardinality(), 1000);
// this might happen once in a million years if you hash a billion values a second
fillBuckets(collector, (byte) 0, (byte) 63);
collector.add(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0});
- Assert.assertEquals(Double.POSITIVE_INFINITY, collector.estimateCardinality(), 1000);
+ Assertions.assertEquals(Double.POSITIVE_INFINITY, collector.estimateCardinality(), 1000);
}
@Test
@@ -708,20 +708,20 @@ public class HyperLogLogCollectorTest
{
HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
collector.add((short) 23, (byte) 16);
- Assert.assertEquals(23, collector.getMaxOverflowRegister());
- Assert.assertEquals(16, collector.getMaxOverflowValue());
- Assert.assertEquals(0, collector.getRegisterOffset());
- Assert.assertEquals(0, collector.getNumNonZeroRegisters());
+ Assertions.assertEquals(23, collector.getMaxOverflowRegister());
+ Assertions.assertEquals(16, collector.getMaxOverflowValue());
+ Assertions.assertEquals(0, collector.getRegisterOffset());
+ Assertions.assertEquals(0, collector.getNumNonZeroRegisters());
collector.add((short) 56, (byte) 17);
- Assert.assertEquals(56, collector.getMaxOverflowRegister());
- Assert.assertEquals(17, collector.getMaxOverflowValue());
+ Assertions.assertEquals(56, collector.getMaxOverflowRegister());
+ Assertions.assertEquals(17, collector.getMaxOverflowValue());
collector.add((short) 43, (byte) 16);
- Assert.assertEquals(56, collector.getMaxOverflowRegister());
- Assert.assertEquals(17, collector.getMaxOverflowValue());
- Assert.assertEquals(0, collector.getRegisterOffset());
- Assert.assertEquals(0, collector.getNumNonZeroRegisters());
+ Assertions.assertEquals(56, collector.getMaxOverflowRegister());
+ Assertions.assertEquals(17, collector.getMaxOverflowValue());
+ Assertions.assertEquals(0, collector.getRegisterOffset());
+ Assertions.assertEquals(0, collector.getNumNonZeroRegisters());
}
@Test
@@ -731,10 +731,10 @@ public class HyperLogLogCollectorTest
// Skip the first bucket
for (int i = 1; i < HyperLogLogCollector.NUM_BUCKETS; i++) {
collector.add((short) i, (byte) 1);
- Assert.assertEquals(i, collector.getNumNonZeroRegisters());
- Assert.assertEquals(0, collector.getRegisterOffset());
+ Assertions.assertEquals(i, collector.getNumNonZeroRegisters());
+ Assertions.assertEquals(0, collector.getRegisterOffset());
}
- Assert.assertEquals(
+ Assertions.assertEquals(
15615.219683654448D,
HyperLogLogCollector.makeCollector(collector.toByteBuffer().asReadOnlyBuffer())
.estimateCardinality(),
@@ -744,28 +744,28 @@ public class HyperLogLogCollectorTest
final byte[] hash = new byte[10];
hash[0] = 1; // Bucket 0, 1 offset of 0
collector.add(hash);
- Assert.assertEquals(0, collector.getNumNonZeroRegisters());
- Assert.assertEquals(1, collector.getRegisterOffset());
+ Assertions.assertEquals(0, collector.getNumNonZeroRegisters());
+ Assertions.assertEquals(1, collector.getRegisterOffset());
// We have a REALLY bad distribution, Sketch as 0 is fine.
- Assert.assertEquals(
+ Assertions.assertEquals(
0.0D,
HyperLogLogCollector.makeCollector(collector.toByteBuffer().asReadOnlyBuffer())
.estimateCardinality(),
1e-5D
);
final ByteBuffer buffer = collector.toByteBuffer();
- Assert.assertEquals(collector.getNumHeaderBytes(), buffer.remaining());
+ Assertions.assertEquals(collector.getNumHeaderBytes(), buffer.remaining());
final HyperLogLogCollector denseCollector = HyperLogLogCollector.makeLatestCollector();
for (int i = 0; i < HyperLogLogCollector.NUM_BUCKETS - 1; i++) {
denseCollector.add((short) i, (byte) 1);
}
- Assert.assertEquals(HyperLogLogCollector.NUM_BUCKETS - 1, denseCollector.getNumNonZeroRegisters());
+ Assertions.assertEquals(HyperLogLogCollector.NUM_BUCKETS - 1, denseCollector.getNumNonZeroRegisters());
final HyperLogLogCollector folded = denseCollector.fold(HyperLogLogCollector.makeCollector(buffer));
- Assert.assertNotNull(folded.toByteBuffer());
- Assert.assertEquals(folded.getStorageBuffer().remaining(), denseCollector.getNumBytesForDenseStorage());
+ Assertions.assertNotNull(folded.toByteBuffer());
+ Assertions.assertEquals(folded.getStorageBuffer().remaining(), denseCollector.getNumBytesForDenseStorage());
}
// Example of a terrible sampling filter. Don't use this method
@@ -795,8 +795,8 @@ public class HyperLogLogCollectorTest
hasher.putInt(rnd);
hyperLogLogCollector.add(hasher.hash().asBytes());
} while (hyperLogLogCollector.getNumNonZeroRegisters() > 0 && ++loops < loopLimit);
- Assert.assertNotEquals(loopLimit, loops);
- Assert.assertEquals(hyperLogLogCollector.getNumHeaderBytes(), hyperLogLogCollector.toByteBuffer().remaining());
+ Assertions.assertNotEquals(loopLimit, loops);
+ Assertions.assertEquals(hyperLogLogCollector.getNumHeaderBytes(), hyperLogLogCollector.toByteBuffer().remaining());
}
@Test
@@ -810,8 +810,8 @@ public class HyperLogLogCollectorTest
collector.add((short) 56, (byte) 17);
collector.fold(other);
- Assert.assertEquals(56, collector.getMaxOverflowRegister());
- Assert.assertEquals(17, collector.getMaxOverflowValue());
+ Assertions.assertEquals(56, collector.getMaxOverflowRegister());
+ Assertions.assertEquals(17, collector.getMaxOverflowValue());
// different offsets
// fill up all the buckets so we reach a registerOffset of 49
@@ -824,8 +824,8 @@ public class HyperLogLogCollectorTest
other.add((short) 47, (byte) 67);
collector.fold(other);
- Assert.assertEquals(47, collector.getMaxOverflowRegister());
- Assert.assertEquals(67, collector.getMaxOverflowValue());
+ Assertions.assertEquals(47, collector.getMaxOverflowRegister());
+ Assertions.assertEquals(67, collector.getMaxOverflowValue());
}
@Test
@@ -851,41 +851,41 @@ public class HyperLogLogCollectorTest
for (HyperLogLogCollector foldee : permutation) {
collector.fold(foldee);
}
- Assert.assertEquals(29, collector.getMaxOverflowValue());
- Assert.assertEquals(366, collector.getMaxOverflowRegister());
- Assert.assertEquals(1.0429189446653817E7, collector.estimateCardinality(), 1);
+ Assertions.assertEquals(29, collector.getMaxOverflowValue());
+ Assertions.assertEquals(366, collector.getMaxOverflowRegister());
+ Assertions.assertEquals(1.0429189446653817E7, collector.estimateCardinality(), 1);
}
}
@Test
- @Ignore("Doesn't pass; see https://github.com/apache/druid/issues/13950")
+ @Disabled("Doesn't pass; see https://github.com/apache/druid/issues/13950")
public void testAddEmptyString()
{
final HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
collector.add(HyperLogLogHash.getDefault().hash(""));
- Assert.assertEquals(1, collector.estimateCardinality(), 0.01);
+ Assertions.assertEquals(1, collector.estimateCardinality(), 0.01);
final byte[] collectorByteArray = collector.toByteArray();
final HyperLogLogCollector collector2 = HyperLogLogCollector.makeCollector(ByteBuffer.wrap(collectorByteArray));
- Assert.assertEquals(1, collector2.estimateCardinality(), 0.01);
+ Assertions.assertEquals(1, collector2.estimateCardinality(), 0.01);
}
@Test
- @Ignore("Doesn't pass; see https://github.com/apache/druid/issues/13950")
+ @Disabled("Doesn't pass; see https://github.com/apache/druid/issues/13950")
public void testAddEmptyStringAndOneOtherValue()
{
final HyperLogLogCollector collector = HyperLogLogCollector.makeLatestCollector();
collector.add(HyperLogLogHash.getDefault().hash("abc"));
collector.add(HyperLogLogHash.getDefault().hash(""));
- Assert.assertEquals(2, collector.estimateCardinality(), 0.01);
+ Assertions.assertEquals(2, collector.estimateCardinality(), 0.01);
final byte[] collectorByteArray = collector.toByteArray();
final HyperLogLogCollector collector2 = HyperLogLogCollector.makeCollector(ByteBuffer.wrap(collectorByteArray));
- Assert.assertEquals(2, collector2.estimateCardinality(), 0.01);
+ Assertions.assertEquals(2, collector2.estimateCardinality(), 0.01);
}
// Provides a nice printout of error rates as a function of cardinality
- @Ignore
+ @Disabled
@Test
public void showErrorRate()
{
diff --git a/processing/src/test/java/org/apache/druid/hll/HyperLogLogSerdeBenchmarkTest.java b/processing/src/test/java/org/apache/druid/hll/HyperLogLogSerdeBenchmarkTest.java
index 0e002d8ca31..58baf3a749f 100644
--- a/processing/src/test/java/org/apache/druid/hll/HyperLogLogSerdeBenchmarkTest.java
+++ b/processing/src/test/java/org/apache/druid/hll/HyperLogLogSerdeBenchmarkTest.java
@@ -19,19 +19,17 @@
package org.apache.druid.hll;
-import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
-import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.google.common.collect.ImmutableList;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.MethodSource;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -42,9 +40,10 @@ import java.util.Random;
/**
* TODO rewrite to use JMH and move to the benchmarks project
*/
-@RunWith(Parameterized.class)
-@Ignore // Don't need to run every time
-public class HyperLogLogSerdeBenchmarkTest extends AbstractBenchmark
+@ParameterizedClass
+@MethodSource("getParameters")
+@Disabled // Don't need to run every time
+public class HyperLogLogSerdeBenchmarkTest
{
private final HyperLogLogCollector collector;
private final long NUM_HASHES;
@@ -57,7 +56,6 @@ public class HyperLogLogSerdeBenchmarkTest extends AbstractBenchmark
private static final HashFunction HASH_FUNCTION = Hashing.murmur3_128();
- @Parameterized.Parameters
public static Collection<Object[]> getParameters()
{
return ImmutableList.of(
@@ -229,13 +227,13 @@ public class HyperLogLogSerdeBenchmarkTest extends AbstractBenchmark
return hasher.hash();
}
- @BeforeClass
+ @BeforeAll
public static void setupHash()
{
}
- @Before
+ @BeforeEach
public void setup()
{
fillCollector(collector);
@@ -245,7 +243,6 @@ public class HyperLogLogSerdeBenchmarkTest extends AbstractBenchmark
@SuppressWarnings("unused")
volatile HashCode hashCode;
- @BenchmarkOptions(benchmarkRounds = 100000, warmupRounds = 100)
@Test
public void benchmarkToByteBuffer()
{
diff --git a/processing/src/test/java/org/apache/druid/indexer/report/TaskReportSerdeTest.java b/processing/src/test/java/org/apache/druid/indexer/report/TaskReportSerdeTest.java
index b137ffe1f35..f21e99650d4 100644
--- a/processing/src/test/java/org/apache/druid/indexer/report/TaskReportSerdeTest.java
+++ b/processing/src/test/java/org/apache/druid/indexer/report/TaskReportSerdeTest.java
@@ -30,11 +30,11 @@ import org.apache.druid.java.util.common.jackson.JacksonUtils;
import org.apache.druid.segment.incremental.ParseExceptionReport;
import org.apache.druid.segment.incremental.RowIngestionMetersTotals;
import org.apache.druid.segment.incremental.RowMeters;
+import org.apache.druid.testing.TemporaryFolderExtension;
import org.apache.druid.utils.CollectionUtils;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.File;
import java.nio.charset.StandardCharsets;
@@ -49,8 +49,8 @@ public class TaskReportSerdeTest
{
private final ObjectMapper jsonMapper;
- @Rule
- public final TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @RegisterExtension
+ public final TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();
public TaskReportSerdeTest()
{
@@ -65,10 +65,10 @@ public class TaskReportSerdeTest
String reportJson = jsonMapper.writeValueAsString(originalReport);
TaskReport deserialized = jsonMapper.readValue(reportJson, TaskReport.class);
- Assert.assertTrue(deserialized instanceof IngestionStatsAndErrorsTaskReport);
+ Assertions.assertTrue(deserialized instanceof IngestionStatsAndErrorsTaskReport);
IngestionStatsAndErrorsTaskReport deserializedReport = (IngestionStatsAndErrorsTaskReport) deserialized;
- Assert.assertEquals(originalReport, deserializedReport);
+ Assertions.assertEquals(originalReport, deserializedReport);
}
@Test
@@ -78,11 +78,11 @@ public class TaskReportSerdeTest
String reportJson = jsonMapper.writeValueAsString(originalReport);
TaskReport deserialized = jsonMapper.readValue(reportJson, TaskReport.class);
- Assert.assertTrue(deserialized instanceof KillTaskReport);
+ Assertions.assertTrue(deserialized instanceof KillTaskReport);
KillTaskReport deserializedReport = (KillTaskReport) deserialized;
- Assert.assertEquals(originalReport, deserializedReport);
- Assert.assertEquals(originalReport.hashCode(), deserializedReport.hashCode());
+ Assertions.assertEquals(originalReport, deserializedReport);
+ Assertions.assertEquals(originalReport.hashCode(), deserializedReport.hashCode());
}
@Test
@@ -95,10 +95,10 @@ public class TaskReportSerdeTest
String reportJson = jsonMapper.writeValueAsString(originalReport);
TaskReport deserialized = jsonMapper.readValue(reportJson, TaskReport.class);
- Assert.assertTrue(deserialized instanceof TaskContextReport);
+ Assertions.assertTrue(deserialized instanceof TaskContextReport);
TaskContextReport deserializedReport = (TaskContextReport) deserialized;
- Assert.assertEquals(originalReport, deserializedReport);
+ Assertions.assertEquals(originalReport, deserializedReport);
}
@Test
@@ -112,7 +112,7 @@ public class TaskReportSerdeTest
writer.write("testID", reportMap1);
TaskReport.ReportMap reportMap2 = jsonMapper.readValue(reportFile, TaskReport.ReportMap.class);
- Assert.assertEquals(reportMap1, reportMap2);
+ Assertions.assertEquals(reportMap1, reportMap2);
}
@Test
@@ -123,7 +123,7 @@ public class TaskReportSerdeTest
String json = jsonMapper.writeValueAsString(reportMap);
TaskReport.ReportMap deserializedReportMap = jsonMapper.readValue(json, TaskReport.ReportMap.class);
- Assert.assertEquals(reportMap, deserializedReportMap);
+ Assertions.assertEquals(reportMap, deserializedReportMap);
}
@Test
@@ -186,22 +186,22 @@ public class TaskReportSerdeTest
final TaskReport.ReportMap deserializedReportMap = jsonMapper.readValue(plainMapJson, TaskReport.ReportMap.class);
Optional<IngestionStatsAndErrorsTaskReport> ingestStatsReport = deserializedReportMap.findReport(
"ingestionStatsAndErrors");
- Assert.assertTrue(ingestStatsReport.isPresent());
+ Assertions.assertTrue(ingestStatsReport.isPresent());
- Assert.assertEquals("ingestionStatsAndErrors", ingestStatsReport.get().getReportKey());
- Assert.assertEquals("abc", ingestStatsReport.get().getTaskId());
+ Assertions.assertEquals("ingestionStatsAndErrors", ingestStatsReport.get().getReportKey());
+ Assertions.assertEquals("abc", ingestStatsReport.get().getTaskId());
// Verify basic fields in the payload
final IngestionStatsAndErrors observedPayload = ingestStatsReport.get().getPayload();
- Assert.assertEquals(expectedPayload.get("ingestionState"), observedPayload.getIngestionState());
- Assert.assertNull(observedPayload.getSegmentsRead());
- Assert.assertNull(observedPayload.getSegmentsPublished());
- Assert.assertNull(observedPayload.getErrorMsg());
- Assert.assertNull(observedPayload.getRecordsProcessed());
+ Assertions.assertEquals(expectedPayload.get("ingestionState"), observedPayload.getIngestionState());
+ Assertions.assertNull(observedPayload.getSegmentsRead());
+ Assertions.assertNull(observedPayload.getSegmentsPublished());
+ Assertions.assertNull(observedPayload.getErrorMsg());
+ Assertions.assertNull(observedPayload.getRecordsProcessed());
// Verify stats and unparseable events
final Map<String, Object> observedRowStats = observedPayload.getRowStats();
- Assert.assertEquals(expectedAverages, observedRowStats.get("movingAverages"));
+ Assertions.assertEquals(expectedAverages, observedRowStats.get("movingAverages"));
final Map<String, Object> observedTotals = (Map<String, Object>) observedRowStats.get("totals");
verifyTotalRowStats(observedTotals, determinePartitionTotalStats, buildSegmentTotalStats);
@@ -220,15 +220,15 @@ public class TaskReportSerdeTest
// Verify basic fields in the payload
final Map<String, Object> observedPayload2 = (Map<String, Object>) ingestStatsReport2.get("payload");
- Assert.assertEquals(expectedPayload.get("ingestionState").toString(), observedPayload2.get("ingestionState"));
- Assert.assertNull(observedPayload2.get("segmentsRead"));
- Assert.assertNull(observedPayload2.get("segmentsPublished"));
- Assert.assertNull(observedPayload2.get("errorMsg"));
- Assert.assertNull(observedPayload2.get("recordsProcessed"));
+ Assertions.assertEquals(expectedPayload.get("ingestionState").toString(), observedPayload2.get("ingestionState"));
+ Assertions.assertNull(observedPayload2.get("segmentsRead"));
+ Assertions.assertNull(observedPayload2.get("segmentsPublished"));
+ Assertions.assertNull(observedPayload2.get("errorMsg"));
+ Assertions.assertNull(observedPayload2.get("recordsProcessed"));
// Verify stats and unparseable events
final Map<String, Object> observedRowStats2 = (Map<String, Object>) observedPayload2.get("rowStats");
- Assert.assertEquals(expectedAverages, observedRowStats2.get("movingAverages"));
+ Assertions.assertEquals(expectedAverages, observedRowStats2.get("movingAverages"));
final Map<String, Object> observedTotals2 = (Map<String, Object>) observedRowStats2.get("totals");
verifyTotalRowStats(observedTotals2, determinePartitionTotalStats, buildSegmentTotalStats);
@@ -278,8 +278,8 @@ public class TaskReportSerdeTest
);
TaskReport deserialized = jsonMapper.readValue(json, TaskReport.class);
- Assert.assertEquals(expected.getTaskId(), deserialized.getTaskId());
- Assert.assertEquals(expected, deserialized);
+ Assertions.assertEquals(expected.getTaskId(), deserialized.getTaskId());
+ Assertions.assertEquals(expected, deserialized);
}
@Test
@@ -292,7 +292,7 @@ public class TaskReportSerdeTest
// Read the file, ensure it's incomplete and not valid JSON. This allows callers to determine the report was
// not complete when written.
- Assert.assertEquals(
+ Assertions.assertEquals(
"{\"report\":{\"type\":\"exceptional\"",
Files.asCharSource(reportFile, StandardCharsets.UTF_8).read()
);
@@ -321,16 +321,16 @@ public class TaskReportSerdeTest
List<ParseExceptionReport> buildSegmentUnparseableEvents
)
{
- Assert.assertEquals(Collections.emptyList(), observed.get("determinePartitions"));
+ Assertions.assertEquals(Collections.emptyList(), observed.get("determinePartitions"));
final List<Object> observedBuildSegmentUnparseableEvents
= (List<Object>) observed.get("buildSegments");
- Assert.assertEquals(2, observedBuildSegmentUnparseableEvents.size());
+ Assertions.assertEquals(2, observedBuildSegmentUnparseableEvents.size());
for (int i = 0; i < buildSegmentUnparseableEvents.size(); ++i) {
final ParseExceptionReport expectedEvent = buildSegmentUnparseableEvents.get(i);
final Object observedEvent = observedBuildSegmentUnparseableEvents.get(i);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.of(
"input", expectedEvent.getInput(),
"errorType", expectedEvent.getErrorType(),
@@ -348,7 +348,7 @@ public class TaskReportSerdeTest
RowIngestionMetersTotals buildSegmentTotalStats
)
{
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.of(
"processed", (int) determinePartitionTotalStats.getProcessed(),
"processedBytes", (int) determinePartitionTotalStats.getProcessedBytes(),
@@ -359,7 +359,7 @@ public class TaskReportSerdeTest
),
observedTotals.get("determinePartitions")
);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.of(
"processed", (int) buildSegmentTotalStats.getProcessed(),
"processedBytes", (int) buildSegmentTotalStats.getProcessedBytes(),
diff --git a/processing/src/test/java/org/apache/druid/java/util/common/CompressionUtilsTest.java b/processing/src/test/java/org/apache/druid/java/util/common/CompressionUtilsTest.java
index 50a65c56832..6fe76c33a3a 100644
--- a/processing/src/test/java/org/apache/druid/java/util/common/CompressionUtilsTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/common/CompressionUtilsTest.java
@@ -31,12 +31,12 @@ import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream
import org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorOutputStream;
import org.apache.commons.compress.compressors.xz.XZCompressorOutputStream;
import org.apache.commons.compress.compressors.zstandard.ZstdCompressorOutputStream;
+import org.apache.druid.testing.TemporaryFolderExtension;
import org.apache.druid.utils.CompressionUtils;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -107,8 +107,8 @@ public class CompressionUtilsTest
GZ_BYTES = gzByteStream.toByteArray();
}
- @Rule
- public final TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @RegisterExtension
+ public final TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();
private File testDir;
private File testFile;
@@ -116,11 +116,11 @@ public class CompressionUtilsTest
{
try (final ByteArrayOutputStream bos = new ByteArrayOutputStream(EXPECTED.length)) {
ByteStreams.copy(stream, bos);
- Assert.assertArrayEquals(EXPECTED, bos.toByteArray());
+ Assertions.assertArrayEquals(EXPECTED, bos.toByteArray());
}
}
- @Before
+ @BeforeEach
public void setUp() throws IOException
{
testDir = temporaryFolder.newFolder("testDir");
@@ -128,26 +128,26 @@ public class CompressionUtilsTest
try (OutputStream outputStream = new FileOutputStream(testFile)) {
outputStream.write(StringUtils.toUtf8(CONTENT));
}
- Assert.assertTrue(testFile.getParentFile().equals(testDir));
+ Assertions.assertTrue(testFile.getParentFile().equals(testDir));
}
@Test
public void testGoodGzNameResolution()
{
- Assert.assertEquals("foo", CompressionUtils.getGzBaseName("foo.gz"));
+ Assertions.assertEquals("foo", CompressionUtils.getGzBaseName("foo.gz"));
}
- @Test(expected = IAE.class)
+ @Test
public void testBadGzName()
{
- CompressionUtils.getGzBaseName("foo");
+ Assertions.assertThrows(IAE.class, () -> CompressionUtils.getGzBaseName("foo"));
}
- @Test(expected = IAE.class)
+ @Test
public void testBadShortGzName()
{
- CompressionUtils.getGzBaseName(".gz");
+ Assertions.assertThrows(IAE.class, () -> CompressionUtils.getGzBaseName(".gz"));
}
@Test
@@ -196,9 +196,9 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testGoodGZCompressUncompressToFile");
final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
- Assert.assertFalse(gzFile.exists());
+ Assertions.assertFalse(gzFile.exists());
CompressionUtils.gzip(testFile, gzFile);
- Assert.assertTrue(gzFile.exists());
+ Assertions.assertTrue(gzFile.exists());
try (
final InputStream fileInputStream = new FileInputStream(gzFile);
final InputStream inputStream = new GZIPInputStream(fileInputStream)
@@ -206,9 +206,9 @@ public class CompressionUtilsTest
assertGoodDataStream(inputStream);
}
testFile.delete();
- Assert.assertFalse(testFile.exists());
+ Assertions.assertFalse(testFile.exists());
CompressionUtils.gunzip(gzFile, testFile);
- Assert.assertTrue(testFile.exists());
+ Assertions.assertTrue(testFile.exists());
try (final InputStream inputStream = new FileInputStream(testFile)) {
assertGoodDataStream(inputStream);
}
@@ -312,7 +312,7 @@ public class CompressionUtilsTest
verifyUnzip(unzipDir, result, expectedFiles);
// Check that all bytes were read from the stream
- Assert.assertEquals(zipFile.length(), zipIn.getCount());
+ Assertions.assertEquals(zipFile.length(), zipIn.getCount());
}
}
@@ -321,9 +321,9 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource");
final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
- Assert.assertFalse(gzFile.exists());
+ Assertions.assertFalse(gzFile.exists());
CompressionUtils.gzip(Files.asByteSource(testFile), Files.asByteSink(gzFile), Predicates.alwaysTrue());
- Assert.assertTrue(gzFile.exists());
+ Assertions.assertTrue(gzFile.exists());
try (
final InputStream fileInputStream = new FileInputStream(gzFile);
final InputStream inputStream = CompressionUtils.decompress(fileInputStream, gzFile.getName())
@@ -333,9 +333,9 @@ public class CompressionUtilsTest
if (!testFile.delete()) {
throw new IOE("Unable to delete file [%s]", testFile.getAbsolutePath());
}
- Assert.assertFalse(testFile.exists());
+ Assertions.assertFalse(testFile.exists());
CompressionUtils.gunzip(Files.asByteSource(gzFile), testFile);
- Assert.assertTrue(testFile.exists());
+ Assertions.assertTrue(testFile.exists());
try (final InputStream inputStream = new FileInputStream(testFile)) {
assertGoodDataStream(inputStream);
}
@@ -346,7 +346,7 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testDecompressBzip2");
final File bzFile = new File(tmpDir, testFile.getName() + ".bz2");
- Assert.assertFalse(bzFile.exists());
+ Assertions.assertFalse(bzFile.exists());
try (
final OutputStream fileOutputStream = new FileOutputStream(bzFile);
final OutputStream out = new BZip2CompressorOutputStream(fileOutputStream);
@@ -367,7 +367,7 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testDecompressXz");
final File xzFile = new File(tmpDir, testFile.getName() + ".xz");
- Assert.assertFalse(xzFile.exists());
+ Assertions.assertFalse(xzFile.exists());
try (
final OutputStream fileOutputStream = new FileOutputStream(xzFile);
final OutputStream out = new XZCompressorOutputStream(fileOutputStream);
@@ -388,7 +388,7 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testDecompressSnappy");
final File snappyFile = new File(tmpDir, testFile.getName() + ".sz");
- Assert.assertFalse(snappyFile.exists());
+ Assertions.assertFalse(snappyFile.exists());
try (
final OutputStream fileOutputStream = new FileOutputStream(snappyFile);
final OutputStream out = new FramedSnappyCompressorOutputStream(fileOutputStream);
@@ -409,7 +409,7 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testDecompressZstd");
final File zstdFile = new File(tmpDir, testFile.getName() + ".zst");
- Assert.assertFalse(zstdFile.exists());
+ Assertions.assertFalse(zstdFile.exists());
try (
final OutputStream fileOutputStream = new FileOutputStream(zstdFile);
final OutputStream out = new ZstdCompressorOutputStream(fileOutputStream);
@@ -430,7 +430,7 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testDecompressZip");
final File zipFile = new File(tmpDir, testFile.getName() + ".zip");
- Assert.assertFalse(zipFile.exists());
+ Assertions.assertFalse(zipFile.exists());
try (
final OutputStream fileOutputStream = new FileOutputStream(zipFile);
final ZipOutputStream out = new ZipOutputStream(fileOutputStream);
@@ -460,7 +460,7 @@ public class CompressionUtilsTest
final InputStream inputStream = CompressionUtils.decompress(fileInputStream, zipFile.getName())
) {
// Should read the first file, which contains a single null byte.
- Assert.assertArrayEquals(new byte[]{0}, ByteStreams.toByteArray(inputStream));
+ Assertions.assertArrayEquals(new byte[]{0}, ByteStreams.toByteArray(inputStream));
}
}
@@ -475,7 +475,7 @@ public class CompressionUtilsTest
}
final File newDir = new File(tmpDir, "newDir");
- Assert.assertTrue(newDir.mkdir());
+ Assertions.assertTrue(newDir.mkdir());
final FileUtils.FileCopyResult result;
try (final InputStream in = new FileInputStream(lz4File)) {
@@ -490,7 +490,7 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testDecompressLz4");
final File lz4File = new File(tmpDir, testFile.getName() + ".lz4");
- Assert.assertFalse(lz4File.exists());
+ Assertions.assertFalse(lz4File.exists());
try (
final OutputStream out = new LZ4BlockOutputStream(new FileOutputStream(lz4File));
@@ -509,14 +509,14 @@ public class CompressionUtilsTest
{
final File tmpDir = temporaryFolder.newFolder("testGoodGZStream");
final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
- Assert.assertFalse(gzFile.exists());
+ Assertions.assertFalse(gzFile.exists());
try (
final InputStream inputStream = new FileInputStream(testFile);
final OutputStream outputStream = new FileOutputStream(gzFile)
) {
CompressionUtils.gzip(inputStream, outputStream);
}
- Assert.assertTrue(gzFile.exists());
+ Assertions.assertTrue(gzFile.exists());
try (
final InputStream fileInputStream = new FileInputStream(gzFile);
final InputStream inputStream = new GZIPInputStream(fileInputStream)
@@ -526,11 +526,11 @@ public class CompressionUtilsTest
if (!testFile.delete()) {
throw new IOE("Unable to delete file [%s]", testFile.getAbsolutePath());
}
- Assert.assertFalse(testFile.exists());
+ Assertions.assertFalse(testFile.exists());
try (final InputStream inputStream = new FileInputStream(gzFile)) {
CompressionUtils.gunzip(inputStream, testFile);
}
- Assert.assertTrue(testFile.exists());
+ Assertions.assertTrue(testFile.exists());
try (final InputStream inputStream = new FileInputStream(testFile)) {
assertGoodDataStream(inputStream);
}
@@ -552,11 +552,11 @@ public class CompressionUtilsTest
CompressionUtils.unzip(evilZip, tmpDir);
}
catch (ISE ise) {
- Assert.assertTrue(ise.getMessage().contains("does not start with outDir"));
- Assert.assertFalse("Zip exploit triggered, /tmp/evil.txt was written.", evilResult.exists());
+ Assertions.assertTrue(ise.getMessage().contains("does not start with outDir"));
+ Assertions.assertFalse(evilResult.exists(), "Zip exploit triggered, /tmp/evil.txt was written.");
return;
}
- Assert.fail("Exception was not thrown for malicious zip file");
+ Assertions.fail("Exception was not thrown for malicious zip file");
}
@Test
@@ -575,11 +575,11 @@ public class CompressionUtilsTest
CompressionUtils.unzip(inputStream, tmpDir);
}
catch (ISE ise) {
- Assert.assertTrue(ise.getMessage().contains("does not start with outDir"));
- Assert.assertFalse("Zip exploit triggered, /tmp/evil.txt was written.", evilResult.exists());
+ Assertions.assertTrue(ise.getMessage().contains("does not start with outDir"));
+ Assertions.assertFalse(evilResult.exists(), "Zip exploit triggered, /tmp/evil.txt was written.");
return;
}
- Assert.fail("Exception was not thrown for malicious zip file");
+ Assertions.fail("Exception was not thrown for malicious zip file");
}
@Test
@@ -610,11 +610,11 @@ public class CompressionUtilsTest
);
}
catch (ISE ise) {
- Assert.assertTrue(ise.getMessage().contains("does not start with outDir"));
- Assert.assertFalse("Zip exploit triggered, /tmp/evil.txt was written.", evilResult.exists());
+ Assertions.assertTrue(ise.getMessage().contains("does not start with outDir"));
+ Assertions.assertFalse(evilResult.exists(), "Zip exploit triggered, /tmp/evil.txt was written.");
return;
}
- Assert.fail("Exception was not thrown for malicious zip file");
+ Assertions.fail("Exception was not thrown for malicious zip file");
}
@Test
@@ -622,21 +622,21 @@ public class CompressionUtilsTest
public void testZeroRemainingInputStream() throws IOException
{
try (OutputStream outputStream = new FileOutputStream(testFile)) {
- Assert.assertEquals(
+ Assertions.assertEquals(
GZ_BYTES.length,
ByteStreams.copy(
new ZeroRemainingInputStream(new ByteArrayInputStream(GZ_BYTES)),
outputStream
)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
GZ_BYTES.length,
ByteStreams.copy(
new ZeroRemainingInputStream(new ByteArrayInputStream(GZ_BYTES)),
outputStream
)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
GZ_BYTES.length,
ByteStreams.copy(
new ZeroRemainingInputStream(new ByteArrayInputStream(GZ_BYTES)),
@@ -644,15 +644,15 @@ public class CompressionUtilsTest
)
);
}
- Assert.assertEquals(GZ_BYTES.length * 3, testFile.length());
+ Assertions.assertEquals((long) GZ_BYTES.length * 3, testFile.length());
try (InputStream inputStream = new ZeroRemainingInputStream(new FileInputStream(testFile))) {
for (int i = 0; i < 3; ++i) {
final byte[] bytes = new byte[GZ_BYTES.length];
- Assert.assertEquals(bytes.length, inputStream.read(bytes));
- Assert.assertArrayEquals(
- StringUtils.format("Failed on range %d", i),
+ Assertions.assertEquals(bytes.length, inputStream.read(bytes));
+ Assertions.assertArrayEquals(
GZ_BYTES,
- bytes
+ bytes,
+ StringUtils.format("Failed on range %d", i)
);
}
}
@@ -662,7 +662,7 @@ public class CompressionUtilsTest
public void testGunzipConcatenatedByteSource() throws IOException
{
testFile.delete();
- Assert.assertFalse(testFile.exists());
+ Assertions.assertFalse(testFile.exists());
final ByteArrayOutputStream tripleGzByteStream = new ByteArrayOutputStream(GZ_BYTES.length * 3);
tripleGzByteStream.write(GZ_BYTES);
@@ -678,20 +678,20 @@ public class CompressionUtilsTest
}
};
- Assert.assertEquals((long) (EXPECTED.length * 3), CompressionUtils.gunzip(inputStreamFactory, testFile).size());
+ Assertions.assertEquals((long) (EXPECTED.length * 3), CompressionUtils.gunzip(inputStreamFactory, testFile).size());
try (final InputStream inputStream = new FileInputStream(testFile)) {
try (final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(EXPECTED.length * 3)) {
- Assert.assertEquals(
- "Read terminated too soon",
+ Assertions.assertEquals(
EXPECTED.length * 3,
- ByteStreams.copy(inputStream, outputStream)
+ ByteStreams.copy(inputStream, outputStream),
+ "Read terminated too soon"
);
final byte[] found = outputStream.toByteArray();
- Assert.assertEquals(EXPECTED.length * 3, found.length);
- Assert.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 0, EXPECTED.length * 1));
- Assert.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 1, EXPECTED.length * 2));
- Assert.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 2, EXPECTED.length * 3));
+ Assertions.assertEquals(EXPECTED.length * 3, found.length);
+ Assertions.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 0, EXPECTED.length * 1));
+ Assertions.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 1, EXPECTED.length * 2));
+ Assertions.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 2, EXPECTED.length * 3));
}
}
}
@@ -706,7 +706,7 @@ public class CompressionUtilsTest
tripleGzByteStream.write(GZ_BYTES);
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(EXPECTED.length * 3)) {
- Assert.assertEquals(
+ Assertions.assertEquals(
EXPECTED.length * 3,
CompressionUtils.gunzip(
new ZeroRemainingInputStream(
@@ -715,10 +715,10 @@ public class CompressionUtilsTest
)
);
final byte[] found = bos.toByteArray();
- Assert.assertEquals(EXPECTED.length * 3, found.length);
- Assert.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 0, EXPECTED.length * 1));
- Assert.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 1, EXPECTED.length * 2));
- Assert.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 2, EXPECTED.length * 3));
+ Assertions.assertEquals(EXPECTED.length * 3, found.length);
+ Assertions.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 0, EXPECTED.length * 1));
+ Assertions.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 1, EXPECTED.length * 2));
+ Assertions.assertArrayEquals(EXPECTED, Arrays.copyOfRange(found, EXPECTED.length * 2, EXPECTED.length * 3));
}
}
@@ -731,12 +731,12 @@ public class CompressionUtilsTest
final File file = new File(tmpDir, "zipDir.zip");
final Path unzipPath = Paths.get(zipDir.getPath(), "test.dat");
file.delete();
- Assert.assertFalse(file.exists());
- Assert.assertFalse(unzipPath.toFile().exists());
+ Assertions.assertFalse(file.exists());
+ Assertions.assertFalse(unzipPath.toFile().exists());
CompressionUtils.zip(testDir, file);
- Assert.assertTrue(file.exists());
+ Assertions.assertTrue(file.exists());
CompressionUtils.unzip(file, zipDir);
- Assert.assertTrue(unzipPath.toFile().exists());
+ Assertions.assertTrue(unzipPath.toFile().exists());
try (final FileInputStream inputStream = new FileInputStream(unzipPath.toFile())) {
assertGoodDataStream(inputStream);
}
@@ -746,37 +746,37 @@ public class CompressionUtilsTest
public void testNewFileDoesntCreateFile()
{
final File tmpFile = new File(testDir, "fofooofodshfudhfwdjkfwf.dat");
- Assert.assertFalse(tmpFile.exists());
+ Assertions.assertFalse(tmpFile.exists());
}
@Test
public void testGoodGzipName()
{
- Assert.assertEquals("foo", CompressionUtils.getGzBaseName("foo.gz"));
+ Assertions.assertEquals("foo", CompressionUtils.getGzBaseName("foo.gz"));
}
@Test
public void testGoodGzipNameWithPath()
{
- Assert.assertEquals("foo", CompressionUtils.getGzBaseName("/tar/ball/baz/bock/foo.gz"));
+ Assertions.assertEquals("foo", CompressionUtils.getGzBaseName("/tar/ball/baz/bock/foo.gz"));
}
- @Test(expected = IAE.class)
+ @Test
public void testBadShortName()
{
- CompressionUtils.getGzBaseName(".gz");
+ Assertions.assertThrows(IAE.class, () -> CompressionUtils.getGzBaseName(".gz"));
}
- @Test(expected = IAE.class)
+ @Test
public void testBadName()
{
- CompressionUtils.getGzBaseName("BANANAS");
+ Assertions.assertThrows(IAE.class, () -> CompressionUtils.getGzBaseName("BANANAS"));
}
- @Test(expected = IAE.class)
+ @Test
public void testBadNameWithPath()
{
- CompressionUtils.getGzBaseName("/foo/big/.gz");
+ Assertions.assertThrows(IAE.class, () -> CompressionUtils.getGzBaseName("/foo/big/.gz"));
}
@Test
@@ -785,7 +785,7 @@ public class CompressionUtilsTest
final AtomicLong flushes = new AtomicLong(0);
final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource");
final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
- Assert.assertFalse(gzFile.exists());
+ Assertions.assertFalse(gzFile.exists());
CompressionUtils.gzip(
Files.asByteSource(testFile), new ByteSink()
{
@@ -807,7 +807,7 @@ public class CompressionUtilsTest
}
}, Predicates.alwaysTrue()
);
- Assert.assertTrue(gzFile.exists());
+ Assertions.assertTrue(gzFile.exists());
try (
final InputStream fileInputStream = new FileInputStream(gzFile);
final InputStream inputStream = CompressionUtils.decompress(fileInputStream, "file.gz")
@@ -817,79 +817,89 @@ public class CompressionUtilsTest
if (!testFile.delete()) {
throw new IOE("Unable to delete file [%s]", testFile.getAbsolutePath());
}
- Assert.assertFalse(testFile.exists());
+ Assertions.assertFalse(testFile.exists());
CompressionUtils.gunzip(Files.asByteSource(gzFile), testFile);
- Assert.assertTrue(testFile.exists());
+ Assertions.assertTrue(testFile.exists());
try (final InputStream inputStream = new FileInputStream(testFile)) {
assertGoodDataStream(inputStream);
}
- Assert.assertEquals(4, flushes.get()); // 2 for suppressed closes, 2 for manual calls to shake out errors
+ Assertions.assertEquals(4, flushes.get()); // 2 for suppressed closes, 2 for manual calls to shake out errors
}
- @Test(expected = IOException.class)
+ @Test
public void testStreamErrorGzip() throws Exception
{
- final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource");
- final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
- Assert.assertFalse(gzFile.exists());
- final AtomicLong flushes = new AtomicLong(0L);
- try (
- final InputStream inputStream = new FileInputStream(testFile);
- final OutputStream outputStream = new FileOutputStream(gzFile)
- {
- @Override
- public void flush() throws IOException
- {
- if (flushes.getAndIncrement() > 0) {
- super.flush();
- } else {
- throw new IOException("Test exception");
- }
+ Assertions.assertThrows(
+ IOException.class,
+ () -> {
+ final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource");
+ final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
+ Assertions.assertFalse(gzFile.exists());
+ final AtomicLong flushes = new AtomicLong(0L);
+ try (
+ final InputStream inputStream = new FileInputStream(testFile);
+ final OutputStream outputStream = new FileOutputStream(gzFile)
+ {
+ @Override
+ public void flush() throws IOException
+ {
+ if (flushes.getAndIncrement() > 0) {
+ super.flush();
+ } else {
+ throw new IOException("Test exception");
+ }
+ }
+ }
+ ) {
+ CompressionUtils.gzip(inputStream, outputStream);
}
}
- ) {
- CompressionUtils.gzip(inputStream, outputStream);
- }
+ );
}
- @Test(expected = IOException.class)
+ @Test
public void testStreamErrorGunzip() throws Exception
{
- final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource");
- final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
- Assert.assertFalse(gzFile.exists());
- CompressionUtils.gzip(Files.asByteSource(testFile), Files.asByteSink(gzFile), Predicates.alwaysTrue());
- Assert.assertTrue(gzFile.exists());
- try (
- final InputStream fileInputStream = new FileInputStream(gzFile);
- final InputStream inputStream = CompressionUtils.decompress(fileInputStream, "file.gz")
- ) {
- assertGoodDataStream(inputStream);
- }
- if (testFile.exists() && !testFile.delete()) {
- throw new RE("Unable to delete file [%s]", testFile.getAbsolutePath());
- }
- Assert.assertFalse(testFile.exists());
- final AtomicLong flushes = new AtomicLong(0L);
- try (
- final InputStream inputStream = new FileInputStream(gzFile);
- final OutputStream outputStream = new FilterOutputStream(
- new FileOutputStream(testFile)
- {
- @Override
- public void flush() throws IOException
- {
- if (flushes.getAndIncrement() > 0) {
- super.flush();
- } else {
- throw new IOException("Test exception");
- }
- }
- }
- )
- ) {
- CompressionUtils.gunzip(inputStream, outputStream);
- }
+ Assertions.assertThrows(
+ IOException.class,
+ () -> {
+ final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource");
+ final File gzFile = new File(tmpDir, testFile.getName() + ".gz");
+ Assertions.assertFalse(gzFile.exists());
+ CompressionUtils.gzip(Files.asByteSource(testFile), Files.asByteSink(gzFile), Predicates.alwaysTrue());
+ Assertions.assertTrue(gzFile.exists());
+ try (
+ final InputStream fileInputStream = new FileInputStream(gzFile);
+ final InputStream inputStream = CompressionUtils.decompress(fileInputStream, "file.gz")
+ ) {
+ assertGoodDataStream(inputStream);
+ }
+ if (testFile.exists() && !testFile.delete()) {
+ throw new RE("Unable to delete file [%s]", testFile.getAbsolutePath());
+ }
+ Assertions.assertFalse(testFile.exists());
+ final AtomicLong flushes = new AtomicLong(0L);
+ try (
+ final InputStream inputStream = new FileInputStream(gzFile);
+ final OutputStream outputStream = new FilterOutputStream(
+ new FileOutputStream(testFile)
+ {
+ @Override
+ public void flush() throws IOException
+ {
+ if (flushes.getAndIncrement() > 0) {
+ super.flush();
+ } else {
+ throw new IOException("Test exception");
+ }
+ }
+ }
+ )
+ ) {
+ CompressionUtils.gunzip(inputStream, outputStream);
+ }
+ }
+ );
}
private void verifyUnzip(
@@ -901,14 +911,14 @@ public class CompressionUtilsTest
final List<String> filePaths = expectedFiles.keySet().stream().sorted().collect(Collectors.toList());
// Check the FileCopyResult
- Assert.assertEquals(expectedFiles.values().stream().mapToLong(arr -> arr.length).sum(), result.size());
- Assert.assertEquals(
+ Assertions.assertEquals(expectedFiles.values().stream().mapToLong(arr -> arr.length).sum(), result.size());
+ Assertions.assertEquals(
filePaths.stream().map(filePath -> new File(unzipDir, filePath)).collect(Collectors.toList()),
result.getFiles().stream().sorted().collect(Collectors.toList())
);
// Check the actual file list
- Assert.assertEquals(
+ Assertions.assertEquals(
filePaths,
Arrays.stream(unzipDir.listFiles()).map(File::getName).sorted().collect(Collectors.toList())
);
@@ -917,7 +927,7 @@ public class CompressionUtilsTest
for (Map.Entry<String, byte[]> entry : expectedFiles.entrySet()) {
try (final FileInputStream in = new FileInputStream(new File(unzipDir, entry.getKey()))) {
final byte[] bytes = ByteStreams.toByteArray(in);
- Assert.assertArrayEquals(entry.getValue(), bytes);
+ Assertions.assertArrayEquals(entry.getValue(), bytes);
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/java/util/common/GranularityTest.java b/processing/src/test/java/org/apache/druid/java/util/common/GranularityTest.java
index a4deac7b597..2304e722320 100644
--- a/processing/src/test/java/org/apache/druid/java/util/common/GranularityTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/common/GranularityTest.java
@@ -30,8 +30,8 @@ import org.joda.time.IllegalFieldValueException;
import org.joda.time.Interval;
import org.joda.time.Period;
import org.joda.time.chrono.ISOChronology;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.NoSuchElementException;
@@ -699,42 +699,43 @@ public class GranularityTest
for (PathDate pd : checks) {
if (pd.exception == null) {
// check if path returns expected date
- Assert.assertEquals(
+ Assertions.assertEquals(
+ pd.date,
+ granularity.toDate(pd.path, formatter),
StringUtils.format(
"[%s,%s] Expected path %s to return date %s",
granularity,
formatter,
pd.path,
pd.date
- ),
- pd.date,
- granularity.toDate(pd.path, formatter)
+ )
);
if (formatter.equals(Granularity.Formatter.DEFAULT)) {
- Assert.assertEquals(
+ Assertions.assertEquals(
+ granularity.toDate(pd.path),
+ granularity.toDate(pd.path, formatter),
StringUtils.format(
"[%s] Expected toDate(%s) to return the same as toDate(%s, DEFAULT)",
granularity,
pd.path,
pd.path
- ),
- granularity.toDate(pd.path), granularity.toDate(pd.path, formatter)
+ )
);
}
if (pd.date != null) {
// check if formatter is readable by toDate
- Assert.assertEquals(
+ Assertions.assertEquals(
+ pd.date,
+ granularity.toDate(granularity.getFormatter(formatter).print(pd.date) + "/", formatter),
StringUtils.format(
"[%s,%s] Expected date %s to return date %s",
granularity,
formatter,
pd.date,
pd.date
- ),
- pd.date,
- granularity.toDate(granularity.getFormatter(formatter).print(pd.date) + "/", formatter)
+ )
);
}
} else {
@@ -748,15 +749,15 @@ public class GranularityTest
}
}
- Assert.assertTrue(
+ Assertions.assertTrue(
+ flag,
StringUtils.format(
"[%s,%s] Expected exception %s for path: %s",
granularity,
formatter,
pd.exception,
pd.path
- ),
- flag
+ )
);
}
}
@@ -767,78 +768,78 @@ public class GranularityTest
{
DateTime dt = DateTimes.of("2011-02-03T04:05:06.100");
- Assert.assertEquals(Intervals.ETERNITY, ALL.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-01-01/2012-01-01"), YEAR.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-02-01/2011-03-01"), MONTH.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-01-31/2011-02-07"), WEEK.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-02-03/2011-02-04"), DAY.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-02-03T04/2011-02-03T05"), HOUR.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-02-03T04:05:00/2011-02-03T04:06:00"), MINUTE.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-02-03T04:05:06/2011-02-03T04:05:07"), SECOND.bucket(dt));
- Assert.assertEquals(Intervals.of("2011-02-03T04:05:06.100/2011-02-03T04:05:06.101"), NONE.bucket(dt));
+ Assertions.assertEquals(Intervals.ETERNITY, ALL.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-01-01/2012-01-01"), YEAR.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-02-01/2011-03-01"), MONTH.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-01-31/2011-02-07"), WEEK.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-02-03/2011-02-04"), DAY.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-02-03T04/2011-02-03T05"), HOUR.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-02-03T04:05:00/2011-02-03T04:06:00"), MINUTE.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-02-03T04:05:06/2011-02-03T04:05:07"), SECOND.bucket(dt));
+ Assertions.assertEquals(Intervals.of("2011-02-03T04:05:06.100/2011-02-03T04:05:06.101"), NONE.bucket(dt));
// Test with aligned DateTime
- Assert.assertEquals(Intervals.of("2011-01-01/2011-01-02"), DAY.bucket(DateTimes.of("2011-01-01")));
+ Assertions.assertEquals(Intervals.of("2011-01-01/2011-01-02"), DAY.bucket(DateTimes.of("2011-01-01")));
}
@Test
public void testBucketStart()
{
DateTime date = DateTimes.of("2011-03-15T22:42:23.898");
- Assert.assertEquals(DateTimes.MIN, ALL.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-01-01T00:00:00.000"), YEAR.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-03-01T00:00:00.000"), MONTH.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-03-14T00:00:00.000"), WEEK.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T00:00:00.000"), DAY.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:00:00.000"), HOUR.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:00.000"), MINUTE.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:23.000"), SECOND.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:23.898"), NONE.bucketStart(date));
+ Assertions.assertEquals(DateTimes.MIN, ALL.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-01-01T00:00:00.000"), YEAR.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-01T00:00:00.000"), MONTH.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-14T00:00:00.000"), WEEK.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T00:00:00.000"), DAY.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:00:00.000"), HOUR.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:00.000"), MINUTE.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:23.000"), SECOND.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:23.898"), NONE.bucketStart(date));
}
@Test
public void testBucketStartOnMillis()
{
DateTime date = DateTimes.of("2011-03-15T22:42:23.898");
- Assert.assertEquals(DateTimes.MIN.getMillis(), ALL.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-01-01T00:00:00.000").getMillis(), YEAR.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-01T00:00:00.000").getMillis(), MONTH.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-14T00:00:00.000").getMillis(), WEEK.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T00:00:00.000").getMillis(), DAY.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:00:00.000").getMillis(), HOUR.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:00.000").getMillis(), MINUTE.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:23.000").getMillis(), SECOND.bucketStart(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:23.898").getMillis(), NONE.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.MIN.getMillis(), ALL.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-01-01T00:00:00.000").getMillis(), YEAR.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-01T00:00:00.000").getMillis(), MONTH.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-14T00:00:00.000").getMillis(), WEEK.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T00:00:00.000").getMillis(), DAY.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:00:00.000").getMillis(), HOUR.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:00.000").getMillis(), MINUTE.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:23.000").getMillis(), SECOND.bucketStart(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:23.898").getMillis(), NONE.bucketStart(date.getMillis()));
}
@Test
public void testIncrement()
{
DateTime date = DateTimes.of("2011-03-15T22:42:23.898");
- Assert.assertEquals(DateTimes.MIN, ALL.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2012-03-15T22:42:23.898"), YEAR.increment(date));
- Assert.assertEquals(DateTimes.of("2011-04-15T22:42:23.898"), MONTH.increment(date));
- Assert.assertEquals(DateTimes.of("2011-03-22T22:42:23.898"), WEEK.increment(date));
- Assert.assertEquals(DateTimes.of("2011-03-16T22:42:23.898"), DAY.increment(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T23:42:23.898"), HOUR.increment(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:43:23.898"), MINUTE.increment(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:24.898"), SECOND.increment(date));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:23.899"), NONE.increment(date));
+ Assertions.assertEquals(DateTimes.MIN, ALL.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2012-03-15T22:42:23.898"), YEAR.increment(date));
+ Assertions.assertEquals(DateTimes.of("2011-04-15T22:42:23.898"), MONTH.increment(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-22T22:42:23.898"), WEEK.increment(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-16T22:42:23.898"), DAY.increment(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T23:42:23.898"), HOUR.increment(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:43:23.898"), MINUTE.increment(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:24.898"), SECOND.increment(date));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:23.899"), NONE.increment(date));
}
@Test
public void testIncrementOnMillis()
{
DateTime date = DateTimes.of("2011-03-15T22:42:23.898");
- Assert.assertEquals(DateTimes.MIN, ALL.bucketStart(date));
- Assert.assertEquals(DateTimes.of("2012-03-15T22:42:23.898").getMillis(), YEAR.increment(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-04-15T22:42:23.898").getMillis(), MONTH.increment(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-22T22:42:23.898").getMillis(), WEEK.increment(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-16T22:42:23.898").getMillis(), DAY.increment(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T23:42:23.898").getMillis(), HOUR.increment(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:43:23.898").getMillis(), MINUTE.increment(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:24.898").getMillis(), SECOND.increment(date.getMillis()));
- Assert.assertEquals(DateTimes.of("2011-03-15T22:42:23.899").getMillis(), NONE.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.MIN, ALL.bucketStart(date));
+ Assertions.assertEquals(DateTimes.of("2012-03-15T22:42:23.898").getMillis(), YEAR.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-04-15T22:42:23.898").getMillis(), MONTH.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-22T22:42:23.898").getMillis(), WEEK.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-16T22:42:23.898").getMillis(), DAY.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T23:42:23.898").getMillis(), HOUR.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:43:23.898").getMillis(), MINUTE.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:24.898").getMillis(), SECOND.increment(date.getMillis()));
+ Assertions.assertEquals(DateTimes.of("2011-03-15T22:42:23.899").getMillis(), NONE.increment(date.getMillis()));
}
@Test
@@ -849,25 +850,25 @@ public class GranularityTest
Iterator<Interval> intervals = DAY.getIterable(new Interval(start, end)).iterator();
- Assert.assertEquals(Intervals.of("2011-01-01/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-02/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-03/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-04/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-05/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-06/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-07/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-08/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-09/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-10/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-11/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-12/P1d"), intervals.next());
- Assert.assertEquals(Intervals.of("2011-01-13/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-01/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-02/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-03/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-04/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-05/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-06/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-07/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-08/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-09/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-10/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-11/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-12/P1d"), intervals.next());
+ Assertions.assertEquals(Intervals.of("2011-01-13/P1d"), intervals.next());
try {
intervals.next();
}
catch (NoSuchElementException e) {
- Assert.assertTrue(true);
+ Assertions.assertTrue(true);
}
}
@@ -904,7 +905,7 @@ public class GranularityTest
try {
Period p = Period.years(6).withMonths(3).withSeconds(23);
GranularityType.fromPeriod(p);
- Assert.fail("Complicated period creation should fail b/c of unsupported granularity type.");
+ Assertions.fail("Complicated period creation should fail b/c of unsupported granularity type.");
}
catch (IAE e) {
// pass
@@ -933,7 +934,7 @@ public class GranularityTest
// Similar to what query engines do: call granularity.bucketStart on the datetimes returned by their cursors.
// (And the cursors, in turn, use getIterable like above.)
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(
new DateTime("2017-10-14", saoPaulo),
new DateTime("2017-10-15T01", saoPaulo),
@@ -948,27 +949,27 @@ public class GranularityTest
@Test
public void testIsFinerComparator()
{
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(NONE, SECOND) < 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(SECOND, NONE) > 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(NONE, MINUTE) < 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(MINUTE, NONE) > 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(DAY, MONTH) < 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(Granularities.YEAR, ALL) < 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(Granularities.ALL, YEAR) > 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(NONE, SECOND) < 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(SECOND, NONE) > 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(NONE, MINUTE) < 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(MINUTE, NONE) > 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(DAY, MONTH) < 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(Granularities.YEAR, ALL) < 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(Granularities.ALL, YEAR) > 0);
// Distinct references are needed to avoid intelli-j complain about compare being called on itself
// thus the variables
Granularity day = DAY;
Granularity none = NONE;
Granularity all = ALL;
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(DAY, day) == 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(NONE, none) == 0);
- Assert.assertTrue(Granularity.IS_FINER_THAN.compare(ALL, all) == 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(DAY, day) == 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(NONE, none) == 0);
+ Assertions.assertTrue(Granularity.IS_FINER_THAN.compare(ALL, all) == 0);
}
@Test
public void testGranularitiesFinerThanDay()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(
Granularities.DAY,
Granularities.EIGHT_HOUR,
@@ -988,7 +989,7 @@ public class GranularityTest
@Test
public void testGranularitiesFinerThanHour()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(
Granularities.HOUR,
Granularities.THIRTY_MINUTE,
@@ -1005,7 +1006,7 @@ public class GranularityTest
@Test
public void testGranularitiesFinerThanWeek()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(
Granularities.WEEK,
Granularities.DAY,
@@ -1026,7 +1027,7 @@ public class GranularityTest
@Test
public void testGranularitiesFinerThanAll()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(
Granularities.ALL,
Granularities.YEAR,
@@ -1050,7 +1051,7 @@ public class GranularityTest
@Test
public void testGranularitiesFinerThanNone()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableList.of(),
Granularity.granularitiesFinerThan(Granularities.NONE)
);
diff --git a/processing/src/test/java/org/apache/druid/java/util/common/HumanReadableBytesTest.java b/processing/src/test/java/org/apache/druid/java/util/common/HumanReadableBytesTest.java
index bf44e55f461..4857a6ea795 100644
--- a/processing/src/test/java/org/apache/druid/java/util/common/HumanReadableBytesTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/common/HumanReadableBytesTest.java
@@ -22,359 +22,318 @@ package org.apache.druid.java.util.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.druid.utils.CollectionUtils;
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
+
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HumanReadableBytesTest
{
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
+ private static final String INVALID_FORMAT_PREFIX = "Invalid format";
+ private static final String OVERFLOW_PREFIX = "Number overflow";
@Test
public void testNumberString()
{
- Assert.assertEquals(0, HumanReadableBytes.parse("0"));
- Assert.assertEquals(1, HumanReadableBytes.parse("1"));
- Assert.assertEquals(10000000, HumanReadableBytes.parse("10000000"));
+ Assertions.assertEquals(0, HumanReadableBytes.parse("0"));
+ Assertions.assertEquals(1, HumanReadableBytes.parse("1"));
+ Assertions.assertEquals(10000000, HumanReadableBytes.parse("10000000"));
}
@Test
public void testWithWhiteSpace()
{
- Assert.assertEquals(12345, HumanReadableBytes.parse(" 12345 "));
- Assert.assertEquals(12345, HumanReadableBytes.parse("\t12345\t"));
+ Assertions.assertEquals(12345, HumanReadableBytes.parse(" 12345 "));
+ Assertions.assertEquals(12345, HumanReadableBytes.parse("\t12345\t"));
}
@Test
public void testK()
{
- Assert.assertEquals(1000, HumanReadableBytes.parse("1k"));
- Assert.assertEquals(1000, HumanReadableBytes.parse("1K"));
+ Assertions.assertEquals(1000, HumanReadableBytes.parse("1k"));
+ Assertions.assertEquals(1000, HumanReadableBytes.parse("1K"));
}
@Test
public void testM()
{
- Assert.assertEquals(1000_000, HumanReadableBytes.parse("1m"));
- Assert.assertEquals(1000_000, HumanReadableBytes.parse("1M"));
+ Assertions.assertEquals(1000_000, HumanReadableBytes.parse("1m"));
+ Assertions.assertEquals(1000_000, HumanReadableBytes.parse("1M"));
}
@Test
public void testG()
{
- Assert.assertEquals(1000_000_000, HumanReadableBytes.parse("1g"));
- Assert.assertEquals(1000_000_000, HumanReadableBytes.parse("1G"));
+ Assertions.assertEquals(1000_000_000, HumanReadableBytes.parse("1g"));
+ Assertions.assertEquals(1000_000_000, HumanReadableBytes.parse("1G"));
}
@Test
public void testT()
{
- Assert.assertEquals(1000_000_000_000L, HumanReadableBytes.parse("1t"));
- Assert.assertEquals(1000_000_000_000L, HumanReadableBytes.parse("1T"));
+ Assertions.assertEquals(1000_000_000_000L, HumanReadableBytes.parse("1t"));
+ Assertions.assertEquals(1000_000_000_000L, HumanReadableBytes.parse("1T"));
}
@Test
public void testKiB()
{
- Assert.assertEquals(1024, HumanReadableBytes.parse("1kib"));
- Assert.assertEquals(9 * 1024, HumanReadableBytes.parse("9KiB"));
- Assert.assertEquals(9 * 1024, HumanReadableBytes.parse("9Kib"));
- Assert.assertEquals(9 * 1024, HumanReadableBytes.parse("9Ki"));
+ Assertions.assertEquals(1024, HumanReadableBytes.parse("1kib"));
+ Assertions.assertEquals(9 * 1024, HumanReadableBytes.parse("9KiB"));
+ Assertions.assertEquals(9 * 1024, HumanReadableBytes.parse("9Kib"));
+ Assertions.assertEquals(9 * 1024, HumanReadableBytes.parse("9Ki"));
}
@Test
public void testMiB()
{
- Assert.assertEquals(1024 * 1024, HumanReadableBytes.parse("1mib"));
- Assert.assertEquals(9 * 1024 * 1024, HumanReadableBytes.parse("9MiB"));
- Assert.assertEquals(9 * 1024 * 1024, HumanReadableBytes.parse("9Mib"));
- Assert.assertEquals(9 * 1024 * 1024, HumanReadableBytes.parse("9Mi"));
+ Assertions.assertEquals(1024 * 1024, HumanReadableBytes.parse("1mib"));
+ Assertions.assertEquals(9 * 1024 * 1024, HumanReadableBytes.parse("9MiB"));
+ Assertions.assertEquals(9 * 1024 * 1024, HumanReadableBytes.parse("9Mib"));
+ Assertions.assertEquals(9 * 1024 * 1024, HumanReadableBytes.parse("9Mi"));
}
@Test
public void testGiB()
{
- Assert.assertEquals(1024 * 1024 * 1024, HumanReadableBytes.parse("1gib"));
- Assert.assertEquals(1024 * 1024 * 1024, HumanReadableBytes.parse("1GiB"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Gib"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Gi"));
+ Assertions.assertEquals(1024 * 1024 * 1024, HumanReadableBytes.parse("1gib"));
+ Assertions.assertEquals(1024 * 1024 * 1024, HumanReadableBytes.parse("1GiB"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Gib"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Gi"));
}
@Test
public void testTiB()
{
- Assert.assertEquals(1024L * 1024 * 1024 * 1024, HumanReadableBytes.parse("1tib"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9TiB"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Tib"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Ti"));
+ Assertions.assertEquals(1024L * 1024 * 1024 * 1024, HumanReadableBytes.parse("1tib"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9TiB"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Tib"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Ti"));
}
@Test
public void testPiB()
{
- Assert.assertEquals(1024L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("1pib"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9PiB"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Pib"));
- Assert.assertEquals(9L * 1024 * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Pi"));
+ Assertions.assertEquals(1024L * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("1pib"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9PiB"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Pib"));
+ Assertions.assertEquals(9L * 1024 * 1024 * 1024 * 1024 * 1024, HumanReadableBytes.parse("9Pi"));
}
@Test
public void testDefault()
{
- Assert.assertEquals(-123, HumanReadableBytes.parse(" ", -123));
- Assert.assertEquals(-456, HumanReadableBytes.parse(null, -456));
- Assert.assertEquals(-789, HumanReadableBytes.parse("\t", -789));
- }
-
- static class ExceptionMatcher implements Matcher
- {
- static ExceptionMatcher INVALIDFORMAT = new ExceptionMatcher("Invalid format");
- static ExceptionMatcher OVERFLOW = new ExceptionMatcher("Number overflow");
-
- private String prefix;
-
- public ExceptionMatcher(String prefix)
- {
- this.prefix = prefix;
- }
-
- @Override
- public boolean matches(Object item)
- {
- if (!(item instanceof IAE)) {
- return false;
- }
-
- return ((IAE) item).getMessage().startsWith(prefix);
- }
-
- @Override
- public void describeMismatch(Object item, Description mismatchDescription)
- {
- }
-
- @Override
- public void _dont_implement_Matcher___instead_extend_BaseMatcher_()
- {
- }
-
- @Override
- public void describeTo(Description description)
- {
- }
+ Assertions.assertEquals(-123, HumanReadableBytes.parse(" ", -123));
+ Assertions.assertEquals(-456, HumanReadableBytes.parse(null, -456));
+ Assertions.assertEquals(-789, HumanReadableBytes.parse("\t", -789));
}
@Test
public void testNull()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse(null);
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(null));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testEmpty()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(""));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testWhitespace()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse(" ");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(" "));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testNegative()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("-1");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("-1"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatOneChar()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("b");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("b"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatOneCharK8s()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("i");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("i"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatOneChar2()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("B");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("B"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatExtraSpace()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("1 b");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("1 b"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormat4()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("1b");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("1b"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatMiBExtraSpace()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("1 mib");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("1 mib"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatMiExtraSpace()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("1 mi");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("1 mi"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatTiB()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("tib");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("tib"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatTi()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("ti");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("ti"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatGiB()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("gib");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("gib"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidFormatPiB()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse(" pib");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(" pib"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testInvalidCharacter()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- HumanReadableBytes.parse("c");
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("c"));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testExtraLargeNumber()
{
- expectedException.expect(ExceptionMatcher.INVALIDFORMAT);
- String extraLarge = Long.MAX_VALUE + "1";
- HumanReadableBytes.parse(extraLarge);
+ final String extraLarge = Long.MAX_VALUE + "1";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(extraLarge));
+ Assertions.assertTrue(exception.getMessage().startsWith(INVALID_FORMAT_PREFIX));
}
@Test
public void testOverflowK()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / 1000 + 1) + "k";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / 1000 + 1) + "k";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowM()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / 1000_000 + 1) + "m";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / 1000_000 + 1) + "m";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowG()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / 1000_000_000L + 1) + "g";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / 1000_000_000L + 1) + "g";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowT()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / 1000_000_000_000L + 1) + "t";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / 1000_000_000_000L + 1) + "t";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowP()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / 1_000_000_000_000_000L + 1) + "p";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / 1_000_000_000_000_000L + 1) + "p";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowKiB()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / 1024 + 1) + "KiB";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / 1024 + 1) + "KiB";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowMiB()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / (1024 * 1024) + 1) + "MiB";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / (1024 * 1024) + 1) + "MiB";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowGiB()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / (1024L * 1024 * 1024) + 1) + "GiB";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / (1024L * 1024 * 1024) + 1) + "GiB";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowTiB()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / (1024L * 1024 * 1024 * 1024) + 1) + "TiB";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / (1024L * 1024 * 1024 * 1024) + 1) + "TiB";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
public void testOverflowPiB()
{
- expectedException.expect(ExceptionMatcher.OVERFLOW);
- String overflow = (Long.MAX_VALUE / (1024L * 1024 * 1024 * 1024 * 1024) + 1) + "PiB";
- HumanReadableBytes.parse(overflow);
+ final String overflow = (Long.MAX_VALUE / (1024L * 1024 * 1024 * 1024 * 1024) + 1) + "PiB";
+ final IAE exception = Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse(overflow));
+ Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}
@Test
@@ -384,15 +343,17 @@ public class HumanReadableBytesTest
HumanReadableBytes bytes = new HumanReadableBytes("5m");
String serialized = mapper.writeValueAsString(bytes);
HumanReadableBytes deserialized = mapper.readValue(serialized, HumanReadableBytes.class);
- Assert.assertEquals(bytes, deserialized);
+ Assertions.assertEquals(bytes, deserialized);
}
@Test
public void testGetInt()
{
- expectedException.expectMessage("Number [2147483648] exceeds range of Integer.MAX_VALUE");
- HumanReadableBytes bytes = new HumanReadableBytes("2GiB");
- bytes.getBytesInInt();
+ final HumanReadableBytes bytes = new HumanReadableBytes("2GiB");
+ final ISE exception = Assertions.assertThrows(ISE.class, bytes::getBytesInInt);
+ Assertions.assertTrue(
+ exception.getMessage().contains("Number [2147483648] exceeds range of Integer.MAX_VALUE")
+ );
}
static class TestBytesRange
@@ -410,108 +371,112 @@ public class HumanReadableBytesTest
public void testBytesRange()
{
String message = validate(new TestBytesRange(HumanReadableBytes.valueOf(-1)));
- Assert.assertEquals("value must be in the range of [0, 5]", message);
+ Assertions.assertEquals("value must be in the range of [0, 5]", message);
message = validate(new TestBytesRange(HumanReadableBytes.valueOf(0)));
- Assert.assertEquals(null, message);
+ Assertions.assertEquals(null, message);
message = validate(new TestBytesRange(HumanReadableBytes.valueOf(5)));
- Assert.assertEquals(null, message);
+ Assertions.assertEquals(null, message);
message = validate(new TestBytesRange(HumanReadableBytes.valueOf(6)));
- Assert.assertEquals("value must be in the range of [0, 5]", message);
+ Assertions.assertEquals("value must be in the range of [0, 5]", message);
}
@Test
public void testFormatInBinaryByte()
{
- Assert.assertEquals("-8.00 EiB", HumanReadableBytes.format(Long.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("-8.000 EiB", HumanReadableBytes.format(Long.MIN_VALUE, 3, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("-8.00 EiB", HumanReadableBytes.format(Long.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("-8.000 EiB", HumanReadableBytes.format(Long.MIN_VALUE, 3, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("-2.00 GiB", HumanReadableBytes.format(Integer.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("-32.00 KiB", HumanReadableBytes.format(Short.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("-2.00 GiB", HumanReadableBytes.format(Integer.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("-32.00 KiB", HumanReadableBytes.format(Short.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("-128 B", HumanReadableBytes.format(Byte.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("-1 B", HumanReadableBytes.format(-1, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("0 B", HumanReadableBytes.format(0, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1 B", HumanReadableBytes.format(1, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("-128 B", HumanReadableBytes.format(Byte.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("-1 B", HumanReadableBytes.format(-1, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("0 B", HumanReadableBytes.format(0, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1 B", HumanReadableBytes.format(1, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.00 KiB", HumanReadableBytes.format(1024L, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.00 MiB", HumanReadableBytes.format(1024L * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.00 GiB", HumanReadableBytes.format(1024L * 1024 * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.00 TiB", HumanReadableBytes.format(1024L * 1024 * 1024 * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.00 PiB", HumanReadableBytes.format(1024L * 1024 * 1024 * 1024 * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("8.00 EiB", HumanReadableBytes.format(Long.MAX_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.00 KiB", HumanReadableBytes.format(1024L, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.00 MiB", HumanReadableBytes.format(1024L * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.00 GiB", HumanReadableBytes.format(1024L * 1024 * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.00 TiB", HumanReadableBytes.format(1024L * 1024 * 1024 * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.00 PiB", HumanReadableBytes.format(1024L * 1024 * 1024 * 1024 * 1024, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("8.00 EiB", HumanReadableBytes.format(Long.MAX_VALUE, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
}
@Test
public void testPrecisionInBinaryFormat()
{
- Assert.assertEquals("1 KiB", HumanReadableBytes.format(1500, 0, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.5 KiB", HumanReadableBytes.format(1500, 1, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.46 KiB", HumanReadableBytes.format(1500, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
- Assert.assertEquals("1.465 KiB", HumanReadableBytes.format(1500, 3, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1 KiB", HumanReadableBytes.format(1500, 0, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.5 KiB", HumanReadableBytes.format(1500, 1, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.46 KiB", HumanReadableBytes.format(1500, 2, HumanReadableBytes.UnitSystem.BINARY_BYTE));
+ Assertions.assertEquals("1.465 KiB", HumanReadableBytes.format(1500, 3, HumanReadableBytes.UnitSystem.BINARY_BYTE));
}
@Test
public void testPrecisionInDecimalFormat()
{
- Assert.assertEquals("1 KB", HumanReadableBytes.format(1456, 0, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.5 KB", HumanReadableBytes.format(1456, 1, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.46 KB", HumanReadableBytes.format(1456, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.456 KB", HumanReadableBytes.format(1456, 3, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1 KB", HumanReadableBytes.format(1456, 0, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.5 KB", HumanReadableBytes.format(1456, 1, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.46 KB", HumanReadableBytes.format(1456, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.456 KB", HumanReadableBytes.format(1456, 3, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
}
@Test
public void testFormatInDecimalByte()
{
- Assert.assertEquals("1 B", HumanReadableBytes.format(1, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.00 KB", HumanReadableBytes.format(1000L, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.00 MB", HumanReadableBytes.format(1000L * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.00 GB", HumanReadableBytes.format(1000L * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.00 TB", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("1.00 PB", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("9.22 EB", HumanReadableBytes.format(Long.MAX_VALUE, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1 B", HumanReadableBytes.format(1, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.00 KB", HumanReadableBytes.format(1000L, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.00 MB", HumanReadableBytes.format(1000L * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.00 GB", HumanReadableBytes.format(1000L * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.00 TB", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("1.00 PB", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("9.22 EB", HumanReadableBytes.format(Long.MAX_VALUE, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("100.00 KB", HumanReadableBytes.format(99999, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("99.999 KB", HumanReadableBytes.format(99999, 3, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("100.00 KB", HumanReadableBytes.format(99999, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("99.999 KB", HumanReadableBytes.format(99999, 3, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("999.9 PB", HumanReadableBytes.format(999_949_999_999_999_999L, 1, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("999.95 PB", HumanReadableBytes.format(999_949_999_999_999_999L, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
- Assert.assertEquals("999.949 PB", HumanReadableBytes.format(999_949_999_999_999_999L, 3, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("999.9 PB", HumanReadableBytes.format(999_949_999_999_999_999L, 1, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("999.95 PB", HumanReadableBytes.format(999_949_999_999_999_999L, 2, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
+ Assertions.assertEquals("999.949 PB", HumanReadableBytes.format(999_949_999_999_999_999L, 3, HumanReadableBytes.UnitSystem.DECIMAL_BYTE));
}
@Test
public void testFormatInDecimal()
{
- Assert.assertEquals("1", HumanReadableBytes.format(1, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("999", HumanReadableBytes.format(999, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("-999", HumanReadableBytes.format(-999, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("-1.00 K", HumanReadableBytes.format(-1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("1.00 K", HumanReadableBytes.format(1000L, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("1.00 M", HumanReadableBytes.format(1000L * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("1.00 G", HumanReadableBytes.format(1000L * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("1.00 T", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("1.00 P", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("-9.22 E", HumanReadableBytes.format(Long.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("9.22 E", HumanReadableBytes.format(Long.MAX_VALUE, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("1", HumanReadableBytes.format(1, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("999", HumanReadableBytes.format(999, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("-999", HumanReadableBytes.format(-999, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("-1.00 K", HumanReadableBytes.format(-1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("1.00 K", HumanReadableBytes.format(1000L, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("1.00 M", HumanReadableBytes.format(1000L * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("1.00 G", HumanReadableBytes.format(1000L * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("1.00 T", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("1.00 P", HumanReadableBytes.format(1000L * 1000 * 1000 * 1000 * 1000, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("-9.22 E", HumanReadableBytes.format(Long.MIN_VALUE, 2, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("9.22 E", HumanReadableBytes.format(Long.MAX_VALUE, 2, HumanReadableBytes.UnitSystem.DECIMAL));
}
@Test
public void testInvalidPrecisionArgumentLowerBound()
{
- expectedException.expect(IAE.class);
- expectedException.expectMessage("precision [-1] must be in the range of [0,3]");
- Assert.assertEquals("1.00", HumanReadableBytes.format(1, -1, HumanReadableBytes.UnitSystem.DECIMAL));
+ final IAE exception = Assertions.assertThrows(
+ IAE.class,
+ () -> HumanReadableBytes.format(1, -1, HumanReadableBytes.UnitSystem.DECIMAL)
+ );
+ Assertions.assertTrue(exception.getMessage().contains("precision [-1] must be in the range of [0,3]"));
}
@Test
public void testInvalidPrecisionArgumentUpperBound()
{
- expectedException.expect(IAE.class);
- expectedException.expectMessage("precision [4] must be in the range of [0,3]");
- Assert.assertEquals("1", HumanReadableBytes.format(1, 3, HumanReadableBytes.UnitSystem.DECIMAL));
- Assert.assertEquals("1", HumanReadableBytes.format(1, 4, HumanReadableBytes.UnitSystem.DECIMAL));
+ Assertions.assertEquals("1", HumanReadableBytes.format(1, 3, HumanReadableBytes.UnitSystem.DECIMAL));
+ final IAE exception = Assertions.assertThrows(
+ IAE.class,
+ () -> HumanReadableBytes.format(1, 4, HumanReadableBytes.UnitSystem.DECIMAL)
+ );
+ Assertions.assertTrue(exception.getMessage().contains("precision [4] must be in the range of [0,3]"));
}
private static <T> String validate(T obj)
diff --git a/processing/src/test/java/org/apache/druid/java/util/common/RetryUtilsTest.java b/processing/src/test/java/org/apache/druid/java/util/common/RetryUtilsTest.java
index 4d267ba4c54..322bebb7cc3 100644
--- a/processing/src/test/java/org/apache/druid/java/util/common/RetryUtilsTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/common/RetryUtilsTest.java
@@ -60,7 +60,7 @@ public class RetryUtilsTest
public void testEventualFailure() throws Exception
{
final AtomicInteger count = new AtomicInteger();
- boolean threwExpectedException = false;
+ boolean threwExpectedError = false;
try {
RetryUtils.retry(
() -> {
@@ -72,9 +72,9 @@ public class RetryUtilsTest
);
}
catch (IOException e) {
- threwExpectedException = e.getMessage().equals("what");
+ threwExpectedError = e.getMessage().equals("what");
}
- Assertions.assertTrue(threwExpectedException, "threw expected exception");
+ Assertions.assertTrue(threwExpectedError, "threw expected exception");
Assertions.assertEquals(2, count.get(), "count");
}
diff --git a/processing/src/test/java/org/apache/druid/java/util/common/StringUtilsTest.java b/processing/src/test/java/org/apache/druid/java/util/common/StringUtilsTest.java
index 5927207ba08..8a7c69fd46c 100644
--- a/processing/src/test/java/org/apache/druid/java/util/common/StringUtilsTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/common/StringUtilsTest.java
@@ -21,10 +21,8 @@ package org.apache.druid.java.util.common;
import com.google.common.collect.ImmutableList;
import org.apache.druid.collections.ResourceHolder;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.nio.BufferUnderflowException;
@@ -54,17 +52,14 @@ public class StringUtilsTest
"fox"
);
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
public void fromUtf8ConversionTest() throws UnsupportedEncodingException
{
byte[] bytes = new byte[]{'a', 'b', 'c', 'd'};
- Assert.assertEquals("abcd", StringUtils.fromUtf8(bytes));
+ Assertions.assertEquals("abcd", StringUtils.fromUtf8(bytes));
String abcd = "abcd";
- Assert.assertEquals(abcd, StringUtils.fromUtf8(abcd.getBytes(StringUtils.UTF8_STRING)));
+ Assertions.assertEquals(abcd, StringUtils.fromUtf8(abcd.getBytes(StringUtils.UTF8_STRING)));
}
@Test
@@ -73,7 +68,7 @@ public class StringUtilsTest
byte[] bytes = new byte[]{'a', 'b', 'c', 'd'};
byte[] strBytes = StringUtils.toUtf8("abcd");
for (int i = 0; i < bytes.length; ++i) {
- Assert.assertEquals(bytes[i], strBytes[i]);
+ Assertions.assertEquals(bytes[i], strBytes[i]);
}
}
@@ -85,31 +80,31 @@ public class StringUtilsTest
final ByteBuffer bigBuffer = ByteBuffer.allocate(8);
final int smallBufferResult = StringUtils.toUtf8WithLimit("🚀🌔", smallBuffer);
- Assert.assertEquals(4, smallBufferResult);
+ Assertions.assertEquals(4, smallBufferResult);
final byte[] smallBufferByteArray = new byte[smallBufferResult];
smallBuffer.get(smallBufferByteArray);
- Assert.assertEquals("🚀", StringUtils.fromUtf8(smallBufferByteArray));
+ Assertions.assertEquals("🚀", StringUtils.fromUtf8(smallBufferByteArray));
final int mediumBufferResult = StringUtils.toUtf8WithLimit("🚀🌔", mediumBuffer);
- Assert.assertEquals(4, mediumBufferResult);
+ Assertions.assertEquals(4, mediumBufferResult);
final byte[] mediumBufferByteArray = new byte[mediumBufferResult];
mediumBuffer.get(mediumBufferByteArray);
- Assert.assertEquals("🚀", StringUtils.fromUtf8(mediumBufferByteArray));
+ Assertions.assertEquals("🚀", StringUtils.fromUtf8(mediumBufferByteArray));
final int bigBufferResult = StringUtils.toUtf8WithLimit("🚀🌔", bigBuffer);
- Assert.assertEquals(8, bigBufferResult);
+ Assertions.assertEquals(8, bigBufferResult);
final byte[] bigBufferByteArray = new byte[bigBufferResult];
bigBuffer.get(bigBufferByteArray);
- Assert.assertEquals("🚀🌔", StringUtils.fromUtf8(bigBufferByteArray));
+ Assertions.assertEquals("🚀🌔", StringUtils.fromUtf8(bigBufferByteArray));
}
@Test
public void fromUtf8ByteBufferHeap()
{
ByteBuffer bytes = ByteBuffer.wrap(new byte[]{'a', 'b', 'c', 'd'});
- Assert.assertEquals("abcd", StringUtils.fromUtf8(bytes, 4));
+ Assertions.assertEquals("abcd", StringUtils.fromUtf8(bytes, 4));
bytes.rewind();
- Assert.assertEquals("abcd", StringUtils.fromUtf8(bytes));
+ Assertions.assertEquals("abcd", StringUtils.fromUtf8(bytes));
}
@Test
@@ -117,30 +112,30 @@ public class StringUtilsTest
{
ByteBuffer bytes = ByteBuffer.wrap(new byte[]{'a', 'b', 'c', 'd'});
bytes.position(1).limit(3);
- Assert.assertEquals("bc", StringUtils.fromUtf8(bytes, 2));
+ Assertions.assertEquals("bc", StringUtils.fromUtf8(bytes, 2));
bytes.position(1);
- Assert.assertEquals("bc", StringUtils.fromUtf8(bytes));
+ Assertions.assertEquals("bc", StringUtils.fromUtf8(bytes));
}
- @Test(expected = BufferUnderflowException.class)
+ @Test
public void testOutOfBounds()
{
ByteBuffer bytes = ByteBuffer.wrap(new byte[]{'a', 'b', 'c', 'd'});
bytes.position(1).limit(3);
- StringUtils.fromUtf8(bytes, 3);
+ Assertions.assertThrows(BufferUnderflowException.class, () -> StringUtils.fromUtf8(bytes, 3));
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testNullPointerByteBuffer()
{
- StringUtils.fromUtf8((ByteBuffer) null);
+ Assertions.assertThrows(NullPointerException.class, () -> StringUtils.fromUtf8((ByteBuffer) null));
}
- @Test(expected = NullPointerException.class)
+ @Test
public void testNullPointerByteArray()
{
- StringUtils.fromUtf8((byte[]) null);
+ Assertions.assertThrows(NullPointerException.class, () -> StringUtils.fromUtf8((byte[]) null));
}
@Test
@@ -150,9 +145,9 @@ public class StringUtilsTest
final ByteBuffer bytes = bufferHolder.get();
bytes.put(new byte[]{'a', 'b', 'c', 'd'});
bytes.rewind();
- Assert.assertEquals("abcd", StringUtils.fromUtf8(bytes, 4));
+ Assertions.assertEquals("abcd", StringUtils.fromUtf8(bytes, 4));
bytes.rewind();
- Assert.assertEquals("abcd", StringUtils.fromUtf8(bytes));
+ Assertions.assertEquals("abcd", StringUtils.fromUtf8(bytes));
}
}
@@ -160,155 +155,161 @@ public class StringUtilsTest
@Test
public void testNonStrictFormat()
{
- Assert.assertEquals("test%d; format", StringUtils.nonStrictFormat("test%d", "format"));
- Assert.assertEquals("test%s%s; format", StringUtils.nonStrictFormat("test%s%s", "format"));
+ Assertions.assertEquals("test%d; format", StringUtils.nonStrictFormat("test%d", "format"));
+ Assertions.assertEquals(
+ "test%s%s; format",
+ // codeql[java/missing-format-argument]
+ StringUtils.nonStrictFormat("test%s%s", "format")
+ );
}
@Test
public void testRemoveChar()
{
- Assert.assertEquals("123", StringUtils.removeChar("123", ','));
- Assert.assertEquals("123", StringUtils.removeChar("123,", ','));
- Assert.assertEquals("123", StringUtils.removeChar(",1,,2,3,", ','));
- Assert.assertEquals("", StringUtils.removeChar(",,", ','));
+ Assertions.assertEquals("123", StringUtils.removeChar("123", ','));
+ Assertions.assertEquals("123", StringUtils.removeChar("123,", ','));
+ Assertions.assertEquals("123", StringUtils.removeChar(",1,,2,3,", ','));
+ Assertions.assertEquals("", StringUtils.removeChar(",,", ','));
}
@Test
public void testReplaceChar()
{
- Assert.assertEquals("123", StringUtils.replaceChar("123", ',', "x"));
- Assert.assertEquals("12345", StringUtils.replaceChar("123,", ',', "45"));
- Assert.assertEquals("", StringUtils.replaceChar("", 'a', "bb"));
- Assert.assertEquals("bb", StringUtils.replaceChar("a", 'a', "bb"));
- Assert.assertEquals("bbbb", StringUtils.replaceChar("aa", 'a', "bb"));
+ Assertions.assertEquals("123", StringUtils.replaceChar("123", ',', "x"));
+ Assertions.assertEquals("12345", StringUtils.replaceChar("123,", ',', "45"));
+ Assertions.assertEquals("", StringUtils.replaceChar("", 'a', "bb"));
+ Assertions.assertEquals("bb", StringUtils.replaceChar("a", 'a', "bb"));
+ Assertions.assertEquals("bbbb", StringUtils.replaceChar("aa", 'a', "bb"));
}
@Test
public void testReplace()
{
- Assert.assertEquals("x1x2x3x", StringUtils.replace("123", "", "x"));
- Assert.assertEquals("12345", StringUtils.replace("123,", ",", "45"));
- Assert.assertEquals("", StringUtils.replace("", "a", "bb"));
- Assert.assertEquals("bb", StringUtils.replace("a", "a", "bb"));
- Assert.assertEquals("bba", StringUtils.replace("aaa", "aa", "bb"));
- Assert.assertEquals("bcb", StringUtils.replace("aacaa", "aa", "b"));
- Assert.assertEquals("bb", StringUtils.replace("aaaa", "aa", "b"));
- Assert.assertEquals("", StringUtils.replace("aaaa", "aa", ""));
+ Assertions.assertEquals("x1x2x3x", StringUtils.replace("123", "", "x"));
+ Assertions.assertEquals("12345", StringUtils.replace("123,", ",", "45"));
+ Assertions.assertEquals("", StringUtils.replace("", "a", "bb"));
+ Assertions.assertEquals("bb", StringUtils.replace("a", "a", "bb"));
+ Assertions.assertEquals("bba", StringUtils.replace("aaa", "aa", "bb"));
+ Assertions.assertEquals("bcb", StringUtils.replace("aacaa", "aa", "b"));
+ Assertions.assertEquals("bb", StringUtils.replace("aaaa", "aa", "b"));
+ Assertions.assertEquals("", StringUtils.replace("aaaa", "aa", ""));
}
@Test
public void testEncodeForFormat()
{
- Assert.assertEquals("x %% a %%s", StringUtils.encodeForFormat("x % a %s"));
- Assert.assertEquals("", StringUtils.encodeForFormat(""));
- Assert.assertNull(StringUtils.encodeForFormat(null));
+ Assertions.assertEquals("x %% a %%s", StringUtils.encodeForFormat("x % a %s"));
+ Assertions.assertEquals("", StringUtils.encodeForFormat(""));
+ Assertions.assertNull(StringUtils.encodeForFormat(null));
}
@Test
public void testURLEncodeSpace()
{
String s1 = StringUtils.urlEncode("aaa bbb");
- Assert.assertEquals(s1, "aaa%20bbb");
- Assert.assertEquals("aaa bbb", StringUtils.urlDecode(s1));
+ Assertions.assertEquals(s1, "aaa%20bbb");
+ Assertions.assertEquals("aaa bbb", StringUtils.urlDecode(s1));
String s2 = StringUtils.urlEncode("fff+ggg");
- Assert.assertEquals(s2, "fff%2Bggg");
- Assert.assertEquals("fff+ggg", StringUtils.urlDecode(s2));
+ Assertions.assertEquals(s2, "fff%2Bggg");
+ Assertions.assertEquals("fff+ggg", StringUtils.urlDecode(s2));
}
@Test
public void testRepeat()
{
- Assert.assertEquals("", StringUtils.repeat("foo", 0));
- Assert.assertEquals("foo", StringUtils.repeat("foo", 1));
- Assert.assertEquals("foofoofoo", StringUtils.repeat("foo", 3));
+ Assertions.assertEquals("", StringUtils.repeat("foo", 0));
+ Assertions.assertEquals("foo", StringUtils.repeat("foo", 1));
+ Assertions.assertEquals("foofoofoo", StringUtils.repeat("foo", 3));
- Assert.assertEquals("", StringUtils.repeat("", 0));
- Assert.assertEquals("", StringUtils.repeat("", 1));
- Assert.assertEquals("", StringUtils.repeat("", 3));
+ Assertions.assertEquals("", StringUtils.repeat("", 0));
+ Assertions.assertEquals("", StringUtils.repeat("", 1));
+ Assertions.assertEquals("", StringUtils.repeat("", 3));
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("count is negative, -1");
- Assert.assertEquals("", StringUtils.repeat("foo", -1));
+ final IllegalArgumentException exception = Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> StringUtils.repeat("foo", -1)
+ );
+ Assertions.assertTrue(exception.getMessage().contains("count is negative, -1"));
}
@Test
public void testLpad()
{
String lpad = StringUtils.lpad("abc", 7, "de");
- Assert.assertEquals("dedeabc", lpad);
+ Assertions.assertEquals("dedeabc", lpad);
lpad = StringUtils.lpad("abc", 6, "de");
- Assert.assertEquals("dedabc", lpad);
+ Assertions.assertEquals("dedabc", lpad);
lpad = StringUtils.lpad("abc", 2, "de");
- Assert.assertEquals("ab", lpad);
+ Assertions.assertEquals("ab", lpad);
lpad = StringUtils.lpad("abc", 0, "de");
- Assert.assertEquals("", lpad);
+ Assertions.assertEquals("", lpad);
lpad = StringUtils.lpad("abc", -1, "de");
- Assert.assertEquals("", lpad);
+ Assertions.assertEquals("", lpad);
lpad = StringUtils.lpad("abc", 10, "");
- Assert.assertEquals("abc", lpad);
+ Assertions.assertEquals("abc", lpad);
lpad = StringUtils.lpad("abc", 1, "");
- Assert.assertEquals("a", lpad);
+ Assertions.assertEquals("a", lpad);
}
@Test
public void testRpad()
{
String rpad = StringUtils.rpad("abc", 7, "de");
- Assert.assertEquals("abcdede", rpad);
+ Assertions.assertEquals("abcdede", rpad);
rpad = StringUtils.rpad("abc", 6, "de");
- Assert.assertEquals("abcded", rpad);
+ Assertions.assertEquals("abcded", rpad);
rpad = StringUtils.rpad("abc", 2, "de");
- Assert.assertEquals("ab", rpad);
+ Assertions.assertEquals("ab", rpad);
rpad = StringUtils.rpad("abc", 0, "de");
- Assert.assertEquals("", rpad);
+ Assertions.assertEquals("", rpad);
rpad = StringUtils.rpad("abc", -1, "de");
- Assert.assertEquals("", rpad);
+ Assertions.assertEquals("", rpad);
rpad = StringUtils.rpad("abc", 10, "");
- Assert.assertEquals("abc", rpad);
+ Assertions.assertEquals("abc", rpad);
rpad = StringUtils.rpad("abc", 1, "");
- Assert.assertEquals("a", rpad);
+ Assertions.assertEquals("a", rpad);
}
@Test
public void testChop()
{
- Assert.assertEquals("foo", StringUtils.chop("foo", 5));
- Assert.assertEquals("fo", StringUtils.chop("foo", 2));
- Assert.assertEquals("", StringUtils.chop("foo", 0));
- Assert.assertEquals("smile 🙂 for", StringUtils.chop("smile 🙂 for the camera", 14));
- Assert.assertEquals("smile 🙂", StringUtils.chop("smile 🙂 for the camera", 10));
- Assert.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 9));
- Assert.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 8));
- Assert.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 7));
- Assert.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 6));
- Assert.assertEquals("smile", StringUtils.chop("smile 🙂 for the camera", 5));
+ Assertions.assertEquals("foo", StringUtils.chop("foo", 5));
+ Assertions.assertEquals("fo", StringUtils.chop("foo", 2));
+ Assertions.assertEquals("", StringUtils.chop("foo", 0));
+ Assertions.assertEquals("smile 🙂 for", StringUtils.chop("smile 🙂 for the camera", 14));
+ Assertions.assertEquals("smile 🙂", StringUtils.chop("smile 🙂 for the camera", 10));
+ Assertions.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 9));
+ Assertions.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 8));
+ Assertions.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 7));
+ Assertions.assertEquals("smile ", StringUtils.chop("smile 🙂 for the camera", 6));
+ Assertions.assertEquals("smile", StringUtils.chop("smile 🙂 for the camera", 5));
}
@Test
public void testFastLooseChop()
{
- Assert.assertEquals("foo", StringUtils.fastLooseChop("foo", 5));
- Assert.assertEquals("fo", StringUtils.fastLooseChop("foo", 2));
- Assert.assertEquals("", StringUtils.fastLooseChop("foo", 0));
- Assert.assertEquals("smile 🙂 for", StringUtils.fastLooseChop("smile 🙂 for the camera", 12));
- Assert.assertEquals("smile 🙂 ", StringUtils.fastLooseChop("smile 🙂 for the camera", 9));
- Assert.assertEquals("smile 🙂", StringUtils.fastLooseChop("smile 🙂 for the camera", 8));
- Assert.assertEquals("smile \uD83D", StringUtils.fastLooseChop("smile 🙂 for the camera", 7));
- Assert.assertEquals("smile ", StringUtils.fastLooseChop("smile 🙂 for the camera", 6));
- Assert.assertEquals("smile", StringUtils.fastLooseChop("smile 🙂 for the camera", 5));
+ Assertions.assertEquals("foo", StringUtils.fastLooseChop("foo", 5));
+ Assertions.assertEquals("fo", StringUtils.fastLooseChop("foo", 2));
+ Assertions.assertEquals("", StringUtils.fastLooseChop("foo", 0));
+ Assertions.assertEquals("smile 🙂 for", StringUtils.fastLooseChop("smile 🙂 for the camera", 12));
+ Assertions.assertEquals("smile 🙂 ", StringUtils.fastLooseChop("smile 🙂 for the camera", 9));
+ Assertions.assertEquals("smile 🙂", StringUtils.fastLooseChop("smile 🙂 for the camera", 8));
+ Assertions.assertEquals("smile \uD83D", StringUtils.fastLooseChop("smile 🙂 for the camera", 7));
+ Assertions.assertEquals("smile ", StringUtils.fastLooseChop("smile 🙂 for the camera", 6));
+ Assertions.assertEquals("smile", StringUtils.fastLooseChop("smile 🙂 for the camera", 5));
}
@Test
@@ -322,14 +323,14 @@ public class StringUtilsTest
StringUtils.toUtf8(string2)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
+ (int) Math.signum(compareUtf8),
+ (int) Math.signum(compareUnicode),
StringUtils.format(
"compareUnicode (actual) matches compareUtf8 (expected) for [%s] vs [%s]",
string1,
string2
- ),
- (int) Math.signum(compareUtf8),
- (int) Math.signum(compareUnicode)
+ )
);
}
}
@@ -362,26 +363,26 @@ public class StringUtilsTest
utf8Bytes2.length
);
- Assert.assertEquals(
+ Assertions.assertEquals(
+ (int) Math.signum(compareJavaString),
+ (int) Math.signum(compareByteArrayUtf8UsingJavaStringOrdering),
StringUtils.format(
"compareUtf8UsingJavaStringOrdering(byte[]) (actual) "
+ "matches compareJavaString (expected) for [%s] vs [%s]",
string1,
string2
- ),
- (int) Math.signum(compareJavaString),
- (int) Math.signum(compareByteArrayUtf8UsingJavaStringOrdering)
+ )
);
- Assert.assertEquals(
+ Assertions.assertEquals(
+ (int) Math.signum(compareJavaString),
+ (int) Math.signum(compareByteBufferUtf8UsingJavaStringOrdering),
StringUtils.format(
"compareByteBufferUtf8UsingJavaStringOrdering(ByteBuffer) (actual) "
+ "matches compareJavaString (expected) for [%s] vs [%s]",
string1,
string2
- ),
- (int) Math.signum(compareJavaString),
- (int) Math.signum(compareByteBufferUtf8UsingJavaStringOrdering)
+ )
);
}
}
@@ -390,13 +391,13 @@ public class StringUtilsTest
@Test()
public void testNonStrictFormatWithNullMessage()
{
- Assert.assertThrows(NullPointerException.class, () -> StringUtils.nonStrictFormat(null, 1, 2));
+ Assertions.assertThrows(NullPointerException.class, () -> StringUtils.nonStrictFormat(null, 1, 2));
}
@Test
public void testNonStrictFormatWithStringContainingPercent()
{
- Assert.assertEquals(
+ Assertions.assertEquals(
"some string containing % %s %d %f",
StringUtils.nonStrictFormat("%s", "some string containing % %s %d %f")
);
diff --git a/processing/src/test/java/org/apache/druid/java/util/common/guava/ParallelMergeCombiningSequenceTest.java b/processing/src/test/java/org/apache/druid/java/util/common/guava/ParallelMergeCombiningSequenceTest.java
index 6e3881a5292..adb1f24ea51 100644
--- a/processing/src/test/java/org/apache/druid/java/util/common/guava/ParallelMergeCombiningSequenceTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/common/guava/ParallelMergeCombiningSequenceTest.java
@@ -25,10 +25,10 @@ import org.apache.druid.java.util.common.Pair;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.query.QueryTimeoutException;
import org.apache.druid.utils.JvmUtils;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
@@ -62,7 +62,7 @@ public class ParallelMergeCombiningSequenceTest
private ForkJoinPool pool;
- @Before
+ @BeforeEach
public void setup()
{
pool = new ForkJoinPool(
@@ -73,7 +73,7 @@ public class ParallelMergeCombiningSequenceTest
);
}
- @After
+ @AfterEach
public void teardown()
{
pool.shutdown();
@@ -94,8 +94,8 @@ public class ParallelMergeCombiningSequenceTest
IntPair prev = null;
while (!rawYielder.isDone() && !cursor.isDone()) {
- Assert.assertEquals(rawYielder.get(), cursor.get());
- Assert.assertNotEquals(cursor.get(), prev);
+ Assertions.assertEquals(rawYielder.get(), cursor.get());
+ Assertions.assertNotEquals(cursor.get(), prev);
prev = cursor.get();
rawYielder = rawYielder.next(rawYielder.get());
cursor.advance();
@@ -127,8 +127,8 @@ public class ParallelMergeCombiningSequenceTest
new ParallelMergeCombiningSequence.ResultBatch<>(batchSize);
int batchCounter = 0;
while (!rawYielder.isDone() && !cursor.isDone()) {
- Assert.assertEquals(rawYielder.get(), cursor.get());
- Assert.assertNotEquals(cursor.get(), prev);
+ Assertions.assertEquals(rawYielder.get(), cursor.get());
+ Assertions.assertNotEquals(cursor.get(), prev);
prev = cursor.get();
currentBatch.add(prev);
batchCounter++;
@@ -160,8 +160,8 @@ public class ParallelMergeCombiningSequenceTest
Yielder<IntPair> queueYielder = Yielders.each(queueAsSequence);
while (!rawYielder.isDone() && !queueYielder.isDone()) {
- Assert.assertEquals(rawYielder.get(), queueYielder.get());
- Assert.assertNotEquals(queueYielder.get(), prev);
+ Assertions.assertEquals(rawYielder.get(), queueYielder.get());
+ Assertions.assertNotEquals(queueYielder.get(), prev);
prev = queueYielder.get();
rawYielder = rawYielder.next(rawYielder.get());
queueYielder = queueYielder.next(queueYielder.get());
@@ -195,8 +195,8 @@ public class ParallelMergeCombiningSequenceTest
new ParallelMergeCombiningSequence.ResultBatch<>(batchSize);
int batchCounter = 0;
while (!rawYielder.isDone() && !cursor.isDone()) {
- Assert.assertEquals(rawYielder.get(), cursor.get());
- Assert.assertNotEquals(cursor.get(), prev);
+ Assertions.assertEquals(rawYielder.get(), cursor.get());
+ Assertions.assertNotEquals(cursor.get(), prev);
prev = cursor.get();
currentBatch.add(prev);
batchCounter++;
@@ -230,8 +230,8 @@ public class ParallelMergeCombiningSequenceTest
queueCursor.initialize();
prev = null;
while (!rawYielder.isDone() && !queueCursor.isDone()) {
- Assert.assertEquals(rawYielder.get(), queueCursor.get());
- Assert.assertNotEquals(queueCursor.get(), prev);
+ Assertions.assertEquals(rawYielder.get(), queueCursor.get());
+ Assertions.assertNotEquals(queueCursor.get(), prev);
prev = queueCursor.get();
rawYielder = rawYielder.next(rawYielder.get());
queueCursor.advance();
@@ -298,11 +298,11 @@ public class ParallelMergeCombiningSequenceTest
(t, e) -> LOG.error(e, "Unhandled exception in thread [%s]", t),
true
);
- Throwable t = Assert.assertThrows(
+ Throwable t = Assertions.assertThrows(
QueryTimeoutException.class,
() -> assertResultWithCustomPool(input, 10, 20, reportMetrics -> {}, customBadPool)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
"Query did not complete within configured timeout period. You can increase query timeout or tune the performance of query.",
t.getMessage()
);
@@ -317,12 +317,12 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(5));
input.add(nonBlockingSequence(6));
assertResult(input, 10, 20, reportMetrics -> {
- Assert.assertEquals(1, reportMetrics.getParallelism());
- Assert.assertEquals(2, reportMetrics.getInputSequences());
- Assert.assertEquals(11, reportMetrics.getInputRows());
+ Assertions.assertEquals(1, reportMetrics.getParallelism());
+ Assertions.assertEquals(2, reportMetrics.getInputSequences());
+ Assertions.assertEquals(11, reportMetrics.getInputRows());
// deltas because it depends how much result combining is happening, which is random
- Assert.assertEquals(6, reportMetrics.getOutputRows(), 5);
- Assert.assertEquals(4, reportMetrics.getTaskCount());
+ Assertions.assertEquals(6, reportMetrics.getOutputRows(), 5);
+ Assertions.assertEquals(4, reportMetrics.getTaskCount());
});
input.clear();
@@ -335,12 +335,12 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(4));
input.add(nonBlockingSequence(6));
assertResult(input, 10, 20, reportMetrics -> {
- Assert.assertEquals(2, reportMetrics.getParallelism());
- Assert.assertEquals(6, reportMetrics.getInputSequences());
- Assert.assertEquals(34, reportMetrics.getInputRows());
+ Assertions.assertEquals(2, reportMetrics.getParallelism());
+ Assertions.assertEquals(6, reportMetrics.getInputSequences());
+ Assertions.assertEquals(34, reportMetrics.getInputRows());
// deltas because it depends how much result combining is happening, which is random
- Assert.assertEquals(16, reportMetrics.getOutputRows(), 15);
- Assert.assertEquals(10, reportMetrics.getTaskCount(), 2);
+ Assertions.assertEquals(16, reportMetrics.getOutputRows(), 15);
+ Assertions.assertEquals(10, reportMetrics.getTaskCount(), 2);
});
}
@@ -352,12 +352,12 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(5));
input.add(nonBlockingSequence(6));
assertResult(input, 4, 20, reportMetrics -> {
- Assert.assertEquals(1, reportMetrics.getParallelism());
- Assert.assertEquals(2, reportMetrics.getInputSequences());
- Assert.assertEquals(11, reportMetrics.getInputRows());
+ Assertions.assertEquals(1, reportMetrics.getParallelism());
+ Assertions.assertEquals(2, reportMetrics.getInputSequences());
+ Assertions.assertEquals(11, reportMetrics.getInputRows());
// deltas because it depends how much result combining is happening, which is random
- Assert.assertEquals(6, reportMetrics.getOutputRows(), 5);
- Assert.assertEquals(4, reportMetrics.getTaskCount());
+ Assertions.assertEquals(6, reportMetrics.getOutputRows(), 5);
+ Assertions.assertEquals(4, reportMetrics.getTaskCount());
});
input.clear();
@@ -370,12 +370,12 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(4));
input.add(nonBlockingSequence(6));
assertResult(input, 4, 20, reportMetrics -> {
- Assert.assertEquals(2, reportMetrics.getParallelism());
- Assert.assertEquals(6, reportMetrics.getInputSequences());
- Assert.assertEquals(34, reportMetrics.getInputRows());
+ Assertions.assertEquals(2, reportMetrics.getParallelism());
+ Assertions.assertEquals(6, reportMetrics.getInputSequences());
+ Assertions.assertEquals(34, reportMetrics.getInputRows());
// deltas because it depends how much result combining is happening, which is random
- Assert.assertEquals(16, reportMetrics.getOutputRows(), 15);
- Assert.assertEquals(10, reportMetrics.getTaskCount(), 2);
+ Assertions.assertEquals(16, reportMetrics.getOutputRows(), 15);
+ Assertions.assertEquals(10, reportMetrics.getTaskCount(), 2);
});
}
@@ -389,12 +389,12 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(26));
assertResult(input, 5, 10, reportMetrics -> {
- Assert.assertEquals(1, reportMetrics.getParallelism());
- Assert.assertEquals(2, reportMetrics.getInputSequences());
- Assert.assertEquals(41, reportMetrics.getInputRows());
+ Assertions.assertEquals(1, reportMetrics.getParallelism());
+ Assertions.assertEquals(2, reportMetrics.getInputSequences());
+ Assertions.assertEquals(41, reportMetrics.getInputRows());
// deltas because it depends how much result combining is happening, which is random
- Assert.assertEquals(21, reportMetrics.getOutputRows(), 20);
- Assert.assertEquals(4, reportMetrics.getTaskCount(), 2);
+ Assertions.assertEquals(21, reportMetrics.getOutputRows(), 20);
+ Assertions.assertEquals(4, reportMetrics.getTaskCount(), 2);
});
// above min sequence count threshold, so will merge in parallel (if enough cores)
@@ -404,12 +404,12 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(14));
assertResult(input, 5, 10, reportMetrics -> {
- Assert.assertEquals(2, reportMetrics.getParallelism());
- Assert.assertEquals(6, reportMetrics.getInputSequences());
- Assert.assertEquals(120, reportMetrics.getInputRows());
+ Assertions.assertEquals(2, reportMetrics.getParallelism());
+ Assertions.assertEquals(6, reportMetrics.getInputSequences());
+ Assertions.assertEquals(120, reportMetrics.getInputRows());
// deltas because it depends how much result combining is happening, which is random
- Assert.assertEquals(60, reportMetrics.getOutputRows(), 59);
- Assert.assertEquals(10, reportMetrics.getTaskCount(), 5);
+ Assertions.assertEquals(60, reportMetrics.getOutputRows(), 59);
+ Assertions.assertEquals(10, reportMetrics.getTaskCount(), 5);
});
}
@@ -440,9 +440,9 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(9_001));
assertResult(input, 128, 1024, reportMetrics -> {
- Assert.assertEquals(1, reportMetrics.getParallelism());
- Assert.assertEquals(2, reportMetrics.getInputSequences());
- Assert.assertEquals(19_001, reportMetrics.getInputRows());
+ Assertions.assertEquals(1, reportMetrics.getParallelism());
+ Assertions.assertEquals(2, reportMetrics.getInputSequences());
+ Assertions.assertEquals(19_001, reportMetrics.getInputRows());
});
input.add(nonBlockingSequence(7_777));
@@ -451,9 +451,9 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(8_888));
assertResult(input, 128, 1024, reportMetrics -> {
- Assert.assertEquals(2, reportMetrics.getParallelism());
- Assert.assertEquals(6, reportMetrics.getInputSequences());
- Assert.assertEquals(49166, reportMetrics.getInputRows());
+ Assertions.assertEquals(2, reportMetrics.getParallelism());
+ Assertions.assertEquals(6, reportMetrics.getInputSequences());
+ Assertions.assertEquals(49166, reportMetrics.getInputRows());
});
}
@@ -465,10 +465,10 @@ public class ParallelMergeCombiningSequenceTest
input.add(explodingSequence(15));
input.add(nonBlockingSequence(25));
- Throwable t = Assert.assertThrows(RuntimeException.class, () -> assertException(input));
- Assert.assertEquals("exploded", t.getMessage());
- Assert.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Throwable t = Assertions.assertThrows(RuntimeException.class, () -> assertException(input));
+ Assertions.assertEquals("exploded", t.getMessage());
+ Assertions.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
}
@Test
@@ -480,10 +480,10 @@ public class ParallelMergeCombiningSequenceTest
input.add(explodingSequence(11));
input.add(nonBlockingSequence(12));
- Throwable t = Assert.assertThrows(RuntimeException.class, () -> assertException(input));
- Assert.assertEquals("exploded", t.getMessage());
- Assert.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Throwable t = Assertions.assertThrows(RuntimeException.class, () -> assertException(input));
+ Assertions.assertEquals("exploded", t.getMessage());
+ Assertions.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
}
@Test
@@ -495,10 +495,10 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(2));
input.add(nonBlockingSequence(2));
- Throwable t = Assert.assertThrows(RuntimeException.class, () -> assertException(input));
- Assert.assertEquals("exploded", t.getMessage());
- Assert.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Throwable t = Assertions.assertThrows(RuntimeException.class, () -> assertException(input));
+ Assertions.assertEquals("exploded", t.getMessage());
+ Assertions.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
}
@Test
@@ -512,10 +512,10 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(2));
input.add(nonBlockingSequence(2));
- Throwable t = Assert.assertThrows(RuntimeException.class, () -> assertException(input));
- Assert.assertEquals("exploded", t.getMessage());
- Assert.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Throwable t = Assertions.assertThrows(RuntimeException.class, () -> assertException(input));
+ Assertions.assertEquals("exploded", t.getMessage());
+ Assertions.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
}
@Test
@@ -528,7 +528,7 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(someSize));
input.add(blockingSequence(someSize, 400, 500, 1, 500, true));
- Throwable t = Assert.assertThrows(
+ Throwable t = Assertions.assertThrows(
QueryTimeoutException.class,
() -> assertException(
input,
@@ -538,7 +538,7 @@ public class ParallelMergeCombiningSequenceTest
0
)
);
- Assert.assertEquals("Query did not complete within configured timeout period. " +
+ Assertions.assertEquals("Query did not complete within configured timeout period. " +
"You can increase query timeout or tune the performance of query.", t.getMessage());
@@ -550,9 +550,9 @@ public class ParallelMergeCombiningSequenceTest
// isQuiescent() correctly returns false until the blocked worker wakes up and exits —
// the assertion would time out for long-sleeping sequences.
if (JvmUtils.majorVersion() >= 20 && JvmUtils.majorVersion() < 25) {
- Assert.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
// good result, we want the pool to always be idle if an exception occurred during processing
- Assert.assertTrue(pool.isQuiescent());
+ Assertions.assertTrue(pool.isQuiescent());
}
}
@@ -566,11 +566,11 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(someSize, true));
input.add(nonBlockingSequence(someSize, true));
- Throwable t = Assert.assertThrows(QueryTimeoutException.class, () -> assertException(input, 8, 64, 1000, 1500));
- Assert.assertEquals("Query did not complete within configured timeout period. " +
+ Throwable t = Assertions.assertThrows(QueryTimeoutException.class, () -> assertException(input, 8, 64, 1000, 1500));
+ Assertions.assertEquals("Query did not complete within configured timeout period. " +
"You can increase query timeout or tune the performance of query.", t.getMessage());
- Assert.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Assertions.assertTrue(pool.awaitQuiescence(1, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
}
@Test
@@ -605,22 +605,22 @@ public class ParallelMergeCombiningSequenceTest
reporter.future = parallelMergeCombineSequence.getCancellationFuture();
reporter.yielder = parallelMergeCombineYielder;
reporter.yielder = parallelMergeCombineYielder.next(null);
- Assert.assertFalse(parallelMergeCombineYielder.isDone());
+ Assertions.assertFalse(parallelMergeCombineYielder.isDone());
reporters.add(reporter);
}
// sleep until timeout
Thread.sleep(timeout);
- Assert.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
- Assert.assertFalse(pool.hasQueuedSubmissions());
+ Assertions.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
+ Assertions.assertFalse(pool.hasQueuedSubmissions());
for (TestingReporter reporter : reporters) {
- Assert.assertThrows(QueryTimeoutException.class, () -> reporter.yielder.next(null));
- Assert.assertTrue(reporter.future.isCancelled());
- Assert.assertTrue(reporter.future.getCancellationGizmo().isCanceled());
+ Assertions.assertThrows(QueryTimeoutException.class, () -> reporter.yielder.next(null));
+ Assertions.assertTrue(reporter.future.isCancelled());
+ Assertions.assertTrue(reporter.future.getCancellationGizmo().isCanceled());
}
- Assert.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Assertions.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
}
@Test
@@ -654,7 +654,7 @@ public class ParallelMergeCombiningSequenceTest
reporter.future = parallelMergeCombineSequence.getCancellationFuture();
reporter.yielder = parallelMergeCombineYielder;
parallelMergeCombineYielder.next(null);
- Assert.assertFalse(parallelMergeCombineYielder.isDone());
+ Assertions.assertFalse(parallelMergeCombineYielder.isDone());
reporters.add(reporter);
}
@@ -663,18 +663,18 @@ public class ParallelMergeCombiningSequenceTest
while (!parallelMergeCombineYielder.isDone()) {
parallelMergeCombineYielder = parallelMergeCombineYielder.next(parallelMergeCombineYielder.get());
}
- Assert.assertTrue(parallelMergeCombineYielder.isDone());
+ Assertions.assertTrue(parallelMergeCombineYielder.isDone());
parallelMergeCombineYielder.close();
- Assert.assertTrue(testingReporter.future.isDone());
+ Assertions.assertTrue(testingReporter.future.isDone());
}
- Assert.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
- Assert.assertEquals(0, pool.getRunningThreadCount());
- Assert.assertFalse(pool.hasQueuedSubmissions());
- Assert.assertEquals(0, pool.getActiveThreadCount());
+ Assertions.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
+ Assertions.assertEquals(0, pool.getRunningThreadCount());
+ Assertions.assertFalse(pool.hasQueuedSubmissions());
+ Assertions.assertEquals(0, pool.getActiveThreadCount());
for (TestingReporter reporter : reporters) {
- Assert.assertTrue(reporter.done);
+ Assertions.assertTrue(reporter.done);
}
}
@@ -691,15 +691,15 @@ public class ParallelMergeCombiningSequenceTest
input.add(nonBlockingSequence(8_888));
assertResultWithEarlyClose(input, 128, 1024, 256, reportMetrics -> {
- Assert.assertEquals(2, reportMetrics.getParallelism());
- Assert.assertEquals(6, reportMetrics.getInputSequences());
+ Assertions.assertEquals(2, reportMetrics.getParallelism());
+ Assertions.assertEquals(6, reportMetrics.getInputSequences());
// 49166 is total set of results if yielder were fully processed, expect somewhere more than 0 but less than that
// this isn't super indicative of anything really, since closing the yielder would have triggered the baggage
// to run, which runs this metrics reporter function, while the actual processing could still be occuring on the
// pool in the background and the yielder still operates as intended if cancellation isn't in fact happening.
// other tests ensure that this is true though (yielder.next throwing an exception for example)
- Assert.assertTrue(49166 > reportMetrics.getInputRows());
- Assert.assertTrue(0 < reportMetrics.getInputRows());
+ Assertions.assertTrue(49166 > reportMetrics.getInputRows());
+ Assertions.assertTrue(0 < reportMetrics.getInputRows());
});
}
@@ -760,26 +760,26 @@ public class ParallelMergeCombiningSequenceTest
IntPair prev = null;
while (!combiningYielder.isDone() && !parallelMergeCombineYielder.isDone()) {
- Assert.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
- Assert.assertNotEquals(parallelMergeCombineYielder.get(), prev);
+ Assertions.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
+ Assertions.assertNotEquals(parallelMergeCombineYielder.get(), prev);
prev = parallelMergeCombineYielder.get();
combiningYielder = combiningYielder.next(combiningYielder.get());
parallelMergeCombineYielder = parallelMergeCombineYielder.next(parallelMergeCombineYielder.get());
}
- Assert.assertTrue(combiningYielder.isDone());
- Assert.assertTrue(parallelMergeCombineYielder.isDone());
+ Assertions.assertTrue(combiningYielder.isDone());
+ Assertions.assertTrue(parallelMergeCombineYielder.isDone());
while (pool.getRunningThreadCount() > 0) {
Thread.sleep(100);
}
- Assert.assertEquals(0, pool.getRunningThreadCount());
+ Assertions.assertEquals(0, pool.getRunningThreadCount());
combiningYielder.close();
parallelMergeCombineYielder.close();
// cancellation trigger should not be set if sequence was fully yielded and close is called
// (though shouldn't actually matter even if it was...)
- Assert.assertFalse(parallelMergeCombineSequence.getCancellationFuture().isCancelled());
- Assert.assertTrue(parallelMergeCombineSequence.getCancellationFuture().isDone());
- Assert.assertFalse(parallelMergeCombineSequence.getCancellationFuture().getCancellationGizmo().isCanceled());
+ Assertions.assertFalse(parallelMergeCombineSequence.getCancellationFuture().isCancelled());
+ Assertions.assertTrue(parallelMergeCombineSequence.getCancellationFuture().isDone());
+ Assertions.assertFalse(parallelMergeCombineSequence.getCancellationFuture().getCancellationGizmo().isCanceled());
}
private void assertResult(
@@ -817,24 +817,24 @@ public class ParallelMergeCombiningSequenceTest
IntPair prev = null;
while (!combiningYielder.isDone() && !parallelMergeCombineYielder.isDone()) {
- Assert.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
- Assert.assertNotEquals(parallelMergeCombineYielder.get(), prev);
+ Assertions.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
+ Assertions.assertNotEquals(parallelMergeCombineYielder.get(), prev);
prev = parallelMergeCombineYielder.get();
combiningYielder = combiningYielder.next(combiningYielder.get());
parallelMergeCombineYielder = parallelMergeCombineYielder.next(parallelMergeCombineYielder.get());
}
- Assert.assertTrue(combiningYielder.isDone());
- Assert.assertTrue(parallelMergeCombineYielder.isDone());
- Assert.assertTrue(pool.awaitQuiescence(5, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Assertions.assertTrue(combiningYielder.isDone());
+ Assertions.assertTrue(parallelMergeCombineYielder.isDone());
+ Assertions.assertTrue(pool.awaitQuiescence(5, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
combiningYielder.close();
parallelMergeCombineYielder.close();
// cancellation trigger should not be set if sequence was fully yielded and close is called
// (though shouldn't actually matter even if it was...)
- Assert.assertFalse(parallelMergeCombineSequence.getCancellationFuture().isCancelled());
- Assert.assertFalse(parallelMergeCombineSequence.getCancellationFuture().getCancellationGizmo().isCanceled());
- Assert.assertTrue(parallelMergeCombineSequence.getCancellationFuture().isDone());
+ Assertions.assertFalse(parallelMergeCombineSequence.getCancellationFuture().isCancelled());
+ Assertions.assertFalse(parallelMergeCombineSequence.getCancellationFuture().getCancellationGizmo().isCanceled());
+ Assertions.assertTrue(parallelMergeCombineSequence.getCancellationFuture().isDone());
}
private void assertResultWithEarlyClose(
@@ -880,8 +880,8 @@ public class ParallelMergeCombiningSequenceTest
break;
} else {
yields++;
- Assert.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
- Assert.assertNotEquals(parallelMergeCombineYielder.get(), prev);
+ Assertions.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
+ Assertions.assertNotEquals(parallelMergeCombineYielder.get(), prev);
prev = parallelMergeCombineYielder.get();
combiningYielder = combiningYielder.next(combiningYielder.get());
parallelMergeCombineYielder = parallelMergeCombineYielder.next(parallelMergeCombineYielder.get());
@@ -889,24 +889,24 @@ public class ParallelMergeCombiningSequenceTest
}
// trying to next the yielder creates sadness for you
final String expectedExceptionMsg = "Sequence canceled";
- Assert.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
+ Assertions.assertEquals(combiningYielder.get(), parallelMergeCombineYielder.get());
final Yielder<IntPair> finalYielder = parallelMergeCombineYielder;
- Throwable t = Assert.assertThrows(RuntimeException.class, () -> finalYielder.next(finalYielder.get()));
- Assert.assertEquals(expectedExceptionMsg, t.getMessage());
+ Throwable t = Assertions.assertThrows(RuntimeException.class, () -> finalYielder.next(finalYielder.get()));
+ Assertions.assertEquals(expectedExceptionMsg, t.getMessage());
// cancellation gizmo of sequence should be cancelled, and also should contain our expected message
- Assert.assertTrue(parallelMergeCombineSequence.getCancellationFuture().getCancellationGizmo().isCanceled());
- Assert.assertEquals(
+ Assertions.assertTrue(parallelMergeCombineSequence.getCancellationFuture().getCancellationGizmo().isCanceled());
+ Assertions.assertEquals(
expectedExceptionMsg,
parallelMergeCombineSequence.getCancellationFuture().getCancellationGizmo().getRuntimeException().getMessage()
);
- Assert.assertTrue(parallelMergeCombineSequence.getCancellationFuture().isCancelled());
+ Assertions.assertTrue(parallelMergeCombineSequence.getCancellationFuture().isCancelled());
- Assert.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
- Assert.assertTrue(pool.isQuiescent());
+ Assertions.assertTrue(pool.awaitQuiescence(10, TimeUnit.SECONDS));
+ Assertions.assertTrue(pool.isQuiescent());
- Assert.assertFalse(combiningYielder.isDone());
- Assert.assertFalse(parallelMergeCombineYielder.isDone());
+ Assertions.assertFalse(combiningYielder.isDone());
+ Assertions.assertFalse(parallelMergeCombineYielder.isDone());
}
private void assertException(List<Sequence<IntPair>> sequences) throws Throwable
@@ -929,7 +929,7 @@ public class ParallelMergeCombiningSequenceTest
)
throws Throwable
{
- Throwable t = Assert.assertThrows(Exception.class, () -> {
+ Throwable t = Assertions.assertThrows(Exception.class, () -> {
final ParallelMergeCombiningSequence<IntPair> parallelMergeCombineSequence = new ParallelMergeCombiningSequence<>(
pool,
sequences,
@@ -950,7 +950,7 @@ public class ParallelMergeCombiningSequenceTest
IntPair prev = null;
while (!parallelMergeCombineYielder.isDone()) {
- Assert.assertNotEquals(parallelMergeCombineYielder.get(), prev);
+ Assertions.assertNotEquals(parallelMergeCombineYielder.get(), prev);
prev = parallelMergeCombineYielder.get();
if (readDelayMillis > 0 && ThreadLocalRandom.current().nextBoolean()) {
Thread.sleep(readDelayMillis);
@@ -963,7 +963,7 @@ public class ParallelMergeCombiningSequenceTest
sequences.forEach(sequence -> {
if (sequence instanceof ExplodingSequence) {
ExplodingSequence exploder = (ExplodingSequence) sequence;
- Assert.assertEquals(1, exploder.getCloseCount());
+ Assertions.assertEquals(1, exploder.getCloseCount());
}
});
LOG.warn(t, "exception:");
diff --git a/processing/src/test/java/org/apache/druid/java/util/common/guava/TopNSequenceTest.java b/processing/src/test/java/org/apache/druid/java/util/common/guava/TopNSequenceTest.java
index 5c7109642e4..d4a95b151e4 100644
--- a/processing/src/test/java/org/apache/druid/java/util/common/guava/TopNSequenceTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/common/guava/TopNSequenceTest.java
@@ -23,10 +23,10 @@ import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.provider.MethodSource;
import java.util.Arrays;
import java.util.Collection;
@@ -43,7 +43,8 @@ public class TopNSequenceTest
private static final List<String> RAW_ASC = Lists.newArrayList(Splitter.fixedLength(1).split("abcdefghijk"));
private static final List<String> RAW_DESC = Lists.newArrayList(Splitter.fixedLength(1).split("kjihgfedcba"));
- @RunWith(Parameterized.class)
+ @ParameterizedClass
+ @MethodSource("makeTestData")
public static class TopNSequenceAscDescTest
{
private static final Ordering<String> ASC = Ordering.natural();
@@ -53,7 +54,6 @@ public class TopNSequenceTest
private List<String> rawInput;
private int limit;
- @Parameterized.Parameters(name = "comparator={0}, rawInput={1}, limit={2}")
public static Collection<Object[]> makeTestData()
{
Object[][] data = new Object[][]{
@@ -98,14 +98,15 @@ public class TopNSequenceTest
Sequence<String> result = new TopNSequence<>(Sequences.simple(inputs), ordering, limit);
- Assert.assertEquals(expected, result.toList());
+ Assertions.assertEquals(expected, result.toList());
}
}
/**
* This class has test cases using a comparator that sometimes returns zero for unequal things.
*/
- @RunWith(Parameterized.class)
+ @ParameterizedClass
+ @MethodSource("makeTestData")
public static class TopNSequenceEvenOddTest
{
// 'a', 'c', 'e', ... all come before 'b', 'd', 'f', ...
@@ -114,7 +115,6 @@ public class TopNSequenceTest
private String expected;
private List<String> rawInput;
- @Parameterized.Parameters(name = "rawInput={1}")
public static Collection<Object[]> makeTestData()
{
Object[][] data = new Object[][]{
@@ -137,10 +137,10 @@ public class TopNSequenceTest
// Verify that the output of the sequence is stable relative to the input.
for (int limit = 0; limit < expected.length() + 1; limit++) {
final TopNSequence<String> sequence = new TopNSequence<>(Sequences.simple(rawInput), EVENODD, limit);
- Assert.assertEquals(
- "limit = " + limit,
+ Assertions.assertEquals(
expected.substring(0, Math.min(limit, expected.length())),
- Joiner.on("").join(sequence.toList())
+ Joiner.on("").join(sequence.toList()),
+ "limit = " + limit
);
}
}
diff --git a/processing/src/test/java/org/apache/druid/java/util/emitter/core/EmitterTest.java b/processing/src/test/java/org/apache/druid/java/util/emitter/core/EmitterTest.java
index 62244d3bd28..a023274ce2e 100644
--- a/processing/src/test/java/org/apache/druid/java/util/emitter/core/EmitterTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/emitter/core/EmitterTest.java
@@ -38,10 +38,10 @@ import org.asynchttpclient.Response;
import org.asynchttpclient.netty.EagerResponseBodyPart;
import org.asynchttpclient.netty.NettyResponseStatus;
import org.asynchttpclient.uri.Uri;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -98,13 +98,13 @@ public class EmitterTest
return OK_RESPONSE;
}
- @Before
+ @BeforeEach
public void setUp()
{
httpClient = new MockHttpClient();
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
if (emitter != null) {
@@ -158,10 +158,13 @@ public class EmitterTest
Lifecycle lifecycle = new Lifecycle();
Emitter emitter = Emitters.create(props, httpClient, JSON_MAPPER, lifecycle);
- Assert.assertTrue(StringUtils.format(
- "HttpPostEmitter emitter should be created, but found %s",
- emitter.getClass().getName()
- ), emitter instanceof HttpPostEmitter);
+ Assertions.assertTrue(
+ emitter instanceof HttpPostEmitter,
+ StringUtils.format(
+ "HttpPostEmitter emitter should be created, but found %s",
+ emitter.getClass().getName()
+ )
+ );
emitter.start();
return (HttpPostEmitter) emitter;
}
@@ -234,12 +237,12 @@ public class EmitterTest
@Override
protected ListenableFuture<Response> go(Request request) throws JsonProcessingException
{
- Assert.assertEquals(TARGET_URL, request.getUrl());
- Assert.assertEquals(
+ Assertions.assertEquals(TARGET_URL, request.getUrl());
+ Assertions.assertEquals(
"application/json",
request.getHeaders().get(HttpHeaders.Names.CONTENT_TYPE)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
JSON_MAPPER.readTree(StringUtils.format(
"[%s,%s]\n",
JSON_MAPPER.writeValueAsString(events.get(0)),
@@ -260,7 +263,7 @@ public class EmitterTest
}
waitForEmission(emitter, 1);
closeNoFlush(emitter);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
}
@Test
@@ -278,12 +281,12 @@ public class EmitterTest
@Override
protected ListenableFuture<Response> go(Request request) throws JsonProcessingException
{
- Assert.assertEquals(TARGET_URL, request.getUrl());
- Assert.assertEquals(
+ Assertions.assertEquals(TARGET_URL, request.getUrl());
+ Assertions.assertEquals(
"application/json",
request.getHeaders().get(HttpHeaders.Names.CONTENT_TYPE)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
JSON_MAPPER.readTree(StringUtils.format(
"[%s,%s]\n",
JSON_MAPPER.writeValueAsString(events.get(0)),
@@ -304,7 +307,7 @@ public class EmitterTest
}
waitForEmission(emitter, 1);
closeNoFlush(emitter);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
}
@Test
@@ -325,7 +328,7 @@ public class EmitterTest
emitter.emit(new UnitEvent("test", 5));
closeAndExpectFlush(emitter);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
}
@Test
@@ -353,9 +356,9 @@ public class EmitterTest
latch.await();
long timeWaited = System.currentTimeMillis() - emitTime;
- Assert.assertTrue(
- StringUtils.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2),
- timeWaited < timeBetweenEmissions * 2
+ Assertions.assertTrue(
+ timeWaited < timeBetweenEmissions * 2,
+ StringUtils.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2)
);
waitForEmission(emitter, 1);
@@ -378,25 +381,26 @@ public class EmitterTest
thisLatch.await();
timeWaited = System.currentTimeMillis() - emitTime;
- Assert.assertTrue(
- StringUtils.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2),
- timeWaited < timeBetweenEmissions * 2
+ Assertions.assertTrue(
+ timeWaited < timeBetweenEmissions * 2,
+ StringUtils.format("timeWaited[%s] !< %s", timeWaited, timeBetweenEmissions * 2)
);
waitForEmission(emitter, 2);
closeNoFlush(emitter);
- Assert.assertTrue("httpClient.succeeded()", httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded(), "httpClient.succeeded()");
}
- @Test(timeout = 60_000L)
+ @Test
+ @org.junit.jupiter.api.Timeout(value = 60_000L, unit = java.util.concurrent.TimeUnit.MILLISECONDS)
public void testFailedEmission() throws Exception
{
final UnitEvent event1 = new UnitEvent("test", 1);
final UnitEvent event2 = new UnitEvent("test", 2);
emitter = sizeBasedEmitter(1);
- Assert.assertEquals(0, emitter.getTotalEmittedEvents());
- Assert.assertEquals(0, emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount());
- Assert.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
+ Assertions.assertEquals(0, emitter.getTotalEmittedEvents());
+ Assertions.assertEquals(0, emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount());
+ Assertions.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
httpClient.setGoHandler(
new GoHandler()
@@ -412,12 +416,12 @@ public class EmitterTest
emitter.emit(event1);
emitter.flush();
waitForEmission(emitter, 1);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
// Failed to emit the first event.
- Assert.assertEquals(0, emitter.getTotalEmittedEvents());
- Assert.assertEquals(0, emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount());
- Assert.assertTrue(emitter.getFailedSendingTimeCounter().getTimeSumAndCount() > 0);
+ Assertions.assertEquals(0, emitter.getTotalEmittedEvents());
+ Assertions.assertEquals(0, emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount());
+ Assertions.assertTrue(emitter.getFailedSendingTimeCounter().getTimeSumAndCount() > 0);
httpClient.setGoHandler(
new GoHandler()
@@ -439,11 +443,11 @@ public class EmitterTest
emitter.joinEmitterThread();
// Succeed to emit both events.
- Assert.assertEquals(2, emitter.getTotalEmittedEvents());
- Assert.assertTrue(emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount() > 0);
- Assert.assertTrue(emitter.getFailedSendingTimeCounter().getTimeSumAndCount() > 0);
+ Assertions.assertEquals(2, emitter.getTotalEmittedEvents());
+ Assertions.assertTrue(emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount() > 0);
+ Assertions.assertTrue(emitter.getFailedSendingTimeCounter().getTimeSumAndCount() > 0);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
}
@Test
@@ -461,16 +465,16 @@ public class EmitterTest
@Override
protected ListenableFuture<Response> go(Request request) throws JsonProcessingException
{
- Assert.assertEquals(TARGET_URL, request.getUrl());
- Assert.assertEquals(
+ Assertions.assertEquals(TARGET_URL, request.getUrl());
+ Assertions.assertEquals(
"application/json",
request.getHeaders().get(HttpHeaders.Names.CONTENT_TYPE)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
"Basic " + StringUtils.encodeBase64String(StringUtils.toUtf8("foo:bar")),
request.getHeaders().get(HttpHeaders.Names.AUTHORIZATION)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
JSON_MAPPER.readTree(StringUtils.format(
"%s\n%s\n",
JSON_MAPPER.writeValueAsString(events.get(0)),
@@ -492,7 +496,7 @@ public class EmitterTest
emitter.flush();
waitForEmission(emitter, 1);
closeNoFlush(emitter);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
}
@Test
@@ -511,9 +515,9 @@ public class EmitterTest
);
final AtomicInteger counter = new AtomicInteger();
emitter = manualFlushEmitterWithBatchSize(1024 * 1024);
- Assert.assertEquals(0, emitter.getTotalEmittedEvents());
- Assert.assertEquals(0, emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount());
- Assert.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
+ Assertions.assertEquals(0, emitter.getTotalEmittedEvents());
+ Assertions.assertEquals(0, emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount());
+ Assertions.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
httpClient.setGoHandler(
new GoHandler()
@@ -521,12 +525,12 @@ public class EmitterTest
@Override
protected ListenableFuture<Response> go(Request request) throws JsonProcessingException
{
- Assert.assertEquals(TARGET_URL, request.getUrl());
- Assert.assertEquals(
+ Assertions.assertEquals(TARGET_URL, request.getUrl());
+ Assertions.assertEquals(
"application/json",
request.getHeaders().get(HttpHeaders.Names.CONTENT_TYPE)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
JSON_MAPPER.readTree(StringUtils.format(
"[%s,%s]\n",
JSON_MAPPER.writeValueAsString(events.get(counter.getAndIncrement())),
@@ -546,17 +550,17 @@ public class EmitterTest
emitter.emit(event);
}
waitForEmission(emitter, 1);
- Assert.assertEquals(2, emitter.getTotalEmittedEvents());
- Assert.assertTrue(emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount() > 0);
- Assert.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
+ Assertions.assertEquals(2, emitter.getTotalEmittedEvents());
+ Assertions.assertTrue(emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount() > 0);
+ Assertions.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
emitter.flush();
waitForEmission(emitter, 2);
- Assert.assertEquals(4, emitter.getTotalEmittedEvents());
- Assert.assertTrue(emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount() > 0);
- Assert.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
+ Assertions.assertEquals(4, emitter.getTotalEmittedEvents());
+ Assertions.assertTrue(emitter.getSuccessfulSendingTimeCounter().getTimeSumAndCount() > 0);
+ Assertions.assertEquals(0, emitter.getFailedSendingTimeCounter().getTimeSumAndCount());
closeNoFlush(emitter);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
}
@Test
@@ -575,12 +579,12 @@ public class EmitterTest
@Override
protected ListenableFuture<Response> go(Request request) throws IOException
{
- Assert.assertEquals(TARGET_URL, request.getUrl());
- Assert.assertEquals(
+ Assertions.assertEquals(TARGET_URL, request.getUrl());
+ Assertions.assertEquals(
"application/json",
request.getHeaders().get(HttpHeaders.Names.CONTENT_TYPE)
);
- Assert.assertEquals(
+ Assertions.assertEquals(
HttpHeaders.Values.GZIP,
request.getHeaders().get(HttpHeaders.Names.CONTENT_ENCODING)
);
@@ -591,7 +595,7 @@ public class EmitterTest
data.get(dataArray);
CompressionUtils.gunzip(new ByteArrayInputStream(dataArray), baos);
- Assert.assertEquals(
+ Assertions.assertEquals(
JSON_MAPPER.readTree(StringUtils.format(
"[%s,%s]\n",
JSON_MAPPER.writeValueAsString(events.get(0)),
@@ -612,7 +616,7 @@ public class EmitterTest
}
waitForEmission(emitter, 1);
closeNoFlush(emitter);
- Assert.assertTrue(httpClient.succeeded());
+ Assertions.assertTrue(httpClient.succeeded());
}
private void closeAndExpectFlush(Emitter emitter) throws IOException
diff --git a/processing/src/test/java/org/apache/druid/java/util/emitter/service/ServiceMetricEventTest.java b/processing/src/test/java/org/apache/druid/java/util/emitter/service/ServiceMetricEventTest.java
index 75a1cd4f083..82c0c9a95ea 100644
--- a/processing/src/test/java/org/apache/druid/java/util/emitter/service/ServiceMetricEventTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/emitter/service/ServiceMetricEventTest.java
@@ -25,8 +25,8 @@ import com.google.common.collect.ImmutableMap;
import org.apache.druid.jackson.DefaultObjectMapper;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.IAE;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -54,7 +54,7 @@ public class ServiceMetricEventTest
.setMetric("test-metric", 1234)
.build("test", "localhost");
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.<String, Object>builder()
.put("feed", "metrics")
.put("timestamp", builderEvent.getCreatedTime().toString())
@@ -76,8 +76,8 @@ public class ServiceMetricEventTest
builderEvent.toMap()
);
- Assert.assertEquals("test", builderEvent.getServiceDims().get("service"));
- Assert.assertEquals("localhost", builderEvent.getServiceDims().get("host"));
+ Assertions.assertEquals("test", builderEvent.getServiceDims().get("service"));
+ Assertions.assertEquals("localhost", builderEvent.getServiceDims().get("host"));
ServiceMetricEvent constructorEvent = ServiceMetricEvent
.builder()
@@ -94,7 +94,7 @@ public class ServiceMetricEventTest
.setMetric("test-metric", 1234)
.build("test", "localhost");
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.<String, Object>builder()
.put("feed", "metrics")
.put("timestamp", constructorEvent.getCreatedTime().toString())
@@ -130,7 +130,7 @@ public class ServiceMetricEventTest
.setMetric("test-metric", 1234)
.build("test", "localhost");
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.<String, Object>builder()
.put("feed", "metrics")
.put("timestamp", arrayConstructorEvent.getCreatedTime().toString())
@@ -151,7 +151,7 @@ public class ServiceMetricEventTest
.build(), arrayConstructorEvent.toMap()
);
- Assert.assertNotNull(
+ Assertions.assertNotNull(
new ServiceMetricEvent.Builder()
.setDimension("user1", "a")
.setDimension("user2", "b")
@@ -168,7 +168,7 @@ public class ServiceMetricEventTest
.getCreatedTime()
);
- Assert.assertNotNull(
+ Assertions.assertNotNull(
ServiceMetricEvent.builder()
.setDimension("user1", new String[]{"a"})
.setDimension("user2", new String[]{"b"})
@@ -185,7 +185,7 @@ public class ServiceMetricEventTest
.getCreatedTime()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.<String, Object>builder()
.put("feed", "metrics")
.put("timestamp", DateTimes.utc(42).toString())
@@ -221,7 +221,7 @@ public class ServiceMetricEventTest
.toMap()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.<String, Object>builder()
.put("feed", "metrics")
.put("timestamp", DateTimes.utc(42).toString())
@@ -257,7 +257,7 @@ public class ServiceMetricEventTest
.toMap()
);
- Assert.assertEquals(
+ Assertions.assertEquals(
ImmutableMap.<String, Object>builder()
.put("feed", "metrics")
.put("timestamp", DateTimes.utc(42).toString())
@@ -278,29 +278,41 @@ public class ServiceMetricEventTest
);
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void testInfinite()
{
- ServiceMetricEvent.builder().setMetric("foo", 1 / 0d);
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> ServiceMetricEvent.builder().setMetric("foo", 1 / 0d)
+ );
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void testInfinite2()
{
- ServiceMetricEvent.builder().setMetric("foo", 1 / 0f);
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> ServiceMetricEvent.builder().setMetric("foo", 1 / 0f)
+ );
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void testNaN()
{
- ServiceMetricEvent.builder().setMetric("foo", 0 / 0d);
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> ServiceMetricEvent.builder().setMetric("foo", 0 / 0d)
+ );
}
- @Test(expected = IllegalStateException.class)
+ @Test
public void testNaN2()
{
- ServiceMetricEvent.builder().setMetric("foo", 0 / 0f);
+ Assertions.assertThrows(
+ IllegalStateException.class,
+ () -> ServiceMetricEvent.builder().setMetric("foo", 0 / 0f)
+ );
}
@Test
@@ -311,7 +323,7 @@ public class ServiceMetricEventTest
.setDimensionIfNotNull("userDimMap", userDimMap)
.setMetric("foo", 1)
.build("service", "host");
- Assert.assertEquals(userDimMap, target.getUserDims().get("userDimMap"));
+ Assertions.assertEquals(userDimMap, target.getUserDims().get("userDimMap"));
}
@Test
@@ -321,8 +333,8 @@ public class ServiceMetricEventTest
.setDimensionIfNotNull("userDimMap", null)
.setMetric("foo", 1)
.build("service", "host");
- Assert.assertTrue(target.getUserDims().isEmpty());
- Assert.assertNull(target.getUserDims().get("userDimMap"));
+ Assertions.assertTrue(target.getUserDims().isEmpty());
+ Assertions.assertNull(target.getUserDims().get("userDimMap"));
}
@Test
@@ -335,9 +347,9 @@ public class ServiceMetricEventTest
final ServiceMetricEvent event1 = eventBuilder.build("coordinator", "localhost");
- Assert.assertEquals(Map.of("dim1", "v1"), event1.getUserDims());
- Assert.assertEquals("coordinator", event1.getServiceDims().get("service"));
- Assert.assertEquals("localhost", event1.getServiceDims().get("host"));
+ Assertions.assertEquals(Map.of("dim1", "v1"), event1.getUserDims());
+ Assertions.assertEquals("coordinator", event1.getServiceDims().get("service"));
+ Assertions.assertEquals("localhost", event1.getServiceDims().get("host"));
final ServiceMetricEvent event2 = eventBuilder
.setDimension("dim2", "v2")
@@ -345,10 +357,10 @@ public class ServiceMetricEventTest
.build("coordinator", "localhost");
// Verify that the original event gets changed dimensions
- Assert.assertEquals(Map.of("dim1", "v1", "dim2", "v2"), event2.getUserDims());
- Assert.assertEquals(Map.of("dim1", "v1"), event1.getUserDims());
- Assert.assertEquals("coordinator", event2.getServiceDims().get("service"));
- Assert.assertEquals("localhost", event2.getServiceDims().get("host"));
+ Assertions.assertEquals(Map.of("dim1", "v1", "dim2", "v2"), event2.getUserDims());
+ Assertions.assertEquals(Map.of("dim1", "v1"), event1.getUserDims());
+ Assertions.assertEquals("coordinator", event2.getServiceDims().get("service"));
+ Assertions.assertEquals("localhost", event2.getServiceDims().get("host"));
}
@Test
@@ -356,15 +368,15 @@ public class ServiceMetricEventTest
{
final ServiceMetricEvent.Builder eventBuilder = ServiceMetricEvent.builder();
- Assert.assertThrows(
+ Assertions.assertThrows(
IAE.class,
() -> eventBuilder.setDimension("dim1", (Object) null)
);
- Assert.assertThrows(
+ Assertions.assertThrows(
IAE.class,
() -> eventBuilder.setDimension(null, null)
);
- Assert.assertThrows(
+ Assertions.assertThrows(
IAE.class,
() -> eventBuilder.setDimension(null, new String[]{"a"})
);
@@ -382,7 +394,7 @@ public class ServiceMetricEventTest
.build("broker", "hostA");
- Assert.assertEquals(
+ Assertions.assertEquals(
"{\"feed\":\"test_feed\",\"timestamp\":\"2026-01-01T00:00:00.000Z\",\"metric\":\"m1\",\"value\":42,\"service\":\"broker\",\"host\":\"hostA\",\"dim1\":\"xyz\",\"dim2\":\"xyz\"}",
new DefaultObjectMapper().writeValueAsString(event.toMap())
);
@@ -396,6 +408,6 @@ public class ServiceMetricEventTest
.setDimension("userDim", "value")
.build(ImmutableMap.of("serviceDim1", "dim1", "serviceDim2", "dim2"));
- Assert.assertEquals(ImmutableMap.of("serviceDim1", "dim1", "serviceDim2", "dim2"), event.getServiceDims());
+ Assertions.assertEquals(ImmutableMap.of("serviceDim1", "dim1", "serviceDim2", "dim2"), event.getServiceDims());
}
}
diff --git a/processing/src/test/java/org/apache/druid/java/util/http/client/FriendlyServersTest.java b/processing/src/test/java/org/apache/druid/java/util/http/client/FriendlyServersTest.java
index 4df73564389..27bacf9e6ea 100644
--- a/processing/src/test/java/org/apache/druid/java/util/http/client/FriendlyServersTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/http/client/FriendlyServersTest.java
@@ -36,12 +36,13 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
+
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
@@ -105,8 +106,8 @@ public class FriendlyServersTest
StatusResponseHandler.getInstance()
).get();
- Assert.assertEquals(200, response.getStatus().getCode());
- Assert.assertEquals("hello!", response.getContent());
+ Assertions.assertEquals(200, response.getStatus().getCode());
+ Assertions.assertEquals("hello!", response.getContent());
}
finally {
exec.shutdownNow();
@@ -150,7 +151,7 @@ public class FriendlyServersTest
out.write("HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nhello!".getBytes(StandardCharsets.UTF_8));
}
catch (Exception e) {
- Assert.fail(e.toString());
+ Assertions.fail(e.toString());
}
}
}
@@ -175,10 +176,10 @@ public class FriendlyServersTest
StatusResponseHandler.getInstance()
).get();
- Assert.assertEquals(200, response.getStatus().getCode());
- Assert.assertEquals("hello!", response.getContent());
+ Assertions.assertEquals(200, response.getStatus().getCode());
+ Assertions.assertEquals("hello!", response.getContent());
- Assert.assertEquals(
+ Assertions.assertEquals(
"CONNECT anotherHost:8080 HTTP/1.1\r\nProxy-Authorization: Basic Ym9iOnNhbGx5\r\n",
requestContent.get()
);
@@ -242,9 +243,9 @@ public class FriendlyServersTest
StatusResponseHandler.getInstance()
).get();
- Assert.assertEquals(200, response.getStatus().getCode());
- Assert.assertEquals("hello!", response.getContent());
- Assert.assertTrue(foundAcceptEncoding.get());
+ Assertions.assertEquals(200, response.getStatus().getCode());
+ Assertions.assertEquals("hello!", response.getContent());
+ Assertions.assertTrue(foundAcceptEncoding.get());
}
finally {
exec.shutdownNow();
@@ -300,7 +301,7 @@ public class FriendlyServersTest
),
StatusResponseHandler.getInstance()
).get().getStatus();
- Assert.assertEquals(404, status.getCode());
+ Assertions.assertEquals(404, status.getCode());
}
// Incorrect name ("127.0.0.1")
@@ -322,8 +323,11 @@ public class FriendlyServersTest
ea = e.getCause();
}
- Assert.assertTrue("ChannelException thrown by 'get'", ea instanceof ChannelException);
- Assert.assertTrue("Expected error message", ea.getCause().getMessage().contains("Failed to handshake"));
+ Assertions.assertTrue(ea instanceof ChannelException, "ChannelException thrown by 'get'");
+ Assertions.assertTrue(
+ ea.getCause().getMessage().contains("Failed to handshake"),
+ "Expected error message"
+ );
}
{
@@ -344,10 +348,10 @@ public class FriendlyServersTest
catch (ExecutionException e) {
eb = e.getCause();
}
- Assert.assertNotNull("ChannelException thrown by 'get'", eb);
- Assert.assertTrue(
- "Root cause is SSLHandshakeException",
- eb.getCause().getCause() instanceof SSLHandshakeException
+ Assertions.assertNotNull(eb, "ChannelException thrown by 'get'");
+ Assertions.assertTrue(
+ eb.getCause().getCause() instanceof SSLHandshakeException,
+ "Root cause is SSLHandshakeException"
);
}
}
@@ -358,7 +362,7 @@ public class FriendlyServersTest
}
@Test
- @Ignore
+ @Disabled
public void testHttpBin() throws Throwable
{
final Lifecycle lifecycle = new Lifecycle();
@@ -373,7 +377,7 @@ public class FriendlyServersTest
StatusResponseHandler.getInstance()
).get().getStatus();
- Assert.assertEquals(200, status.getCode());
+ Assertions.assertEquals(200, status.getCode());
}
{
@@ -384,7 +388,7 @@ public class FriendlyServersTest
StatusResponseHandler.getInstance()
).get().getStatus();
- Assert.assertEquals(200, status.getCode());
+ Assertions.assertEquals(200, status.getCode());
}
}
finally {
diff --git a/processing/src/test/java/org/apache/druid/java/util/http/client/JankyServersTest.java b/processing/src/test/java/org/apache/druid/java/util/http/client/JankyServersTest.java
index ec54bd13500..3723c0ba7c6 100644
--- a/processing/src/test/java/org/apache/druid/java/util/http/client/JankyServersTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/http/client/JankyServersTest.java
@@ -28,14 +28,13 @@ import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.jboss.netty.handler.timeout.ReadTimeoutException;
import org.joda.time.Duration;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -57,10 +56,7 @@ public class JankyServersTest
static ServerSocket echoServerSocket;
static ServerSocket closingServerSocket;
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @BeforeClass
+ @BeforeAll
public static void setUp() throws Exception
{
exec = Executors.newCachedThreadPool();
@@ -140,7 +136,7 @@ public class JankyServersTest
);
}
- @AfterClass
+ @AfterAll
public static void tearDown() throws Exception
{
exec.shutdownNow();
@@ -170,7 +166,7 @@ public class JankyServersTest
e = e1.getCause();
}
- Assert.assertTrue("ReadTimeoutException thrown by 'get'", e instanceof ReadTimeoutException);
+ Assertions.assertTrue(e instanceof ReadTimeoutException, "ReadTimeoutException thrown by 'get'");
}
finally {
lifecycle.stop();
@@ -199,7 +195,7 @@ public class JankyServersTest
e = e1.getCause();
}
- Assert.assertTrue("ReadTimeoutException thrown by 'get'", e instanceof ReadTimeoutException);
+ Assertions.assertTrue(e instanceof ReadTimeoutException, "ReadTimeoutException thrown by 'get'");
}
finally {
lifecycle.stop();
@@ -231,7 +227,7 @@ public class JankyServersTest
e = e1.getCause();
}
- Assert.assertTrue("ChannelException thrown by 'get'", e instanceof ChannelException);
+ Assertions.assertTrue(e instanceof ChannelException, "ChannelException thrown by 'get'");
}
finally {
lifecycle.stop();
@@ -259,7 +255,7 @@ public class JankyServersTest
e1.printStackTrace();
}
- Assert.assertTrue("ChannelException thrown by 'get'", isChannelClosedException(e));
+ Assertions.assertTrue(isChannelClosedException(e), "ChannelException thrown by 'get'");
}
finally {
lifecycle.stop();
@@ -289,7 +285,7 @@ public class JankyServersTest
e1.printStackTrace();
}
- Assert.assertTrue("ChannelException thrown by 'get'", isChannelClosedException(e));
+ Assertions.assertTrue(isChannelClosedException(e), "ChannelException thrown by 'get'");
}
finally {
lifecycle.stop();
@@ -325,7 +321,7 @@ public class JankyServersTest
e1.printStackTrace();
}
- Assert.assertTrue("ChannelException thrown by 'get'", isChannelClosedException(e));
+ Assertions.assertTrue(isChannelClosedException(e), "ChannelException thrown by 'get'");
}
finally {
lifecycle.stop();
@@ -361,7 +357,7 @@ public class JankyServersTest
e1.printStackTrace();
}
- Assert.assertTrue("ChannelException thrown by 'get'", isChannelClosedException(e));
+ Assertions.assertTrue(isChannelClosedException(e), "ChannelException thrown by 'get'");
}
finally {
lifecycle.stop();
@@ -388,10 +384,10 @@ public class JankyServersTest
StatusResponseHandler.getInstance()
);
- expectedException.expect(ExecutionException.class);
- expectedException.expectMessage("java.lang.IllegalArgumentException: invalid version format: GET");
-
- response.get();
+ final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, response::get);
+ Assertions.assertTrue(
+ exception.getMessage().contains("java.lang.IllegalArgumentException: invalid version format: GET")
+ );
}
finally {
lifecycle.stop();
@@ -412,10 +408,10 @@ public class JankyServersTest
StatusResponseHandler.getInstance()
);
- expectedException.expect(ExecutionException.class);
- expectedException.expectMessage("org.jboss.netty.channel.ChannelException: Faulty channel in resource pool");
-
- response.get();
+ final ExecutionException exception = Assertions.assertThrows(ExecutionException.class, response::get);
+ Assertions.assertTrue(
+ exception.getMessage().contains("org.jboss.netty.channel.ChannelException: Faulty channel in resource pool")
+ );
}
finally {
lifecycle.stop();
diff --git a/processing/src/test/java/org/apache/druid/java/util/http/client/pool/ResourcePoolTest.java b/processing/src/test/java/org/apache/druid/java/util/http/client/pool/ResourcePoolTest.java
index d9ab3ea919b..7b262924ae3 100644
--- a/processing/src/test/java/org/apache/druid/java/util/http/client/pool/ResourcePoolTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/http/client/pool/ResourcePoolTest.java
@@ -22,9 +22,9 @@ package org.apache.druid.java.util.http.client.pool;
import org.apache.druid.java.util.common.ISE;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -36,7 +36,7 @@ public class ResourcePoolTest
ResourceFactory<String, String> resourceFactory;
ResourcePool<String, String> pool;
- @Before
+ @BeforeEach
public void setUp()
{
setUpPool(true);
@@ -79,7 +79,7 @@ public class ResourcePoolTest
EasyMock.replay(resourceFactory);
ResourceContainer<String> billyString = pool.take("billy");
- Assert.assertEquals("billy0", billyString.get());
+ Assertions.assertEquals("billy0", billyString.get());
billyString.returnResource();
}
@@ -97,12 +97,12 @@ public class ResourcePoolTest
EasyMock.replay(resourceFactory);
ResourceContainer<String> billyString = pool.take("billy");
- Assert.assertEquals("billy0", billyString.get());
+ Assertions.assertEquals("billy0", billyString.get());
billyString.returnResource();
billyString = pool.take("billy");
- Assert.assertEquals("billy0", billyString.get());
+ Assertions.assertEquals("billy0", billyString.get());
billyString.returnResource();
}
@@ -244,8 +244,8 @@ public class ResourcePoolTest
ResourceContainer<String> billyString = pool.take("billy");
ResourceContainer<String> sallyString = pool.take("sally");
- Assert.assertEquals("billy0", billyString.get());
- Assert.assertEquals("sally0", sallyString.get());
+ Assertions.assertEquals("billy0", billyString.get());
+ Assertions.assertEquals("sally0", sallyString.get());
EasyMock.verify(resourceFactory);
EasyMock.reset(resourceFactory);
@@ -266,7 +266,7 @@ public class ResourcePoolTest
EasyMock.replay(resourceFactory);
ResourceContainer<String> billy = pool.take("billy");
- Assert.assertEquals("billy2", billy.get());
+ Assertions.assertEquals("billy2", billy.get());
billy.returnResource();
EasyMock.verify(resourceFactory);
@@ -297,8 +297,8 @@ public class ResourcePoolTest
catch (IllegalStateException e) {
e1 = e;
}
- Assert.assertNotNull("exception", e1);
- Assert.assertEquals("where's billy?", e1.getMessage());
+ Assertions.assertNotNull(e1, "exception");
+ Assertions.assertEquals("where's billy?", e1.getMessage());
IllegalStateException e2 = null;
try {
@@ -307,11 +307,11 @@ public class ResourcePoolTest
catch (IllegalStateException e) {
e2 = e;
}
- Assert.assertNotNull("exception", e2);
- Assert.assertEquals("where's billy?", e2.getMessage());
+ Assertions.assertNotNull(e2, "exception");
+ Assertions.assertEquals("where's billy?", e2.getMessage());
ResourceContainer<String> billy = pool.take("billy");
- Assert.assertEquals("billy2", billy.get());
+ Assertions.assertEquals("billy2", billy.get());
billy.returnResource();
EasyMock.verify(resourceFactory);
@@ -354,9 +354,9 @@ public class ResourcePoolTest
latch1.countDown();
latch3.countDown();
- Assert.assertEquals("billy1", billy1Thread.getValue());
- Assert.assertEquals("billy0", billy0Thread.getValue());
- Assert.assertEquals("billy0", blockedThread.getValue());
+ Assertions.assertEquals("billy1", billy1Thread.getValue());
+ Assertions.assertEquals("billy0", billy0Thread.getValue());
+ Assertions.assertEquals("billy0", blockedThread.getValue());
}
@Test
@@ -406,11 +406,11 @@ public class ResourcePoolTest
latch1.countDown();
latch3.countDown();
- Assert.assertEquals("billy1", billy1Thread.getValue());
- Assert.assertEquals("billy0", billy0Thread.getValue());
+ Assertions.assertEquals("billy1", billy1Thread.getValue());
+ Assertions.assertEquals("billy0", billy0Thread.getValue());
blockedThread.join();
// pool returns null after close
- Assert.assertEquals(null, blockedThread.getValue());
+ Assertions.assertEquals(null, blockedThread.getValue());
}
@Test
@@ -429,7 +429,7 @@ public class ResourcePoolTest
EasyMock.replay(resourceFactory);
ResourceContainer<String> billyString = pool.take("billy");
- Assert.assertEquals("billy0", billyString.get());
+ Assertions.assertEquals("billy0", billyString.get());
EasyMock.verify(resourceFactory);
EasyMock.reset(resourceFactory);
@@ -444,7 +444,7 @@ public class ResourcePoolTest
EasyMock.replay(resourceFactory);
ResourceContainer<String> billy = pool.take("billy");
- Assert.assertEquals("billy1", billy.get());
+ Assertions.assertEquals("billy1", billy.get());
billy.returnResource();
EasyMock.verify(resourceFactory);
diff --git a/processing/src/test/java/org/apache/druid/java/util/metrics/ClockDriftSafeMonitorSchedulerTest.java b/processing/src/test/java/org/apache/druid/java/util/metrics/ClockDriftSafeMonitorSchedulerTest.java
index 712fcbfbb62..234deab1e3c 100644
--- a/processing/src/test/java/org/apache/druid/java/util/metrics/ClockDriftSafeMonitorSchedulerTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/metrics/ClockDriftSafeMonitorSchedulerTest.java
@@ -25,10 +25,10 @@ import io.timeandspace.cronscheduler.CronScheduler;
import io.timeandspace.cronscheduler.CronTask;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -60,14 +60,14 @@ public class ClockDriftSafeMonitorSchedulerTest
private CronScheduler cronScheduler;
private AutoCloseable mocks;
- @Before
+ @BeforeEach
public void setUp()
{
cronTaskRunner = Execs.singleThreaded("monitor-scheduler-test");
mocks = MockitoAnnotations.openMocks(this);
}
- @After
+ @AfterEach
public void tearDown() throws Exception
{
cronTaskRunner.shutdownNow();
@@ -102,12 +102,12 @@ public class ClockDriftSafeMonitorSchedulerTest
final Optional<Monitor1> maybeFound1 = scheduler.findMonitor(Monitor1.class);
final Optional<Monitor2> maybeFound2 = scheduler.findMonitor(Monitor2.class);
- Assert.assertTrue(maybeFound1.isPresent());
- Assert.assertTrue(maybeFound2.isPresent());
- Assert.assertSame(monitor1, maybeFound1.get());
- Assert.assertSame(monitor2, maybeFound2.get());
+ Assertions.assertTrue(maybeFound1.isPresent());
+ Assertions.assertTrue(maybeFound2.isPresent());
+ Assertions.assertSame(monitor1, maybeFound1.get());
+ Assertions.assertSame(monitor2, maybeFound2.get());
- Assert.assertFalse(scheduler.findMonitor(Monitor3.class).isPresent());
+ Assertions.assertFalse(scheduler.findMonitor(Monitor3.class).isPresent());
}
@Test
@@ -301,7 +301,7 @@ public class ClockDriftSafeMonitorSchedulerTest
ArgumentMatchers.any(), ArgumentMatchers.any(CronTask.class));
Mockito.verify(executor, Mockito.times(1)).submit(ArgumentMatchers.any(Callable.class));
Mockito.verify(monitor, Mockito.times(1)).monitor(ArgumentMatchers.any());
- Assert.assertTrue(monitorResultHolder.get());
+ Assertions.assertTrue(monitorResultHolder.get());
scheduler.stop();
}
diff --git a/processing/src/test/java/org/apache/druid/java/util/metrics/OshiSysMonitorTest.java b/processing/src/test/java/org/apache/druid/java/util/metrics/OshiSysMonitorTest.java
index 337d96868b9..5a108e0ba73 100644
--- a/processing/src/test/java/org/apache/druid/java/util/metrics/OshiSysMonitorTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/metrics/OshiSysMonitorTest.java
@@ -24,9 +24,9 @@ import com.google.common.collect.ImmutableMap;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.emitter.core.Event;
import org.apache.druid.java.util.emitter.service.ServiceEmitter;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
@@ -52,7 +52,7 @@ public class OshiSysMonitorTest
private HardwareAbstractionLayer hal;
private OperatingSystem os;
- @Before
+ @BeforeEach
public void setUp()
{
si = Mockito.mock(SystemInfo.class);
@@ -71,7 +71,7 @@ public class OshiSysMonitorTest
serviceEmitter.start();
sysMonitorOshi.monitor(serviceEmitter);
- Assert.assertTrue(sysMonitorOshi.doMonitor(serviceEmitter));
+ Assertions.assertTrue(sysMonitorOshi.doMonitor(serviceEmitter));
}
@@ -102,7 +102,7 @@ public class OshiSysMonitorTest
m.start();
m.monitorMemStats(emitter);
m.stop();
- Assert.assertEquals(3, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(3, emitter.getNumEmittedEvents());
emitter.verifyEmitted("sys/mem/max", 1);
emitter.verifyEmitted("sys/mem/used", 1);
emitter.verifyEmitted("sys/mem/free", 1);
@@ -124,7 +124,7 @@ public class OshiSysMonitorTest
m.start();
m.doMonitor(emitter);
m.stop();
- Assert.assertEquals(3, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(3, emitter.getNumEmittedEvents());
emitter.verifyEmitted("sys/mem/max", 1);
emitter.verifyEmitted("sys/mem/used", 1);
emitter.verifyEmitted("sys/mem/free", 1);
@@ -165,7 +165,7 @@ public class OshiSysMonitorTest
OshiSysMonitor m = createMonitor(si);
m.start();
m.monitorSwapStats(emitter);
- Assert.assertEquals(4, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(4, emitter.getNumEmittedEvents());
emitter.verifyEmitted("sys/swap/pageIn", 1);
emitter.verifyEmitted("sys/swap/pageOut", 1);
emitter.verifyEmitted("sys/swap/max", 1);
@@ -213,7 +213,7 @@ public class OshiSysMonitorTest
OshiSysMonitor m = createMonitor(si);
m.start();
m.monitorFsStats(emitter);
- Assert.assertEquals(8, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(8, emitter.getNumEmittedEvents());
emitter.verifyEmitted("sys/fs/max", 2);
emitter.verifyEmitted("sys/fs/used", 2);
emitter.verifyEmitted("sys/fs/files/count", 2);
@@ -225,17 +225,17 @@ public class OshiSysMonitorTest
"/System/Volumes/boot1"
);
List<Number> metricValues1 = emitter.getMetricValues("sys/fs/max", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(300L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(300L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/fs/used", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(100L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(100L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/fs/files/count", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(1000L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(1000L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/fs/files/free", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(700L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(700L, metricValues1.get(0));
Map<String, Object> userDims2 = ImmutableMap.of(
"fsDevName",
@@ -244,17 +244,17 @@ public class OshiSysMonitorTest
"/System/Volumes/boot2"
);
List<Number> metricValues2 = emitter.getMetricValues("sys/fs/max", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(400L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(400L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/fs/used", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(80L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(80L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/fs/files/count", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(800L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(800L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/fs/files/free", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(600L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(600L, metricValues2.get(0));
m.stop();
}
@@ -284,7 +284,7 @@ public class OshiSysMonitorTest
OshiSysMonitor m = createMonitor(si);
m.start();
m.monitorDiskStats(emitter);
- Assert.assertEquals(0, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(0, emitter.getNumEmittedEvents());
Mockito.when(disk1.getReadBytes()).thenReturn(400L);
Mockito.when(disk1.getReads()).thenReturn(220L);
@@ -300,53 +300,53 @@ public class OshiSysMonitorTest
Mockito.when(disk2.getTransferTime()).thenReturn(1100L);
m.monitorDiskStats(emitter);
- Assert.assertEquals(12, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(12, emitter.getNumEmittedEvents());
Map<String, Object> userDims1 = ImmutableMap.of(
"diskName",
"disk1"
);
List<Number> metricValues1 = emitter.getMetricValues("sys/disk/read/size", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(100L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(100L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/disk/read/count", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(20L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(20L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/disk/write/size", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(200L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(200L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/disk/write/count", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(80L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(80L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/disk/queue", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(200L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(200L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/disk/transferTime", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(100L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(100L, metricValues1.get(0));
Map<String, Object> userDims2 = ImmutableMap.of(
"diskName",
"disk2"
);
List<Number> metricValues2 = emitter.getMetricValues("sys/disk/read/size", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(2500L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(2500L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/disk/read/count", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(500L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(500L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/disk/write/size", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(1300L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(1300L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/disk/write/count", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(1000L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(1000L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/disk/queue", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(150L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(150L, metricValues2.get(0));
metricValues2 = emitter.getMetricValues("sys/disk/transferTime", userDims2);
- Assert.assertEquals(1, metricValues2.size());
- Assert.assertEquals(300L, metricValues2.get(0));
+ Assertions.assertEquals(1, metricValues2.size());
+ Assertions.assertEquals(300L, metricValues2.get(0));
m.stop();
}
@@ -374,7 +374,7 @@ public class OshiSysMonitorTest
OshiSysMonitor m = createMonitor(si);
m.start();
m.monitorNetStats(emitter);
- Assert.assertEquals(0, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(0, emitter.getNumEmittedEvents());
Mockito.when(net1.getBytesRecv()).thenReturn(400L);
Mockito.when(net1.getPacketsRecv()).thenReturn(220L);
@@ -387,7 +387,7 @@ public class OshiSysMonitorTest
m.monitorNetStats(emitter);
- Assert.assertEquals(16, emitter.getNumEmittedEvents()); // 8 * 2 whitelisted ips
+ Assertions.assertEquals(16, emitter.getNumEmittedEvents()); // 8 * 2 whitelisted ips
Map<String, Object> userDims1 = ImmutableMap.of(
"netName",
@@ -406,54 +406,54 @@ public class OshiSysMonitorTest
"ha:rd:wa:re:add"
);
List<Number> metricValues1 = emitter.getMetricValues("sys/net/read/size", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(100L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(100L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/read/packets", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(20L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(20L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/read/errors", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(200L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(200L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/read/dropped", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(80L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(80L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/size", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(200L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(200L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/packets", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(100L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(100L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/errors", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(130L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(130L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/collisions", userDims1);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(220L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(220L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/read/size", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(100L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(100L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/read/packets", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(20L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(20L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/read/errors", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(200L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(200L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/read/dropped", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(80L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(80L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/size", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(200L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(200L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/packets", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(100L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(100L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/errors", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(130L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(130L, metricValues1.get(0));
metricValues1 = emitter.getMetricValues("sys/net/write/collisions", userDims2);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(220L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(220L, metricValues1.get(0));
m.stop();
}
@@ -472,7 +472,7 @@ public class OshiSysMonitorTest
OshiSysMonitor m = createMonitor(si);
m.start();
m.monitorCpuStats(emitter);
- Assert.assertEquals(0, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(0, emitter.getNumEmittedEvents());
long[][] procTicks2 = new long[][]{
{4L, 5L, 6L, 8L, 9L, 7L, 10L, 12L}, // Δtick1 {3,3,3,4,4,1,3,4} _total = 25, emitted percentage
@@ -482,76 +482,76 @@ public class OshiSysMonitorTest
m.monitorCpuStats(emitter);
m.stop();
- Assert.assertEquals(16, emitter.getNumEmittedEvents()); // 8 ticktype * 2 processors
+ Assertions.assertEquals(16, emitter.getNumEmittedEvents()); // 8 ticktype * 2 processors
Map<String, Object> userDims = new HashMap<>();
userDims.put("cpuName", "0");
userDims.put("cpuTime", "user");
List<Number> metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(12L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(12L, metricValues1.get(0));
userDims.replace("cpuTime", "nice");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(12L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(12L, metricValues1.get(0));
userDims.replace("cpuTime", "sys");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(12L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(12L, metricValues1.get(0));
userDims.replace("cpuTime", "idle");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(16L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(16L, metricValues1.get(0));
userDims.replace("cpuTime", "wait");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(16L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(16L, metricValues1.get(0));
userDims.replace("cpuTime", "irq");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(4L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(4L, metricValues1.get(0));
userDims.replace("cpuTime", "softIrq");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(12L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(12L, metricValues1.get(0));
userDims.replace("cpuTime", "stolen");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(16L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(16L, metricValues1.get(0));
userDims.replace("cpuName", "1");
userDims.replace("cpuTime", "user");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(10L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(10L, metricValues1.get(0));
userDims.replace("cpuTime", "nice");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(14L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(14L, metricValues1.get(0));
userDims.replace("cpuTime", "sys");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(7L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(7L, metricValues1.get(0));
userDims.replace("cpuTime", "idle");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(7L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(7L, metricValues1.get(0));
userDims.replace("cpuTime", "wait");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(17L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(17L, metricValues1.get(0));
userDims.replace("cpuTime", "irq");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(7L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(7L, metricValues1.get(0));
userDims.replace("cpuTime", "softIrq");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(14L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(14L, metricValues1.get(0));
userDims.replace("cpuTime", "stolen");
metricValues1 = emitter.getMetricValues("sys/cpu", userDims);
- Assert.assertEquals(1, metricValues1.size());
- Assert.assertEquals(21L, metricValues1.get(0));
+ Assertions.assertEquals(1, metricValues1.size());
+ Assertions.assertEquals(21L, metricValues1.get(0));
}
@@ -569,7 +569,7 @@ public class OshiSysMonitorTest
OshiSysMonitor m = createMonitor(si);
m.start();
m.monitorSysStats(emitter);
- Assert.assertEquals(4, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(4, emitter.getNumEmittedEvents());
m.stop();
emitter.verifyEmitted("sys/uptime", 1);
emitter.verifyEmitted("sys/la/1", 1);
@@ -604,7 +604,7 @@ public class OshiSysMonitorTest
m.start();
m.monitorTcpStats(emitter);
- Assert.assertEquals(0, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(0, emitter.getNumEmittedEvents());
Mockito.when(tcpv4.getConnectionsActive()).thenReturn(20L);
Mockito.when(tcpv4.getConnectionsPassive()).thenReturn(25L);
Mockito.when(tcpv4.getConnectionFailures()).thenReturn(8L);
@@ -616,7 +616,7 @@ public class OshiSysMonitorTest
Mockito.when(tcpv4.getSegmentsRetransmitted()).thenReturn(8L);
m.monitorTcpStats(emitter);
m.stop();
- Assert.assertEquals(9, emitter.getNumEmittedEvents());
+ Assertions.assertEquals(9, emitter.getNumEmittedEvents());
emitter.verifyValue("sys/tcpv4/activeOpens", 10L);
emitter.verifyValue("sys/tcpv4/passiveOpens", 5L);
emitter.verifyValue("sys/tcpv4/attemptFails", 3L);
@@ -631,11 +631,11 @@ public class OshiSysMonitorTest
private void checkEvents(List<Event> events, String expectedFeed)
{
- Assert.assertFalse("no events emitted", events.isEmpty());
+ Assertions.assertFalse(events.isEmpty(), "no events emitted");
for (Event e : events) {
if (!expectedFeed.equals(e.getFeed())) {
String message = StringUtils.format("\"feed\" in event: %s", e.toMap().toString());
- Assert.assertEquals(message, expectedFeed, e.getFeed());
+ Assertions.assertEquals(expectedFeed, e.getFeed(), message);
}
}
}
diff --git a/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuAcctTest.java b/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuAcctTest.java
index 65a03842104..2de35f4cc5b 100644
--- a/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuAcctTest.java
+++ b/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuAcctTest.java
@@ -20,12 +20,11 @@
package org.apache.druid.java.util.metrics.cgroups;
import org.apache.druid.java.util.common.FileUtils;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
+import org.apache.druid.testing.TemporaryFolderExtension;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.File;
import java.io.IOException;
@@ -36,15 +35,13 @@ import java.util.stream.LongStream;
public class CpuAcctTest
{
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @RegisterExtension
+ public TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();
private File procDir;
private File cgroupDir;
private CgroupDiscoverer discoverer;
- @Before
+ @BeforeEach
public void setUp() throws IOException
{
cgroupDir = temporaryFolder.newFolder();
@@ -65,9 +62,9 @@ public class CpuAcctTest
{
final CpuAcct cpuAcct = new CpuAcct(TestUtils.exceptionThrowingDiscoverer());
final CpuAcct.CpuAcctMetric metric = cpuAcct.snapshot();
- Assert.assertEquals(0L, metric.cpuCount());
- Assert.assertEquals(0L, metric.usrTime());
- Assert.assertEquals(0L, metric.sysTime());
+ Assertions.assertEquals(0L, metric.cpuCount());
+ Assertions.assertEquals(0L, metric.usrTime());
+ Assertions.assertEquals(0L, metric.sysTime());
}
@Test
@@ -75,8 +72,8 @@ public class CpuAcctTest
{
final CpuAcct cpuAcct = new CpuAcct(discoverer);
final CpuAcct.CpuAcctMetric snapshot = cpuAcct.snapshot();
- Assert.assertEquals(128, snapshot.cpuCount());
- Assert.assertArrayEquals(new long[]{
+ Assertions.assertEquals(128, snapshot.cpuCount());
+ Assertions.assertArrayEquals(new long[]{
7344294132655L,
28183572804378L,
29552215219002L,
@@ -206,7 +203,7 @@ public class CpuAcctTest
38554167083817L,
38870461161179L
}, snapshot.usrTimes());
- Assert.assertArrayEquals(new long[]{
+ Assertions.assertArrayEquals(new long[]{
4583688852335L,
385888457233L,
370465239852L,
@@ -336,9 +333,9 @@ public class CpuAcctTest
53593212339L,
52866253864L
}, snapshot.sysTimes());
- Assert.assertEquals(LongStream.of(snapshot.sysTimes()).sum(), snapshot.sysTime());
- Assert.assertEquals(LongStream.of(snapshot.usrTimes()).sum(), snapshot.usrTime());
- Assert.assertEquals(
+ Assertions.assertEquals(LongStream.of(snapshot.sysTimes()).sum(), snapshot.sysTime());
+ Assertions.assertEquals(LongStream.of(snapshot.usrTimes()).sum(), snapshot.usrTime());
+ Assertions.assertEquals(
LongStream.of(snapshot.sysTimes()).sum() + LongStream.of(snapshot.usrTimes()).sum(),
snapshot.time()
);
@@ -350,15 +347,15 @@ public class CpuAcctTest
final long[] usrTime = new long[]{1, 2, 3};
final long[] sysTime = new long[]{4, 5, 6};
final CpuAcct.CpuAcctMetric metric = new CpuAcct.CpuAcctMetric(usrTime, sysTime);
- Assert.assertEquals(6, metric.usrTime());
- Assert.assertEquals(15, metric.sysTime());
- Assert.assertArrayEquals(usrTime, metric.usrTimes());
- Assert.assertArrayEquals(sysTime, metric.sysTimes());
+ Assertions.assertEquals(6, metric.usrTime());
+ Assertions.assertEquals(15, metric.sysTime());
+ Assertions.assertArrayEquals(usrTime, metric.usrTimes());
+ Assertions.assertArrayEquals(sysTime, metric.sysTimes());
for (int i = 0; i < usrTime.length; ++i) {
- Assert.assertEquals(usrTime[i], metric.usrTime(i));
+ Assertions.assertEquals(usrTime[i], metric.usrTime(i));
}
for (int i = 0; i < sysTime.length; ++i) {
- Assert.assertEquals(sysTime[i], metric.sysTime(i));
+ Assertions.assertEquals(sysTime[i], metric.sysTime(i));
}
}
@@ -380,11 +377,11 @@ public class CpuAcctTest
final CpuAcct.CpuAcctMetric metric0 = new CpuAcct.CpuAcctMetric(zeroes, zeroes);
final CpuAcct.CpuAcctMetric metric1 = new CpuAcct.CpuAcctMetric(usr, sys);
final CpuAcct.CpuAcctMetric diff = metric1.cumulativeSince(metric0);
- Assert.assertEquals(total, diff.usrTime());
- Assert.assertEquals(total << 1, diff.sysTime());
- Assert.assertNotEquals(0, total);
+ Assertions.assertEquals(total, diff.usrTime());
+ Assertions.assertEquals(total << 1, diff.sysTime());
+ Assertions.assertNotEquals(0, total);
final CpuAcct.CpuAcctMetric zeroDiff = metric1.cumulativeSince(metric1);
- Assert.assertEquals(0, zeroDiff.usrTime());
- Assert.assertEquals(0, zeroDiff.sysTime());
+ Assertions.assertEquals(0, zeroDiff.usrTime());
+ Assertions.assertEquals(0, zeroDiff.sysTime());
}
}
diff --git a/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuV2Test.java b/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuV2Test.java
index f789c8829ab..7f171418fb7 100644
--- a/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuV2Test.java
+++ b/processing/src/test/java/org/apache/druid/java/util/metrics/cgroups/CpuV2Test.java
@@ -19,11 +19,11 @@
package org.apache.druid.java.util.metrics.cgroups;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.apache.druid.testing.TemporaryFolderExtension;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.File;
import java.io.IOException;
@@ -33,14 +33,14 @@ import java.nio.file.Paths;
public class CpuV2Test
{
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @RegisterExtension
+ public TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();
private File cgroupDir;
private File procDir;
private CgroupDiscoverer discoverer;
- @Before
+ @BeforeEach
public void setUp() throws IOException
{
cgroupDir = temporaryFolder.newFolder();
@@ -75,14 +75,14 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Verify the conversion from v2 to v1 format
- Assert.assertEquals("Weight should be converted to shares", 2048L, metrics.getShares());
- Assert.assertEquals("Quota should be preserved", 150000L, metrics.getQuotaUs());
- Assert.assertEquals("Period should be preserved", 100000L, metrics.getPeriodUs());
+ Assertions.assertEquals(2048L, metrics.getShares(), "Weight should be converted to shares");
+ Assertions.assertEquals(150000L, metrics.getQuotaUs(), "Quota should be preserved");
+ Assertions.assertEquals(100000L, metrics.getPeriodUs(), "Period should be preserved");
// V2 should not provide jiffies, only microseconds
- Assert.assertEquals("V2 should not provide user jiffies", -1L, metrics.getUserJiffies());
- Assert.assertEquals("V2 should not provide system jiffies", -1L, metrics.getSystemJiffies());
- Assert.assertEquals("V2 should not provide total jiffies", -1L, metrics.getTotalJiffies());
+ Assertions.assertEquals(-1L, metrics.getUserJiffies(), "V2 should not provide user jiffies");
+ Assertions.assertEquals(-1L, metrics.getSystemJiffies(), "V2 should not provide system jiffies");
+ Assertions.assertEquals(-1L, metrics.getTotalJiffies(), "V2 should not provide total jiffies");
}
@Test
@@ -106,11 +106,11 @@ public class CpuV2Test
CpuV2 cpuV2 = new CpuV2(discoverer);
Cpu.CpuMetrics metrics = cpuV2.snapshot();
- Assert.assertEquals("Default weight should convert to default shares", 1024L, metrics.getShares());
- Assert.assertEquals("Max quota should be -1", -1L, metrics.getQuotaUs());
- Assert.assertEquals("Max period should be -1", -1L, metrics.getPeriodUs());
- Assert.assertEquals("V2 should not provide user jiffies", -1L, metrics.getUserJiffies());
- Assert.assertEquals("V2 should not provide system jiffies", -1L, metrics.getSystemJiffies());
+ Assertions.assertEquals(1024L, metrics.getShares(), "Default weight should convert to default shares");
+ Assertions.assertEquals(-1L, metrics.getQuotaUs(), "Max quota should be -1");
+ Assertions.assertEquals(-1L, metrics.getPeriodUs(), "Max period should be -1");
+ Assertions.assertEquals(-1L, metrics.getUserJiffies(), "V2 should not provide user jiffies");
+ Assertions.assertEquals(-1L, metrics.getSystemJiffies(), "V2 should not provide system jiffies");
}
@Test
@@ -121,12 +121,12 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Should return default/error values when files are missing
- Assert.assertEquals("Missing weight should return default shares", -1L, metrics.getShares());
- Assert.assertEquals("Missing quota should be -1", -1L, metrics.getQuotaUs());
- Assert.assertEquals("Missing period should be -1", -1L, metrics.getPeriodUs());
- Assert.assertEquals("Missing user time should be -1", -1L, metrics.getUserJiffies());
- Assert.assertEquals("Missing system time should be -1", -1L, metrics.getSystemJiffies());
- Assert.assertEquals("Missing total should be -1", -1L, metrics.getTotalJiffies());
+ Assertions.assertEquals(-1L, metrics.getShares(), "Missing weight should return default shares");
+ Assertions.assertEquals(-1L, metrics.getQuotaUs(), "Missing quota should be -1");
+ Assertions.assertEquals(-1L, metrics.getPeriodUs(), "Missing period should be -1");
+ Assertions.assertEquals(-1L, metrics.getUserJiffies(), "Missing user time should be -1");
+ Assertions.assertEquals(-1L, metrics.getSystemJiffies(), "Missing system time should be -1");
+ Assertions.assertEquals(-1L, metrics.getTotalJiffies(), "Missing total should be -1");
}
@Test
@@ -150,11 +150,11 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Should handle invalid data gracefully
- Assert.assertEquals("Invalid weight should return default", -1L, metrics.getShares());
- Assert.assertEquals("Invalid quota should be -1", -1L, metrics.getQuotaUs());
- Assert.assertEquals("Invalid period should be -1", -1L, metrics.getPeriodUs());
- Assert.assertEquals("Invalid user time should be -1", -1L, metrics.getUserJiffies());
- Assert.assertEquals("Invalid system time should be -1", -1L, metrics.getSystemJiffies());
+ Assertions.assertEquals(-1L, metrics.getShares(), "Invalid weight should return default");
+ Assertions.assertEquals(-1L, metrics.getQuotaUs(), "Invalid quota should be -1");
+ Assertions.assertEquals(-1L, metrics.getPeriodUs(), "Invalid period should be -1");
+ Assertions.assertEquals(-1L, metrics.getUserJiffies(), "Invalid user time should be -1");
+ Assertions.assertEquals(-1L, metrics.getSystemJiffies(), "Invalid system time should be -1");
}
@Test
@@ -171,7 +171,7 @@ public class CpuV2Test
testWeightConversion(cgroupDir, 10000, 102400); // Maximum weight -> maximum shares
}
catch (IOException e) {
- Assert.fail("IOException during weight conversion test: " + e.getMessage());
+ Assertions.fail("IOException during weight conversion test: " + e.getMessage());
}
}
@@ -193,9 +193,10 @@ public class CpuV2Test
CpuV2 cpuV2 = new CpuV2(discoverer);
Cpu.CpuMetrics metrics = cpuV2.snapshot();
- Assert.assertEquals(
- "Weight " + weight + " should convert to shares " + expectedShares,
- expectedShares, metrics.getShares()
+ Assertions.assertEquals(
+ expectedShares,
+ metrics.getShares(),
+ "Weight " + weight + " should convert to shares " + expectedShares
);
}
@@ -221,9 +222,9 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// V2 should not provide jiffies, only microseconds
- Assert.assertEquals("V2 should not provide user jiffies", -1L, metrics.getUserJiffies());
- Assert.assertEquals("V2 should not provide system jiffies", -1L, metrics.getSystemJiffies());
- Assert.assertEquals("V2 should not provide total jiffies", -1L, metrics.getTotalJiffies());
+ Assertions.assertEquals(-1L, metrics.getUserJiffies(), "V2 should not provide user jiffies");
+ Assertions.assertEquals(-1L, metrics.getSystemJiffies(), "V2 should not provide system jiffies");
+ Assertions.assertEquals(-1L, metrics.getTotalJiffies(), "V2 should not provide total jiffies");
}
@Test
@@ -255,7 +256,7 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Should parse weight correctly and ignore extra cpu.stat fields
- Assert.assertEquals("Weight should be converted", 1536L, metrics.getShares()); // 150 * 1024 / 100
+ Assertions.assertEquals(1536L, metrics.getShares(), "Weight should be converted"); // 150 * 1024 / 100
}
@Test
@@ -283,8 +284,8 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Should handle malformed cpu.max gracefully
- Assert.assertEquals("Invalid cpu.max should result in -1 quota", -1L, metrics.getQuotaUs());
- Assert.assertEquals("Invalid cpu.max should result in -1 period", -1L, metrics.getPeriodUs());
+ Assertions.assertEquals(-1L, metrics.getQuotaUs(), "Invalid cpu.max should result in -1 quota");
+ Assertions.assertEquals(-1L, metrics.getPeriodUs(), "Invalid cpu.max should result in -1 period");
}
@Test
@@ -308,12 +309,12 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// V2 should not provide jiffies, only microseconds
- Assert.assertEquals("V2 should not provide user jiffies", -1L, metrics.getUserJiffies());
- Assert.assertEquals("V2 should not provide system jiffies", -1L, metrics.getSystemJiffies());
- Assert.assertEquals("V2 should not provide total jiffies", -1L, metrics.getTotalJiffies());
- Assert.assertEquals(0, metrics.getUserUs());
- Assert.assertEquals(0, metrics.getSystemUs());
- Assert.assertEquals(-1, metrics.getTotalUs());
+ Assertions.assertEquals(-1L, metrics.getUserJiffies(), "V2 should not provide user jiffies");
+ Assertions.assertEquals(-1L, metrics.getSystemJiffies(), "V2 should not provide system jiffies");
+ Assertions.assertEquals(-1L, metrics.getTotalJiffies(), "V2 should not provide total jiffies");
+ Assertions.assertEquals(0, metrics.getUserUs());
+ Assertions.assertEquals(0, metrics.getSystemUs());
+ Assertions.assertEquals(-1, metrics.getTotalUs());
}
@Test
@@ -339,8 +340,8 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Should handle whitespace correctly
- Assert.assertEquals("Should parse quota with whitespace", 200000L, metrics.getQuotaUs());
- Assert.assertEquals("Should parse period with whitespace", 100000L, metrics.getPeriodUs());
+ Assertions.assertEquals(200000L, metrics.getQuotaUs(), "Should parse quota with whitespace");
+ Assertions.assertEquals(100000L, metrics.getPeriodUs(), "Should parse period with whitespace");
}
@Test
@@ -364,7 +365,7 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Negative weight should result in -1 shares (no limit)
- Assert.assertEquals("Negative weight should result in -1 shares", -1L, metrics.getShares());
+ Assertions.assertEquals(-1L, metrics.getShares(), "Negative weight should result in -1 shares");
}
@Test
@@ -390,7 +391,7 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Zero weight should result in -1 shares (no limit)
- Assert.assertEquals("Zero weight should result in -1 shares", -1L, metrics.getShares());
+ Assertions.assertEquals(-1L, metrics.getShares(), "Zero weight should result in -1 shares");
}
@Test
@@ -418,6 +419,6 @@ public class CpuV2Test
Cpu.CpuMetrics metrics = cpuV2.snapshot();
// Should parse valid weight and handle malformed cpu.stat lines gracefully
- Assert.assertEquals("Should parse valid weight", 1024L, metrics.getShares());
+ Assertions.assertEquals(1024L, metrics.getShares(), "Should parse valid weight");
}
}
diff --git a/processing/src/test/java/org/apache/druid/query/NestedDataTestUtils.java b/processing/src/test/java/org/apache/druid/query/NestedDataTestUtils.java
index 1c328f6229b..38a7ebe0f28 100644
--- a/processing/src/test/java/org/apache/druid/query/NestedDataTestUtils.java
+++ b/processing/src/test/java/org/apache/druid/query/NestedDataTestUtils.java
@@ -50,6 +50,7 @@ import org.apache.druid.segment.column.StringEncodingStrategy;
import org.apache.druid.segment.incremental.IncrementalIndexSchema;
import org.apache.druid.segment.transform.ExpressionTransform;
import org.apache.druid.segment.transform.TransformSpec;
+import org.apache.druid.testing.TemporaryFolderExtension;
import org.apache.druid.timeline.SegmentId;
import org.junit.rules.TemporaryFolder;
@@ -143,6 +144,83 @@ public class NestedDataTestUtils
JSON_MAPPER.registerModules(BuiltInTypesModule.getJacksonModulesList());
}
+ /**
+ * Temporary compatibility bridge for the JUnit 4 {@link TemporaryFolder} and JUnit 5
+ * {@link TemporaryFolderExtension} APIs. The segment builders use this common surface while
+ * both test styles remain in use; remove it with the {@code TemporaryFolder} overloads once
+ * all callers have migrated to {@link TemporaryFolderExtension}.
+ */
+ private interface TempFolderOperations
+ {
+ File newFolder() throws IOException;
+
+ File newFolder(String... folderNames) throws IOException;
+
+ File newFile() throws IOException;
+
+ File newFile(String fileName) throws IOException;
+ }
+
+ private static TempFolderOperations tempFolderOperations(final TemporaryFolder tempFolder)
+ {
+ return new TempFolderOperations()
+ {
+ @Override
+ public File newFolder() throws IOException
+ {
+ return tempFolder.newFolder();
+ }
+
+ @Override
+ public File newFolder(final String... folderNames) throws IOException
+ {
+ return tempFolder.newFolder(folderNames);
+ }
+
+ @Override
+ public File newFile() throws IOException
+ {
+ return tempFolder.newFile();
+ }
+
+ @Override
+ public File newFile(final String fileName) throws IOException
+ {
+ return tempFolder.newFile(fileName);
+ }
+ };
+ }
+
+ private static TempFolderOperations tempFolderOperations(final TemporaryFolderExtension tempFolder)
+ {
+ return new TempFolderOperations()
+ {
+ @Override
+ public File newFolder() throws IOException
+ {
+ return tempFolder.newFolder();
+ }
+
+ @Override
+ public File newFolder(final String... folderNames) throws IOException
+ {
+ return tempFolder.newFolder(folderNames);
+ }
+
+ @Override
+ public File newFile() throws IOException
+ {
+ return tempFolder.newFile();
+ }
+
+ @Override
+ public File newFile(final String fileName) throws IOException
+ {
+ return tempFolder.newFile(fileName);
+ }
+ };
+ }
+
public static List<Segment> createSegmentsWithConcatenatedJsonInput(
TemporaryFolder tempFolder,
Closer closer,
@@ -152,6 +230,48 @@ public class NestedDataTestUtils
int numCopies,
int numSegments
) throws Exception
+ {
+ return createSegmentsWithConcatenatedJsonInput(
+ tempFolderOperations(tempFolder),
+ closer,
+ inputFile,
+ granularity,
+ rollup,
+ numCopies,
+ numSegments
+ );
+ }
+
+ public static List<Segment> createSegmentsWithConcatenatedJsonInput(
+ TemporaryFolderExtension tempFolder,
+ Closer closer,
+ String inputFile,
+ Granularity granularity,
+ boolean rollup,
+ int numCopies,
+ int numSegments
+ ) throws Exception
+ {
+ return createSegmentsWithConcatenatedJsonInput(
+ tempFolderOperations(tempFolder),
+ closer,
+ inputFile,
+ granularity,
+ rollup,
+ numCopies,
+ numSegments
+ );
+ }
+
+ private static List<Segment> createSegmentsWithConcatenatedJsonInput(
+ final TempFolderOperations tempFolder,
+ final Closer closer,
+ final String inputFile,
+ final Granularity granularity,
+ final boolean rollup,
+ final int numCopies,
+ final int numSegments
+ ) throws Exception
{
List<InputSource> inputFiles = Lists.newArrayListWithCapacity(numSegments);
for (int i = 0; i < numSegments; i++) {
@@ -166,8 +286,8 @@ public class NestedDataTestUtils
public static class ResourceFileSegmentBuilder
{
- private TemporaryFolder tempFolder;
- private Closer closer;
+ private final TempFolderOperations tempFolder;
+ private final Closer closer;
private List<InputSource> inputSources =
List.of(ResourceInputSource.of(NestedDataTestUtils.class.getClassLoader(), SIMPLE_DATA_FILE));
@@ -191,6 +311,16 @@ public class NestedDataTestUtils
* <li>use the default index spec</li>
*/
public ResourceFileSegmentBuilder(TemporaryFolder tempFolder, Closer closer)
+ {
+ this(tempFolderOperations(tempFolder), closer);
+ }
+
+ public ResourceFileSegmentBuilder(TemporaryFolderExtension tempFolder, Closer closer)
+ {
+ this(tempFolderOperations(tempFolder), closer);
+ }
+
+ private ResourceFileSegmentBuilder(TempFolderOperations tempFolder, Closer closer)
{
this.tempFolder = tempFolder;
this.closer = closer;
@@ -311,7 +441,40 @@ public class NestedDataTestUtils
) throws Exception
{
return createSegments(
- tempFolder,
+ tempFolderOperations(tempFolder),
+ closer,
+ Collections.singletonList(ResourceInputSource.of(NestedDataTestUtils.class.getClassLoader(), input)),
+ inputFormat,
+ timestampSpec,
+ dimensionsSpec,
+ transformSpec,
+ aggregators,
+ queryGranularity,
+ rollup,
+ indexSpec
+ );
+ }
+
+ /**
+ * @deprecated Use {@link ResourceFileSegmentBuilder} instead.
+ */
+ @Deprecated
+ public static List<Segment> createSegments(
+ TemporaryFolderExtension tempFolder,
+ Closer closer,
+ String input,
+ InputFormat inputFormat,
+ TimestampSpec timestampSpec,
+ DimensionsSpec dimensionsSpec,
+ TransformSpec transformSpec,
+ AggregatorFactory[] aggregators,
+ Granularity queryGranularity,
+ boolean rollup,
+ IndexSpec indexSpec
+ ) throws Exception
+ {
+ return createSegments(
+ tempFolderOperations(tempFolder),
closer,
Collections.singletonList(ResourceInputSource.of(NestedDataTestUtils.class.getClassLoader(), input)),
inputFormat,
@@ -338,6 +501,64 @@ public class NestedDataTestUtils
boolean rollup,
IndexSpec indexSpec
) throws Exception
+ {
+ return createSegments(
+ tempFolderOperations(tempFolder),
+ closer,
+ inputs,
+ inputFormat,
+ timestampSpec,
+ dimensionsSpec,
+ transformSpec,
+ aggregators,
+ queryGranularity,
+ rollup,
+ indexSpec
+ );
+ }
+
+ public static List<Segment> createSegments(
+ TemporaryFolderExtension tempFolder,
+ Closer closer,
+ List<InputSource> inputs,
+ InputFormat inputFormat,
+ TimestampSpec timestampSpec,
+ DimensionsSpec dimensionsSpec,
+ TransformSpec transformSpec,
+ AggregatorFactory[] aggregators,
+ Granularity queryGranularity,
+ boolean rollup,
+ IndexSpec indexSpec
+ ) throws Exception
+ {
+ return createSegments(
+ tempFolderOperations(tempFolder),
+ closer,
+ inputs,
+ inputFormat,
+ timestampSpec,
+ dimensionsSpec,
+ transformSpec,
+ aggregators,
+ queryGranularity,
+ rollup,
+ indexSpec
+ );
+ }
+
+ private static List<Segment> createSegments(
+ final TempFolderOperations tempFolder,
+ final Closer closer,
+ final List<InputSource> inputs,
+ final InputFormat inputFormat,
+ final TimestampSpec timestampSpec,
+ final DimensionsSpec dimensionsSpec,
+ final TransformSpec transformSpec,
+ final AggregatorFactory[] aggregators,
+ final Granularity queryGranularity,
+ final boolean rollup,
+ final IndexSpec indexSpec
+ ) throws Exception
{
final List<Segment> segments = Lists.newArrayListWithCapacity(inputs.size());
for (InputSource inputSource : inputs) {
@@ -378,6 +599,24 @@ public class NestedDataTestUtils
String inputFileName,
int numCopies
) throws IOException
+ {
+ return selfConcatenateResourceFile(tempFolderOperations(tempFolder), inputFileName, numCopies);
+ }
+
+ public static File selfConcatenateResourceFile(
+ TemporaryFolderExtension tempFolder,
+ String inputFileName,
+ int numCopies
+ ) throws IOException
+ {
+ return selfConcatenateResourceFile(tempFolderOperations(tempFolder), inputFileName, numCopies);
+ }
+
+ private static File selfConcatenateResourceFile(
+ final TempFolderOperations tempFolder,
+ final String inputFileName,
+ final int numCopies
+ ) throws IOException
{
List<InputStream> inputStreams = Lists.newArrayListWithCapacity(numCopies);
for (int i = 0; i < numCopies; i++) {
@@ -516,4 +755,115 @@ public class NestedDataTestUtils
{
return DEFAULT_SEGMENTS_NAME.equals(name) || FRONT_CODED_SEGMENTS_NAME.equals(name);
}
+ public static List<BiFunction<TemporaryFolderExtension, Closer, List<Segment>>> getSegmentGeneratorsWithTempDir(
+ String jsonInputFile
+ )
+ {
+ final List<BiFunction<TemporaryFolderExtension, Closer, List<Segment>>> segmentsGenerators =
+ new ArrayList<>();
+ segmentsGenerators.add(new BiFunction<>()
+ {
+ @Override
+ public List<Segment> apply(TemporaryFolderExtension tempFolder, Closer closer)
+ {
+ try {
+ return ImmutableList.<Segment>builder()
+ .addAll(new ResourceFileSegmentBuilder(tempFolder, closer).input(jsonInputFile).build())
+ .add(new ResourceFileSegmentBuilder(tempFolder, null).input(jsonInputFile).buildIncremental())
+ .build();
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return MIX_SEGMENTS_NAME;
+ }
+ });
+ segmentsGenerators.add(new BiFunction<>()
+ {
+ @Override
+ public List<Segment> apply(TemporaryFolderExtension tempFolder, Closer closer)
+ {
+ try {
+ return ImmutableList.of(
+ new ResourceFileSegmentBuilder(tempFolder, null).input(jsonInputFile).buildIncremental(),
+ new ResourceFileSegmentBuilder(tempFolder, null).input(jsonInputFile).buildIncremental()
+ );
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return INCREMENTAL_SEGMENTS_NAME;
+ }
+ });
+ segmentsGenerators.add(new BiFunction<>()
+ {
+ @Override
+ public List<Segment> apply(TemporaryFolderExtension tempFolder, Closer closer)
+ {
+ try {
+ return ImmutableList.<Segment>builder()
+ .addAll(new ResourceFileSegmentBuilder(tempFolder, closer).input(jsonInputFile).build())
+ .addAll(new ResourceFileSegmentBuilder(tempFolder, closer).input(jsonInputFile).build())
+ .build();
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return DEFAULT_SEGMENTS_NAME;
+ }
+ });
+ segmentsGenerators.add(new BiFunction<>()
+ {
+ @Override
+ public List<Segment> apply(TemporaryFolderExtension tempFolder, Closer closer)
+ {
+ try {
+ return Stream.of(
+ new StringEncodingStrategy.FrontCoded(4, (byte) 0x01),
+ new StringEncodingStrategy.FrontCoded(4, (byte) 0x00)
+ )
+ .map(strategy -> IndexSpec.builder().withStringDictionaryEncoding(strategy).build())
+ .map(indexSpec -> {
+ try {
+ return new ResourceFileSegmentBuilder(tempFolder, closer).input(jsonInputFile)
+ .indexSpec(indexSpec)
+ .build();
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+
+ }).flatMap(Collection::stream)
+ .collect(Collectors.toList());
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return FRONT_CODED_SEGMENTS_NAME;
+ }
+ });
+ return segmentsGenerators;
+ }
+
+
}
diff --git a/processing/src/test/java/org/apache/druid/segment/CloserExtension.java b/processing/src/test/java/org/apache/druid/segment/CloserExtension.java
new file mode 100644
index 00000000000..0a4874a36d8
--- /dev/null
+++ b/processing/src/test/java/org/apache/druid/segment/CloserExtension.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.segment;
+
+import org.apache.druid.java.util.common.io.Closer;
+import org.apache.druid.java.util.common.logger.Logger;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
+
+import java.io.Closeable;
+import java.io.IOException;
+
+/**
+ * JUnit 5 counterpart to {@link CloserRule}. The rule remains available for tests that have not
+ * migrated yet.
+ */
+public class CloserExtension implements BeforeEachCallback, AfterEachCallback, TestExecutionExceptionHandler
+{
+ private static final Logger LOG = new Logger(CloserExtension.class);
+
+ private final boolean throwException;
+ private Closer closer;
+
+ public CloserExtension()
+ {
+ this(false);
+ }
+
+ public CloserExtension(final boolean throwException)
+ {
+ this.throwException = throwException;
+ }
+
+ @Override
+ public void beforeEach(final ExtensionContext context)
+ {
+ if (closer == null) {
+ closer = Closer.create();
+ }
+ }
+
+ @Override
+ public void afterEach(final ExtensionContext context) throws IOException
+ {
+ if (closer != null) {
+ try {
+ closer.close();
+ }
+ finally {
+ closer = null;
+ }
+ }
+ }
+
+ @Override
+ public void handleTestExecutionException(final ExtensionContext context, final Throwable throwable) throws Throwable
+ {
+ if (closer == null) {
+ throw throwable;
+ }
+ throw closer.rethrow(throwable);
+ }
+
+ public <T extends Closeable> T closeLater(final T closeable)
+ {
+ if (closer == null) {
+ closer = Closer.create();
+ }
+
+ closer.register(
+ new Closeable()
+ {
+ @Override
+ public void close() throws IOException
+ {
+ if (throwException) {
+ closeable.close();
+ } else {
+ try {
+ closeable.close();
+ }
+ catch (IOException e) {
+ LOG.warn(e, "Error closing [%s]", closeable);
+ }
+ }
+ }
+ }
+ );
+ return closeable;
+ }
+}
diff --git a/processing/src/test/java/org/apache/druid/testing/TemporaryFolderExtension.java b/processing/src/test/java/org/apache/druid/testing/TemporaryFolderExtension.java
new file mode 100644
index 00000000000..756e6b11313
--- /dev/null
+++ b/processing/src/test/java/org/apache/druid/testing/TemporaryFolderExtension.java
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.testing;
+
+import org.apache.druid.java.util.common.FileUtils;
+import org.junit.jupiter.api.extension.AfterAllCallback;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeAllCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * JUnit 5 extension that creates a temporary folder for each test and removes it afterward.
+ * Register it as follows:
+ *
+ * <pre>{@code
+ * @RegisterExtension
+ * public final TemporaryFolderExtension temporaryFolder = new TemporaryFolderExtension();
+ * }</pre>
+ */
+public class TemporaryFolderExtension implements BeforeAllCallback, BeforeEachCallback, AfterAllCallback, AfterEachCallback
+{
+ private final File parentDirectory;
+ private File root;
+
+ public TemporaryFolderExtension()
+ {
+ this(null);
+ }
+
+ public TemporaryFolderExtension(final File parentDirectory)
+ {
+ this.parentDirectory = parentDirectory;
+ }
+
+ @Override
+ public void beforeAll(final ExtensionContext context) throws IOException
+ {
+ create();
+ }
+
+ @Override
+ public void beforeEach(final ExtensionContext context) throws IOException
+ {
+ create();
+ }
+
+ @Override
+ public void afterAll(final ExtensionContext context) throws IOException
+ {
+ delete();
+ }
+
+ @Override
+ public void afterEach(final ExtensionContext context) throws IOException
+ {
+ delete();
+ }
+
+ public void create() throws IOException
+ {
+ if (root == null) {
+ root = parentDirectory == null
+ ? FileUtils.createTempDir("junit")
+ : FileUtils.createTempDirInLocation(parentDirectory.toPath(), "junit");
+ }
+ }
+
+ public File getRoot()
+ {
+ ensureCreated();
+ return root;
+ }
+
+ public File newFolder() throws IOException
+ {
+ ensureCreated();
+ return FileUtils.createTempDirInLocation(root.toPath(), "junit");
+ }
+
+ public File newFolder(final String... folderNames) throws IOException
+ {
+ ensureCreated();
+ File folder = root;
+ for (final String folderName : folderNames) {
+ folder = new File(folder, folderName);
+ }
+ FileUtils.mkdirp(folder);
+ return folder;
+ }
+
+ public File newFile() throws IOException
+ {
+ ensureCreated();
+ return File.createTempFile("junit", null, root);
+ }
+
+ public File newFile(final String fileName) throws IOException
+ {
+ ensureCreated();
+ final File file = new File(root, fileName);
+ if (!file.createNewFile()) {
+ throw new IOException("Unable to create temporary file " + file);
+ }
+ return file;
+ }
+
+ public void delete() throws IOException
+ {
+ if (root != null) {
+ FileUtils.deleteDirectory(root);
+ root = null;
+ }
+ }
+
+ private void ensureCreated()
+ {
+ try {
+ create();
+ }
+ catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/processing/src/test/java/org/apache/druid/testing/junit/LoggerCaptureExtension.java b/processing/src/test/java/org/apache/druid/testing/junit/LoggerCaptureExtension.java
new file mode 100644
index 00000000000..69d05485ca5
--- /dev/null
+++ b/processing/src/test/java/org/apache/druid/testing/junit/LoggerCaptureExtension.java
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.testing.junit;
+
+import com.google.common.collect.ImmutableList;
+import com.google.errorprone.annotations.concurrent.GuardedBy;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.LoggerContext;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Configuration;
+import org.apache.logging.log4j.core.config.LoggerConfig;
+import org.apache.logging.log4j.core.config.Property;
+import org.junit.jupiter.api.extension.AfterEachCallback;
+import org.junit.jupiter.api.extension.BeforeEachCallback;
+import org.junit.jupiter.api.extension.ExtensionContext;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * JUnit 5 extension that captures Log4j events emitted by a target class.
+ * Register it with {@code new LoggerCaptureExtension(TargetClass.class)} and inspect {@link #getLogEvents()}.
+ */
+public class LoggerCaptureExtension implements BeforeEachCallback, AfterEachCallback
+{
+ private final Class<?> targetClass;
+ private InMemoryAppender inMemoryAppender;
+ private LoggerConfig targetClassLoggerConfig;
+
+ public LoggerCaptureExtension(final Class<?> targetClass)
+ {
+ this.targetClass = targetClass;
+ }
+
+ @Override
+ public void beforeEach(final ExtensionContext context)
+ {
+ inMemoryAppender = new InMemoryAppender(targetClass);
+ final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
+ final Configuration configuration = loggerContext.getConfiguration();
+ targetClassLoggerConfig = configuration.getLoggerConfig(targetClass.getName());
+ targetClassLoggerConfig.addAppender(inMemoryAppender, Level.ALL, null);
+ }
+
+ @Override
+ public void afterEach(final ExtensionContext context)
+ {
+ clearLogEvents();
+ targetClassLoggerConfig.removeAppender(InMemoryAppender.NAME);
+ }
+
+ public List<LogEvent> getLogEvents()
+ {
+ return inMemoryAppender.getLogEvents();
+ }
+
+ public void clearLogEvents()
+ {
+ inMemoryAppender.clearLogEvents();
+ }
+
+ public void awaitLogEvents() throws InterruptedException
+ {
+ inMemoryAppender.awaitLogEvents();
+ }
+
+ private static class InMemoryAppender extends AbstractAppender
+ {
+ private static final String NAME = InMemoryAppender.class.getName();
+ private final String targetLoggerName;
+ @GuardedBy("logEvents")
+ private final List<LogEvent> logEvents = new ArrayList<>();
+
+ InMemoryAppender(final Class<?> targetClass)
+ {
+ super(NAME, null, null, true, Property.EMPTY_ARRAY);
+ targetLoggerName = targetClass.getName();
+ }
+
+ @Override
+ public void append(final LogEvent logEvent)
+ {
+ synchronized (logEvents) {
+ if (logEvent.getLoggerName().equals(targetLoggerName)) {
+ logEvents.add(logEvent);
+ logEvents.notifyAll();
+ }
+ }
+ }
+
+ List<LogEvent> getLogEvents()
+ {
+ synchronized (logEvents) {
+ return ImmutableList.copyOf(logEvents);
+ }
+ }
+
+ void clearLogEvents()
+ {
+ synchronized (logEvents) {
+ logEvents.clear();
+ }
+ }
+
+ void awaitLogEvents() throws InterruptedException
+ {
+ synchronized (logEvents) {
+ while (logEvents.isEmpty()) {
+ logEvents.wait();
+ }
+ }
+ }
+ }
+}
diff --git a/processing/src/test/java/org/apache/druid/timeline/DataSegmentTest.java b/processing/src/test/java/org/apache/druid/timeline/DataSegmentTest.java
index e555f81cae5..c0a97ae2344 100644
--- a/processing/src/test/java/org/apache/druid/timeline/DataSegmentTest.java
+++ b/processing/src/test/java/org/apache/druid/timeline/DataSegmentTest.java
@@ -48,9 +48,9 @@ import org.apache.druid.timeline.partition.NumberedShardSpec;
import org.apache.druid.timeline.partition.ShardSpec;
import org.apache.druid.timeline.partition.TombstoneShardSpec;
import org.joda.time.Interval;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
@@ -66,7 +66,7 @@ public class DataSegmentTest
private static final ObjectMapper MAPPER = new DefaultObjectMapper();
private static final int TEST_VERSION = 0x9;
- @Before
+ @BeforeEach
public void setUp()
{
InjectableValues.Std injectableValues = new InjectableValues.Std();
@@ -123,30 +123,30 @@ public class DataSegmentTest
MAPPER.writeValueAsString(segment),
JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT
);
- Assert.assertEquals(13, objectMap.size());
- Assert.assertEquals("something_2011-10-01T00:00:00.000Z_2011-10-02T00:00:00.000Z_1_3", objectMap.get("identifier"));
- Assert.assertEquals("something", objectMap.get("dataSource"));
- Assert.assertEquals(interval.toString(), objectMap.get("interval"));
- Assert.assertEquals("1", objectMap.get("version"));
- Assert.assertEquals(loadSpec, objectMap.get("loadSpec"));
- Assert.assertEquals("dim1,dim2", objectMap.get("dimensions"));
- Assert.assertEquals("met1,met2", objectMap.get("metrics"));
- Assert.assertEquals("proj1,proj2", objectMap.get("projections"));
- Assert.assertEquals(
+ Assertions.assertEquals(13, objectMap.size());
+ Assertions.assertEquals("something_2011-10-01T00:00:00.000Z_2011-10-02T00:00:00.000Z_1_3", objectMap.get("identifier"));
+ Assertions.assertEquals("something", objectMap.get("dataSource"));
+ Assertions.assertEquals(interval.toString(), objectMap.get("interval"));
+ Assertions.assertEquals("1", objectMap.get("version"));
+ Assertions.assertEquals(loadSpec, objectMap.get("loadSpec"));
+ Assertions.assertEquals("dim1,dim2", objectMap.get("dimensions"));
+ Assertions.assertEquals("met1,met2", objectMap.get("metrics"));
+ Assertions.assertEquals("proj1,proj2", objectMap.get("projections"));
+ Assertions.assertEquals(
ImmutableMap.of("type", "numbered", "partitionNum", 3, "partitions", 0),
objectMap.get("shardSpec")
);
- Assert.assertEquals(TEST_VERSION, objectMap.get("binaryVersion"));
- Assert.assertEquals(123, objectMap.get("size"));
- Assert.assertEquals(12, objectMap.get("totalRows"));
- Assert.assertEquals(6, ((Map) objectMap.get("lastCompactionState")).size());
+ Assertions.assertEquals(TEST_VERSION, objectMap.get("binaryVersion"));
+ Assertions.assertEquals(123, objectMap.get("size"));
+ Assertions.assertEquals(12, objectMap.get("totalRows"));
+ Assertions.assertEquals(6, ((Map) objectMap.get("lastCompactionState")).size());
// another act & assert
DataSegment deserializedSegment = MAPPER.readValue(MAPPER.writeValueAsString(segment), DataSegment.class);
- Assert.assertEquals(segment.toString(), deserializedSegment.toString());
- Assert.assertEquals(segment, deserializedSegment);
- Assert.assertEquals(0, segment.compareTo(deserializedSegment));
- Assert.assertEquals(0, deserializedSegment.compareTo(segment));
- Assert.assertEquals(segment.hashCode(), deserializedSegment.hashCode());
+ Assertions.assertEquals(segment.toString(), deserializedSegment.toString());
+ Assertions.assertEquals(segment, deserializedSegment);
+ Assertions.assertEquals(0, segment.compareTo(deserializedSegment));
+ Assertions.assertEquals(0, deserializedSegment.compareTo(segment));
+ Assertions.assertEquals(segment.hashCode(), deserializedSegment.hashCode());
}
@Test
@@ -206,27 +206,27 @@ public class DataSegmentTest
JacksonUtils.TYPE_REFERENCE_MAP_STRING_OBJECT
);
- Assert.assertEquals(11, objectMap.size());
- Assert.assertEquals("something", objectMap.get("dataSource"));
- Assert.assertEquals(interval.toString(), objectMap.get("interval"));
- Assert.assertEquals("1", objectMap.get("version"));
- Assert.assertEquals(loadSpec, objectMap.get("loadSpec"));
- Assert.assertEquals("dim1,dim2", objectMap.get("dimensions"));
- Assert.assertEquals("met1,met2", objectMap.get("metrics"));
- Assert.assertEquals(
+ Assertions.assertEquals(11, objectMap.size());
+ Assertions.assertEquals("something", objectMap.get("dataSource"));
+ Assertions.assertEquals(interval.toString(), objectMap.get("interval"));
+ Assertions.assertEquals("1", objectMap.get("version"));
+ Assertions.assertEquals(loadSpec, objectMap.get("loadSpec"));
+ Assertions.assertEquals("dim1,dim2", objectMap.get("dimensions"));
+ Assertions.assertEquals("met1,met2", objectMap.get("metrics"));
+ Assertions.assertEquals(
ImmutableMap.of("type", "numbered", "partitionNum", 3, "partitions", 0),
objectMap.get("shardSpec")
);
- Assert.assertEquals(TEST_VERSION, objectMap.get("binaryVersion"));
- Assert.assertEquals(1, objectMap.get("size"));
- Assert.assertEquals(6, ((Map) objectMap.get("lastCompactionState")).size());
+ Assertions.assertEquals(TEST_VERSION, objectMap.get("binaryVersion"));
+ Assertions.assertEquals(1, objectMap.get("size"));
+ Assertions.assertEquals(6, ((Map) objectMap.get("lastCompactionState")).size());
DataSegment deserializedSegment = MAPPER.readValue(MAPPER.writeValueAsString(segment), DataSegment.class);
- Assert.assertEquals(segment.toString(), deserializedSegment.toString());
- Assert.assertEquals(segment, deserializedSegment);
- Assert.assertEquals(0, segment.compareTo(deserializedSegment));
- Assert.assertEquals(0, deserializedSegment.compareTo(segment));
- Assert.assertEquals(segment.hashCode(), deserializedSegment.hashCode());
+ Assertions.assertEquals(segment.toString(), deserializedSegment.toString());
+ Assertions.assertEquals(segment, deserializedSegment);
+ Assertions.assertEquals(0, segment.compareTo(deserializedSegment));
... 2636 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org