From 9df59775619e43a1ae2669b47669cdeeda889871 Mon Sep 17 00:00:00 2001 From: Clint Wylie Date: Fri, 19 Jun 2026 02:18:26 -0700 Subject: [PATCH 1/4] test:convert tests in druid-processing to junit5 pt. 9 --- .../druid/collections/BlockingPoolTest.java | 146 ++++++++------- .../common/guava/CombiningSequenceTest.java | 45 +++-- .../input/impl/RetryingInputStreamTest.java | 50 +++--- .../field/DoubleArrayFieldReaderTest.java | 63 ++++--- .../frame/field/DoubleFieldReaderTest.java | 124 +++++++------ .../field/FloatArrayFieldReaderTest.java | 62 +++---- .../frame/field/FloatFieldReaderTest.java | 124 +++++++------ .../druid/frame/field/TransformUtilsTest.java | 50 +++--- .../granularity/UniformGranularityTest.java | 79 ++++---- .../MemoryBoundLinkedBlockingQueueTest.java | 98 +++++----- .../concurrent/ScheduledExecutorsTest.java | 64 +++---- .../util/common/guava/ConcatSequenceTest.java | 24 +-- .../util/common/guava/MergeSequenceTest.java | 121 ++++++------- .../util/common/lifecycle/LifecycleTest.java | 40 ++--- .../parsers/FlatTextFormatParserTest.java | 110 ++++++------ .../apache/druid/query/DataSourceTest.java | 54 +++--- .../druid/query/InlineDataSourceTest.java | 103 +++++------ .../apache/druid/query/QueryContextsTest.java | 135 +++++++------- .../druid/query/TimewarpOperatorTest.java | 24 ++- .../aggregation/AggregatorFactoryTest.java | 24 +-- .../CardinalityVectorAggregatorTest.java | 16 +- .../DoubleFirstVectorAggregatorTest.java | 34 ++-- .../first/FloatFirstVectorAggregatorTest.java | 44 +++-- .../first/LongFirstVectorAggregatorTest.java | 38 ++-- .../last/DoubleLastVectorAggregatorTest.java | 34 ++-- .../last/FloatLastVectorAggregatorTest.java | 38 ++-- .../query/cache/CacheKeyBuilderTest.java | 24 +-- .../extraction/FunctionalExtractionTest.java | 57 +++--- ...alueMatcherColumnProcessorFactoryTest.java | 108 +++++------ .../druid/query/groupby/GroupByQueryTest.java | 42 ++--- .../epinephelinae/SpillOutputStreamTest.java | 109 +++++------ .../metadata/metadata/ColumnAnalysisTest.java | 36 ++-- .../search/SearchQueryRunnerWithCaseTest.java | 53 +++--- .../topn/TopNMetricSpecOptimizationsTest.java | 24 +-- .../druid/query/topn/TopNQueryTest.java | 169 +++++++++--------- .../druid/segment/CursorBuildSpecTest.java | 50 +++--- .../org/apache/druid/segment/IndexIOTest.java | 47 +++-- .../QueryableIndexCursorFactoryTest.java | 138 +++++++------- .../CompressedColumnarIntsSerializerTest.java | 136 +++++++------- .../data/NumericNullColumnSelectorTest.java | 32 ++-- .../filter/ExtractionDimFilterTest.java | 56 +++--- .../join/JoinConditionAnalysisTest.java | 160 ++++++++--------- .../join/lookup/LookupJoinableTest.java | 54 +++--- .../ScalarDoubleColumnSupplierTest.java | 84 ++++----- .../nested/ScalarLongColumnSupplierTest.java | 84 ++++----- .../ScalarStringColumnSupplierTest.java | 94 +++++----- ...eIndexVectorColumnSelectorFactoryTest.java | 85 +++++---- ...ListFilteredVirtualColumnSelectorTest.java | 38 ++-- .../partition/NumberedShardSpecTest.java | 60 +++---- 49 files changed, 1711 insertions(+), 1773 deletions(-) diff --git a/processing/src/test/java/org/apache/druid/collections/BlockingPoolTest.java b/processing/src/test/java/org/apache/druid/collections/BlockingPoolTest.java index 43a681b7807c..b01eac047e0d 100644 --- a/processing/src/test/java/org/apache/druid/collections/BlockingPoolTest.java +++ b/processing/src/test/java/org/apache/druid/collections/BlockingPoolTest.java @@ -22,12 +22,11 @@ import com.google.common.base.Suppliers; import com.google.common.collect.Iterables; import org.apache.druid.java.util.common.concurrent.Execs; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import java.util.ArrayList; import java.util.List; @@ -43,10 +42,7 @@ public class BlockingPoolTest private CloseableDefaultBlockingPool pool; private CloseableDefaultBlockingPool emptyPool; - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before + @BeforeEach public void setup() { service = Execs.multiThreaded(2, "blocking-pool-test"); @@ -54,7 +50,7 @@ public void setup() emptyPool = new CloseableDefaultBlockingPool<>(Suppliers.ofInstance(1), 0); } - @After + @AfterEach public void teardown() { pool.close(); @@ -62,72 +58,81 @@ public void teardown() service.shutdownNow(); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testParallelInit() { DefaultBlockingPool parallelPool = new DefaultBlockingPool<>(Suppliers.ofInstance(1), 10, true); - Assert.assertEquals(10, parallelPool.getPoolSize()); + Assertions.assertEquals(10, parallelPool.getPoolSize()); final ReferenceCountingResourceHolder holder = Iterables.getOnlyElement(parallelPool.takeBatch(1, 100), null); - Assert.assertNotNull(holder); - Assert.assertEquals(9, parallelPool.getPoolSize()); + Assertions.assertNotNull(holder); + Assertions.assertEquals(9, parallelPool.getPoolSize()); holder.close(); - Assert.assertEquals(10, parallelPool.getPoolSize()); + Assertions.assertEquals(10, parallelPool.getPoolSize()); } @Test public void testTakeFromEmptyPool() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Pool was initialized with limit = 0, there are no objects to take."); - emptyPool.takeBatch(1, 0); + final IllegalStateException e = Assertions.assertThrows( + IllegalStateException.class, + () -> emptyPool.takeBatch(1, 0) + ); + Assertions.assertTrue(e.getMessage().contains("Pool was initialized with limit = 0, there are no objects to take.")); } @Test public void testDrainFromEmptyPool() { - expectedException.expect(IllegalStateException.class); - expectedException.expectMessage("Pool was initialized with limit = 0, there are no objects to take."); - emptyPool.takeBatch(1, 0); + final IllegalStateException e = Assertions.assertThrows( + IllegalStateException.class, + () -> emptyPool.takeBatch(1, 0) + ); + Assertions.assertTrue(e.getMessage().contains("Pool was initialized with limit = 0, there are no objects to take.")); } - @Test(timeout = 60_000L) + @Test +@Timeout(60) public void testTake() { final ReferenceCountingResourceHolder holder = Iterables.getOnlyElement(pool.takeBatch(1, 100), null); - Assert.assertNotNull(holder); - Assert.assertEquals(9, pool.getPoolSize()); + Assertions.assertNotNull(holder); + Assertions.assertEquals(9, pool.getPoolSize()); holder.close(); - Assert.assertEquals(10, pool.getPoolSize()); + Assertions.assertEquals(10, pool.getPoolSize()); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testTakeTimeout() { final List> batchHolder = pool.takeBatch(10, 100L); final ReferenceCountingResourceHolder holder = Iterables.getOnlyElement(pool.takeBatch(1, 100), null); - Assert.assertNull(holder); + Assertions.assertNull(holder); batchHolder.forEach(ReferenceCountingResourceHolder::close); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testTakeBatch() { final List> holder = pool.takeBatch(6, 100L); - Assert.assertNotNull(holder); - Assert.assertEquals(6, holder.size()); - Assert.assertEquals(4, pool.getPoolSize()); + Assertions.assertNotNull(holder); + Assertions.assertEquals(6, holder.size()); + Assertions.assertEquals(4, pool.getPoolSize()); holder.forEach(ReferenceCountingResourceHolder::close); - Assert.assertEquals(10, pool.getPoolSize()); + Assertions.assertEquals(10, pool.getPoolSize()); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testWaitAndTakeBatch() throws InterruptedException, ExecutionException { List> batchHolder = pool.takeBatch(10, 10); - Assert.assertNotNull(batchHolder); - Assert.assertEquals(10, batchHolder.size()); - Assert.assertEquals(0, pool.getPoolSize()); + Assertions.assertNotNull(batchHolder); + Assertions.assertEquals(10, batchHolder.size()); + Assertions.assertEquals(0, pool.getPoolSize()); final Future>> future = service.submit( () -> pool.takeBatch(8, 100) @@ -136,22 +141,24 @@ public void testWaitAndTakeBatch() throws InterruptedException, ExecutionExcepti batchHolder.forEach(ReferenceCountingResourceHolder::close); batchHolder = future.get(); - Assert.assertNotNull(batchHolder); - Assert.assertEquals(8, batchHolder.size()); - Assert.assertEquals(2, pool.getPoolSize()); + Assertions.assertNotNull(batchHolder); + Assertions.assertEquals(8, batchHolder.size()); + Assertions.assertEquals(2, pool.getPoolSize()); batchHolder.forEach(ReferenceCountingResourceHolder::close); - Assert.assertEquals(10, pool.getPoolSize()); + Assertions.assertEquals(10, pool.getPoolSize()); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testTakeBatchTooManyObjects() { final List> holder = pool.takeBatch(100, 100L); - Assert.assertTrue(holder.isEmpty()); + Assertions.assertTrue(holder.isEmpty()); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testConcurrentTake() throws ExecutionException, InterruptedException { final int limit1 = pool.maxSize() / 2; @@ -179,8 +186,8 @@ public void testConcurrentTake() throws ExecutionException, InterruptedException final List> r1 = f1.get(); final List> r2 = f2.get(); - Assert.assertEquals(0, pool.getPoolSize()); - Assert.assertTrue(r1.contains(null) || r2.contains(null)); + Assertions.assertEquals(0, pool.getPoolSize()); + Assertions.assertTrue(r1.contains(null) || r2.contains(null)); int nonNullCount = 0; for (ReferenceCountingResourceHolder holder : r1) { @@ -194,7 +201,7 @@ public void testConcurrentTake() throws ExecutionException, InterruptedException nonNullCount++; } } - Assert.assertEquals(pool.maxSize(), nonNullCount); + Assertions.assertEquals(pool.maxSize(), nonNullCount); final Future future1 = service.submit(() -> { for (ReferenceCountingResourceHolder holder : r1) { @@ -214,10 +221,11 @@ public void testConcurrentTake() throws ExecutionException, InterruptedException future1.get(); future2.get(); - Assert.assertEquals(pool.maxSize(), pool.getPoolSize()); + Assertions.assertEquals(pool.maxSize(), pool.getPoolSize()); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testConcurrentTakeBatch() throws ExecutionException, InterruptedException { final int batch1 = pool.maxSize() / 2; @@ -233,21 +241,22 @@ public void testConcurrentTakeBatch() throws ExecutionException, InterruptedExce final List> r2 = f2.get(); if (!r1.isEmpty()) { - Assert.assertTrue(r2.isEmpty()); - Assert.assertEquals(pool.maxSize() - batch1, pool.getPoolSize()); - Assert.assertEquals(batch1, r1.size()); + Assertions.assertTrue(r2.isEmpty()); + Assertions.assertEquals(pool.maxSize() - batch1, pool.getPoolSize()); + Assertions.assertEquals(batch1, r1.size()); r1.forEach(ReferenceCountingResourceHolder::close); } else { - Assert.assertNotNull(r2); - Assert.assertEquals(pool.maxSize() - batch2, pool.getPoolSize()); - Assert.assertEquals(batch2, r2.size()); + Assertions.assertNotNull(r2); + Assertions.assertEquals(pool.maxSize() - batch2, pool.getPoolSize()); + Assertions.assertEquals(batch2, r2.size()); r2.forEach(ReferenceCountingResourceHolder::close); } - Assert.assertEquals(pool.maxSize(), pool.getPoolSize()); + Assertions.assertEquals(pool.maxSize(), pool.getPoolSize()); } - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testConcurrentBatchClose() throws ExecutionException, InterruptedException { final int batch1 = pool.maxSize() / 2; @@ -262,11 +271,11 @@ public void testConcurrentBatchClose() throws ExecutionException, InterruptedExc final List> r1 = f1.get(); final List> r2 = f2.get(); - Assert.assertNotNull(r1); - Assert.assertNotNull(r2); - Assert.assertEquals(batch1, r1.size()); - Assert.assertEquals(batch2, r2.size()); - Assert.assertEquals(0, pool.getPoolSize()); + Assertions.assertNotNull(r1); + Assertions.assertNotNull(r2); + Assertions.assertEquals(batch1, r1.size()); + Assertions.assertEquals(batch2, r2.size()); + Assertions.assertEquals(0, pool.getPoolSize()); final Future future1 = service.submit(() -> r1.forEach(ReferenceCountingResourceHolder::close)); final Future future2 = service.submit(() -> r2.forEach(ReferenceCountingResourceHolder::close)); @@ -274,11 +283,12 @@ public void testConcurrentBatchClose() throws ExecutionException, InterruptedExc future1.get(); future2.get(); - Assert.assertEquals(pool.maxSize(), pool.getPoolSize()); + Assertions.assertEquals(pool.maxSize(), pool.getPoolSize()); } @SuppressWarnings("CatchMayIgnoreException") - @Test(timeout = 60_000L) + @Test + @Timeout(60) public void testConcurrentTakeBatchClose() throws ExecutionException, InterruptedException { final List> r1 = pool.takeBatch(1, 10); @@ -298,11 +308,11 @@ public void testConcurrentTakeBatchClose() throws ExecutionException, Interrupte final List> r2 = f2.get(); f1.get(); - Assert.assertNotNull(r2); - Assert.assertEquals(10, r2.size()); - Assert.assertEquals(0, pool.getPoolSize()); + Assertions.assertNotNull(r2); + Assertions.assertEquals(10, r2.size()); + Assertions.assertEquals(0, pool.getPoolSize()); r2.forEach(ReferenceCountingResourceHolder::close); - Assert.assertEquals(pool.maxSize(), pool.getPoolSize()); + Assertions.assertEquals(pool.maxSize(), pool.getPoolSize()); } } diff --git a/processing/src/test/java/org/apache/druid/common/guava/CombiningSequenceTest.java b/processing/src/test/java/org/apache/druid/common/guava/CombiningSequenceTest.java index d8888a792587..f3a1815eba50 100644 --- a/processing/src/test/java/org/apache/druid/common/guava/CombiningSequenceTest.java +++ b/processing/src/test/java/org/apache/druid/common/guava/CombiningSequenceTest.java @@ -32,41 +32,36 @@ import org.apache.druid.java.util.common.guava.Sequences; import org.apache.druid.java.util.common.guava.Yielder; import org.apache.druid.java.util.common.guava.YieldingAccumulator; -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; -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.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import javax.annotation.Nullable; import java.io.Closeable; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") public class CombiningSequenceTest { - @Parameterized.Parameters - public static Collection valuesToTry() + public static Stream constructorFeeder() { - return Arrays.asList(new Object[][]{ + return Arrays.stream(new Object[][]{ {1}, {2}, {3}, {4}, {5}, {1000} }); } - private final int yieldEvery; - - public CombiningSequenceTest(int yieldEvery) - { - this.yieldEvery = yieldEvery; - } + @Parameter(0) + public int yieldEvery; @Test public void testMerge() throws Exception @@ -225,13 +220,13 @@ public Integer accumulate(Integer accumulated, Integer in) } } ); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (Exception e) { - Assert.assertThat(e, ThrowableMessageMatcher.hasMessage(CoreMatchers.equalTo("boom"))); + Assertions.assertEquals("boom", e.getMessage()); } - Assert.assertEquals("Closes resources", 1, bomb.getCloseCount()); + Assertions.assertEquals(1, bomb.getCloseCount(), "Closes resources"); } private void testCombining(List> pairs, List> expected) @@ -279,7 +274,7 @@ private void testCombining( List> merged = seq.toList(); - Assert.assertEquals(prefix, expected, merged); + Assertions.assertEquals(expected, merged, prefix); Yielder> yielder = seq.toYielder( null, @@ -326,14 +321,14 @@ public boolean apply( while (!yielder.isDone()) { final Pair expectedVal = expectedVals.next(); final Pair actual = yielder.get(); - Assert.assertEquals(StringUtils.format("%s, i[%s]", prefix, i++), expectedVal, actual); + Assertions.assertEquals(expectedVal, actual, StringUtils.format("%s, i[%s]", prefix, i++)); yielder = yielder.next(actual); } } - Assert.assertTrue(prefix, yielder.isDone()); - Assert.assertFalse(prefix, expectedVals.hasNext()); + Assertions.assertTrue(yielder.isDone(), prefix); + Assertions.assertFalse(expectedVals.hasNext(), prefix); yielder.close(); - Assert.assertTrue("resource closed", closed.await(10000, TimeUnit.MILLISECONDS)); + Assertions.assertTrue(closed.await(10000, TimeUnit.MILLISECONDS), "resource closed"); } } 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 c6eac5212e2d..ac5cff961bb5 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 @@ -25,12 +25,11 @@ import org.apache.druid.data.input.impl.prefetch.ObjectOpenFunction; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -56,17 +55,14 @@ public class RetryingInputStreamTest { private static final int MAX_RETRY = 5; - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File temporaryFolder; private File testFile; private int readBytesBeforeExceptions = 0; private int throwCustomExceptions = 0; private int throwIOExceptions = 0; - private final ObjectOpenFunction objectOpenFunction = spy(new ObjectOpenFunction() { @Override @@ -84,10 +80,10 @@ public InputStream open(File object, long start) throws IOException } }); - @Before + @BeforeEach public void setup() throws IOException { - testFile = temporaryFolder.newFile(); + testFile = File.createTempFile("retrying", null, temporaryFolder); try (FileOutputStream fis = new FileOutputStream(testFile); GZIPOutputStream gis = new GZIPOutputStream(fis); @@ -102,7 +98,7 @@ public void setup() throws IOException throwIOExceptions = 0; } - @After + @AfterEach public void teardown() throws IOException { FileUtils.forceDelete(testFile); @@ -120,12 +116,12 @@ public void testThrowsOnIOException() throws IOException false ); - Assert.assertThrows( + Assertions.assertThrows( IOException.class, () -> retryHelper(retryingInputStream) ); - Assert.assertEquals(0, throwIOExceptions); + Assertions.assertEquals(0, throwIOExceptions); } @Test @@ -142,7 +138,7 @@ public void testRetryOnCustomException() throws IOException retryHelper(retryingInputStream); - Assert.assertEquals(0, throwCustomExceptions); + Assertions.assertEquals(0, throwCustomExceptions); } @Test @@ -157,12 +153,12 @@ public void testThrowsOnCustomException() throws IOException false ); - final IOException e = Assert.assertThrows( + final IOException e = Assertions.assertThrows( IOException.class, () -> retryHelper(retryingInputStream) ); - Assert.assertEquals(0, throwCustomExceptions); + Assertions.assertEquals(0, throwCustomExceptions); MatcherAssert.assertThat(e.getCause(), CoreMatchers.instanceOf(CustomException.class)); } @@ -183,7 +179,7 @@ public void testResumeAfterExceptions() throws IOException retryHelper(retryingInputStream); // Tried more than MAX_RETRY times because progress was being made. (MAX_RETRIES applies to each call individually.) - Assert.assertEquals(81, throwCustomExceptions); + Assertions.assertEquals(81, throwCustomExceptions); } @Test @@ -198,12 +194,12 @@ public void testTooManyExceptions() throws IOException false ); - Assert.assertThrows( + Assertions.assertThrows( IOException.class, () -> retryHelper(retryingInputStream) ); - Assert.assertEquals(6, throwIOExceptions); + Assertions.assertEquals(6, throwIOExceptions); } @Test @@ -221,8 +217,8 @@ public void testIOExceptionNotRetriableRead() throws IOException retryHelper(retryingInputStream); - Assert.assertEquals(0, throwCustomExceptions); - Assert.assertEquals(0, throwIOExceptions); + Assertions.assertEquals(0, throwCustomExceptions); + Assertions.assertEquals(0, throwIOExceptions); } @Test @@ -254,17 +250,17 @@ public InputStream answer(InvocationOnMock invocation) throws Throwable false ); verify(objectOpenFunction, times(3)).open(any(), anyLong()); - Assert.assertEquals(0, throwCustomExceptions); + Assertions.assertEquals(0, throwCustomExceptions); } private void retryHelper(RetryingInputStream retryingInputStream) throws IOException { try (DataInputStream inputStream = new DataInputStream(new GZIPInputStream(retryingInputStream))) { for (int i = 0; i < 10000; i++) { - Assert.assertEquals(i, inputStream.readInt()); + Assertions.assertEquals(i, inputStream.readInt()); } - Assert.assertEquals(-1, inputStream.read()); + Assertions.assertEquals(-1, inputStream.read()); } } diff --git a/processing/src/test/java/org/apache/druid/frame/field/DoubleArrayFieldReaderTest.java b/processing/src/test/java/org/apache/druid/frame/field/DoubleArrayFieldReaderTest.java index 280b93939926..34bbe71e1977 100644 --- a/processing/src/test/java/org/apache/druid/frame/field/DoubleArrayFieldReaderTest.java +++ b/processing/src/test/java/org/apache/druid/frame/field/DoubleArrayFieldReaderTest.java @@ -25,17 +25,18 @@ import org.apache.druid.java.util.common.ISE; import org.apache.druid.segment.ColumnValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import java.util.ArrayList; @@ -43,29 +44,25 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.STRICT_STUBS) public class DoubleArrayFieldReaderTest extends InitializedNullHandlingTest { private static final long MEMORY_POSITION = 1; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); - @Mock public ColumnValueSelector writeSelector; - private final FrameType frameType; + @Parameter(0) + public FrameType frameType; + private WritableMemory memory; private FieldWriter fieldWriter; - public DoubleArrayFieldReaderTest(FrameType frameType) - { - this.frameType = frameType; - } - - @Parameterized.Parameters(name = "frameType = {0}") - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { final List constructors = new ArrayList<>(); for (FrameType frameType : FrameType.values()) { @@ -73,7 +70,7 @@ public static Iterable constructorFeeder() constructors.add(new Object[]{frameType}); } } - return constructors; + return constructors.stream(); } //CHECKSTYLE.OFF: Regexp @@ -127,14 +124,14 @@ public static Iterable constructorFeeder() DOUBLES_LIST_2 = Arrays.stream(DOUBLES_ARRAY_2).map(val -> (Double) val).collect(Collectors.toList()); } - @Before + @BeforeEach public void setUp() { memory = WritableMemory.allocate(1000); fieldWriter = NumericArrayFieldWriter.getDoubleArrayFieldWriter(writeSelector, frameType); } - @After + @AfterEach public void tearDown() { fieldWriter.close(); @@ -144,28 +141,28 @@ public void tearDown() public void test_isNull_null() { writeToMemory(null, MEMORY_POSITION); - Assert.assertTrue(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertTrue(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test public void test_isNull_aValue() { writeToMemory(DOUBLES_ARRAY_1, MEMORY_POSITION); - Assert.assertFalse(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test public void test_isNull_emptyArray() { writeToMemory(new Object[]{}, MEMORY_POSITION); - Assert.assertFalse(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test public void test_isNull_arrayWithSingleNullElement() { writeToMemory(new Object[]{null}, MEMORY_POSITION); - Assert.assertFalse(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(new DoubleArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test @@ -179,7 +176,7 @@ public void test_makeColumnValueSelector_null() new ConstantFieldPointer(MEMORY_POSITION, sz) ); - Assert.assertTrue(readSelector.isNull()); + Assertions.assertTrue(readSelector.isNull()); } @Test @@ -255,14 +252,14 @@ private long writeToMemory(final Object value, final long initialPosition) private void assertResults(List expected, Object actual) { if (expected == null) { - Assert.assertNull(actual); + Assertions.assertNull(actual); } - Assert.assertTrue(actual instanceof Object[]); + Assertions.assertInstanceOf(Object[].class, actual); List actualList = new ArrayList<>(); for (Object val : (Object[]) actual) { actualList.add((Double) val); } - Assert.assertEquals(expected, actualList); + Assertions.assertEquals(expected, actualList); } } diff --git a/processing/src/test/java/org/apache/druid/frame/field/DoubleFieldReaderTest.java b/processing/src/test/java/org/apache/druid/frame/field/DoubleFieldReaderTest.java index 1accdafdfbe5..feeffb4e6a05 100644 --- a/processing/src/test/java/org/apache/druid/frame/field/DoubleFieldReaderTest.java +++ b/processing/src/test/java/org/apache/druid/frame/field/DoubleFieldReaderTest.java @@ -37,46 +37,42 @@ import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.data.IndexedInts; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.STRICT_STUBS) public class DoubleFieldReaderTest extends InitializedNullHandlingTest { private static final long MEMORY_POSITION = 1; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); - @Mock public BaseDoubleColumnValueSelector writeSelector; - private final FrameType frameType; + @Parameter(0) + public FrameType frameType; private WritableMemory memory; private FieldWriter fieldWriter; - public DoubleFieldReaderTest(FrameType frameType) - { - this.frameType = frameType; - } - - @Parameterized.Parameters(name = "frameType = {0}") - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { final List constructors = new ArrayList<>(); for (FrameType frameType : FrameType.values()) { @@ -84,17 +80,17 @@ public static Iterable constructorFeeder() constructors.add(new Object[]{frameType}); } } - return constructors; + return constructors.stream(); } - @Before + @BeforeEach public void setUp() { memory = WritableMemory.allocate(1000); fieldWriter = DoubleFieldWriter.forPrimitive(writeSelector, frameType); } - @After + @AfterEach public void tearDown() { fieldWriter.close(); @@ -104,14 +100,14 @@ public void tearDown() public void test_isNull_defaultOrNull() { writeToMemory(null); - Assert.assertTrue(DoubleFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertTrue(DoubleFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); } @Test public void test_isNull_aValue() { writeToMemory(5.1d); - Assert.assertFalse(DoubleFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(DoubleFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); } @Test @@ -123,7 +119,7 @@ public void test_makeColumnValueSelector_defaultOrNull() DoubleFieldReader.forPrimitive(frameType) .makeColumnValueSelector(memory, new ConstantFieldPointer(MEMORY_POSITION, -1)); - Assert.assertTrue(readSelector.isNull()); + Assertions.assertTrue(readSelector.isNull()); } @Test @@ -135,7 +131,7 @@ public void test_makeColumnValueSelector_aValue() DoubleFieldReader.forPrimitive(frameType) .makeColumnValueSelector(memory, new ConstantFieldPointer(MEMORY_POSITION, -1)); - Assert.assertEquals(5.1d, readSelector.getObject()); + Assertions.assertEquals(5.1d, readSelector.getObject()); } @Test @@ -149,21 +145,21 @@ public void test_makeDimensionSelector_defaultOrNull() // Data retrieval tests. final IndexedInts row = readSelector.getRow(); - Assert.assertEquals(1, row.size()); - Assert.assertNull(readSelector.lookupName(0)); + Assertions.assertEquals(1, row.size()); + Assertions.assertNull(readSelector.lookupName(0)); // Informational method tests. - Assert.assertFalse(readSelector.supportsLookupNameUtf8()); - Assert.assertFalse(readSelector.nameLookupPossibleInAdvance()); - Assert.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); - Assert.assertEquals(String.class, readSelector.classOfObject()); - Assert.assertNull(readSelector.idLookup()); + Assertions.assertFalse(readSelector.supportsLookupNameUtf8()); + Assertions.assertFalse(readSelector.nameLookupPossibleInAdvance()); + Assertions.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); + Assertions.assertEquals(String.class, readSelector.classOfObject()); + Assertions.assertNull(readSelector.idLookup()); // Value matcher tests. - Assert.assertFalse(readSelector.makeValueMatcher("0.0").matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher((String) null).matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.0")).matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.of(DruidObjectPredicate.isNull())).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher("0.0").matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher((String) null).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.0")).matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.of(DruidObjectPredicate.isNull())).matches(false)); } @Test @@ -180,9 +176,9 @@ public void testCompareRows() for (int i = 1; i < rows.size(); i++) { if (Objects.equals(accessor.getObject(i - 1), accessor.getObject(i))) { - Assert.assertEquals(0, accessor.compareRows(i - 1, i)); + Assertions.assertEquals(0, accessor.compareRows(i - 1, i)); } else { - Assert.assertTrue(accessor.compareRows(i - 1, i) < 0); + Assertions.assertTrue(accessor.compareRows(i - 1, i) < 0); } } } @@ -198,22 +194,22 @@ public void test_makeDimensionSelector_aValue() // Data retrieval tests. final IndexedInts row = readSelector.getRow(); - Assert.assertEquals(1, row.size()); - Assert.assertEquals("5.1", readSelector.lookupName(0)); + Assertions.assertEquals(1, row.size()); + Assertions.assertEquals("5.1", readSelector.lookupName(0)); // Informational method tests. - Assert.assertFalse(readSelector.supportsLookupNameUtf8()); - Assert.assertFalse(readSelector.nameLookupPossibleInAdvance()); - Assert.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); - Assert.assertEquals(String.class, readSelector.classOfObject()); - Assert.assertNull(readSelector.idLookup()); + Assertions.assertFalse(readSelector.supportsLookupNameUtf8()); + Assertions.assertFalse(readSelector.nameLookupPossibleInAdvance()); + Assertions.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); + Assertions.assertEquals(String.class, readSelector.classOfObject()); + Assertions.assertNull(readSelector.idLookup()); // Value matcher tests. - Assert.assertTrue(readSelector.makeValueMatcher("5.1").matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher("5").matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5.1")) + Assertions.assertTrue(readSelector.makeValueMatcher("5.1").matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher("5").matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5.1")) .matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5")).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5")).matches(false)); } @Test @@ -230,22 +226,22 @@ public void test_makeDimensionSelector_aValue_extractionFn() // Data retrieval tests. final IndexedInts row = readSelector.getRow(); - Assert.assertEquals(1, row.size()); - Assert.assertEquals("0.5", readSelector.lookupName(0)); + Assertions.assertEquals(1, row.size()); + Assertions.assertEquals("0.5", readSelector.lookupName(0)); // Informational method tests. - Assert.assertFalse(readSelector.supportsLookupNameUtf8()); - Assert.assertFalse(readSelector.nameLookupPossibleInAdvance()); - Assert.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); - Assert.assertEquals(String.class, readSelector.classOfObject()); - Assert.assertNull(readSelector.idLookup()); + Assertions.assertFalse(readSelector.supportsLookupNameUtf8()); + Assertions.assertFalse(readSelector.nameLookupPossibleInAdvance()); + Assertions.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); + Assertions.assertEquals(String.class, readSelector.classOfObject()); + Assertions.assertNull(readSelector.idLookup()); // Value matcher tests. - Assert.assertTrue(readSelector.makeValueMatcher("0.5").matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher("2").matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.5")) + Assertions.assertTrue(readSelector.makeValueMatcher("0.5").matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher("2").matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.5")) .matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("2")).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("2")).matches(false)); } private void writeToMemory(final Double value) diff --git a/processing/src/test/java/org/apache/druid/frame/field/FloatArrayFieldReaderTest.java b/processing/src/test/java/org/apache/druid/frame/field/FloatArrayFieldReaderTest.java index 9fc94b0e171b..5edddcbe42aa 100644 --- a/processing/src/test/java/org/apache/druid/frame/field/FloatArrayFieldReaderTest.java +++ b/processing/src/test/java/org/apache/druid/frame/field/FloatArrayFieldReaderTest.java @@ -25,17 +25,18 @@ import org.apache.druid.java.util.common.ISE; import org.apache.druid.segment.ColumnValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import java.util.ArrayList; @@ -43,30 +44,25 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.STRICT_STUBS) public class FloatArrayFieldReaderTest extends InitializedNullHandlingTest { private static final long MEMORY_POSITION = 1; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); - @Mock public ColumnValueSelector writeSelector; - private final FrameType frameType; + @Parameter(0) + public FrameType frameType; private WritableMemory memory; private FieldWriter fieldWriter; - public FloatArrayFieldReaderTest(FrameType frameType) - { - this.frameType = frameType; - } - - @Parameterized.Parameters(name = "frameType = {0}") - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { final List constructors = new ArrayList<>(); for (FrameType frameType : FrameType.values()) { @@ -74,7 +70,7 @@ public static Iterable constructorFeeder() constructors.add(new Object[]{frameType}); } } - return constructors; + return constructors.stream(); } //CHECKSTYLE.OFF: Regexp @@ -129,14 +125,14 @@ public static Iterable constructorFeeder() FLOATS_LIST_2 = Arrays.stream(FLOATS_ARRAY_2).map(val -> (Float) val).collect(Collectors.toList()); } - @Before + @BeforeEach public void setUp() { memory = WritableMemory.allocate(1000); fieldWriter = NumericArrayFieldWriter.getFloatArrayFieldWriter(writeSelector, frameType); } - @After + @AfterEach public void tearDown() { fieldWriter.close(); @@ -146,28 +142,28 @@ public void tearDown() public void test_isNull_null() { writeToMemory(null, MEMORY_POSITION); - Assert.assertTrue(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertTrue(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test public void test_isNull_aValue() { writeToMemory(FLOATS_ARRAY_1, MEMORY_POSITION); - Assert.assertFalse(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test public void test_isNull_emptyArray() { writeToMemory(new Object[]{}, MEMORY_POSITION); - Assert.assertFalse(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test public void test_isNull_arrayWithSingleNullElement() { writeToMemory(new Object[]{null}, MEMORY_POSITION); - Assert.assertFalse(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(new FloatArrayFieldReader(frameType).isNull(memory, MEMORY_POSITION)); } @Test @@ -179,7 +175,7 @@ public void test_makeColumnValueSelector_null() new FloatArrayFieldReader(frameType) .makeColumnValueSelector(memory, new ConstantFieldPointer(MEMORY_POSITION, sz)); - Assert.assertTrue(readSelector.isNull()); + Assertions.assertTrue(readSelector.isNull()); } @Test @@ -250,14 +246,14 @@ private long writeToMemory(final Object value, final long initialPosition) private void assertResults(List expected, Object actual) { if (expected == null) { - Assert.assertNull(actual); + Assertions.assertNull(actual); } - Assert.assertTrue(actual instanceof Object[]); + Assertions.assertTrue(actual instanceof Object[]); List actualList = new ArrayList<>(); for (Object val : (Object[]) actual) { actualList.add((Float) val); } - Assert.assertEquals(expected, actualList); + Assertions.assertEquals(expected, actualList); } } diff --git a/processing/src/test/java/org/apache/druid/frame/field/FloatFieldReaderTest.java b/processing/src/test/java/org/apache/druid/frame/field/FloatFieldReaderTest.java index a5bf27b7fedb..d7c97f0c902e 100644 --- a/processing/src/test/java/org/apache/druid/frame/field/FloatFieldReaderTest.java +++ b/processing/src/test/java/org/apache/druid/frame/field/FloatFieldReaderTest.java @@ -37,46 +37,42 @@ import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.data.IndexedInts; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.STRICT_STUBS) public class FloatFieldReaderTest extends InitializedNullHandlingTest { private static final long MEMORY_POSITION = 1; - - @Rule - public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); - @Mock public BaseFloatColumnValueSelector writeSelector; - private final FrameType frameType; + @Parameter(0) + public FrameType frameType; private WritableMemory memory; private FieldWriter fieldWriter; - public FloatFieldReaderTest(FrameType frameType) - { - this.frameType = frameType; - } - - @Parameterized.Parameters(name = "frameType = {0}") - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { final List constructors = new ArrayList<>(); for (FrameType frameType : FrameType.values()) { @@ -84,17 +80,17 @@ public static Iterable constructorFeeder() constructors.add(new Object[]{frameType}); } } - return constructors; + return constructors.stream(); } - @Before + @BeforeEach public void setUp() { memory = WritableMemory.allocate(1000); fieldWriter = FloatFieldWriter.forPrimitive(writeSelector, frameType); } - @After + @AfterEach public void tearDown() { fieldWriter.close(); @@ -104,7 +100,7 @@ public void tearDown() public void test_isNull_defaultOrNull() { writeToMemory(null); - Assert.assertTrue(FloatFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertTrue(FloatFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); } @Test @@ -121,9 +117,9 @@ public void testCompareRows() for (int i = 1; i < rows.size(); i++) { if (Objects.equals(accessor.getObject(i - 1), accessor.getObject(i))) { - Assert.assertEquals(0, accessor.compareRows(i - 1, i)); + Assertions.assertEquals(0, accessor.compareRows(i - 1, i)); } else { - Assert.assertTrue(accessor.compareRows(i - 1, i) < 0); + Assertions.assertTrue(accessor.compareRows(i - 1, i) < 0); } } } @@ -132,7 +128,7 @@ public void testCompareRows() public void test_isNull_aValue() { writeToMemory(5.1f); - Assert.assertFalse(FloatFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); + Assertions.assertFalse(FloatFieldReader.forPrimitive(frameType).isNull(memory, MEMORY_POSITION)); } @Test @@ -144,7 +140,7 @@ public void test_makeColumnValueSelector_defaultOrNull() FloatFieldReader.forPrimitive(frameType) .makeColumnValueSelector(memory, new ConstantFieldPointer(MEMORY_POSITION, -1)); - Assert.assertTrue(readSelector.isNull()); + Assertions.assertTrue(readSelector.isNull()); } @Test @@ -156,7 +152,7 @@ public void test_makeColumnValueSelector_aValue() FloatFieldReader.forPrimitive(frameType) .makeColumnValueSelector(memory, new ConstantFieldPointer(MEMORY_POSITION, -1)); - Assert.assertEquals(5.1f, readSelector.getObject()); + Assertions.assertEquals(5.1f, readSelector.getObject()); } @Test @@ -170,21 +166,21 @@ public void test_makeDimensionSelector_defaultOrNull() // Data retrieval tests. final IndexedInts row = readSelector.getRow(); - Assert.assertEquals(1, row.size()); - Assert.assertEquals(null, readSelector.lookupName(0)); + Assertions.assertEquals(1, row.size()); + Assertions.assertEquals(null, readSelector.lookupName(0)); // Informational method tests. - Assert.assertFalse(readSelector.supportsLookupNameUtf8()); - Assert.assertFalse(readSelector.nameLookupPossibleInAdvance()); - Assert.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); - Assert.assertEquals(String.class, readSelector.classOfObject()); - Assert.assertNull(readSelector.idLookup()); + Assertions.assertFalse(readSelector.supportsLookupNameUtf8()); + Assertions.assertFalse(readSelector.nameLookupPossibleInAdvance()); + Assertions.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); + Assertions.assertEquals(String.class, readSelector.classOfObject()); + Assertions.assertNull(readSelector.idLookup()); // Value matcher tests. - Assert.assertFalse(readSelector.makeValueMatcher("0.0").matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher((String) null).matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.0")).matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.of(DruidObjectPredicate.isNull())).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher("0.0").matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher((String) null).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.0")).matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.of(DruidObjectPredicate.isNull())).matches(false)); } @Test @@ -198,22 +194,22 @@ public void test_makeDimensionSelector_aValue() // Data retrieval tests. final IndexedInts row = readSelector.getRow(); - Assert.assertEquals(1, row.size()); - Assert.assertEquals("5.1", readSelector.lookupName(0)); + Assertions.assertEquals(1, row.size()); + Assertions.assertEquals("5.1", readSelector.lookupName(0)); // Informational method tests. - Assert.assertFalse(readSelector.supportsLookupNameUtf8()); - Assert.assertFalse(readSelector.nameLookupPossibleInAdvance()); - Assert.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); - Assert.assertEquals(String.class, readSelector.classOfObject()); - Assert.assertNull(readSelector.idLookup()); + Assertions.assertFalse(readSelector.supportsLookupNameUtf8()); + Assertions.assertFalse(readSelector.nameLookupPossibleInAdvance()); + Assertions.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); + Assertions.assertEquals(String.class, readSelector.classOfObject()); + Assertions.assertNull(readSelector.idLookup()); // Value matcher tests. - Assert.assertTrue(readSelector.makeValueMatcher("5.1").matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher("5").matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5.1")) + Assertions.assertTrue(readSelector.makeValueMatcher("5.1").matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher("5").matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5.1")) .matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5")).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("5")).matches(false)); } @Test @@ -230,22 +226,22 @@ public void test_makeDimensionSelector_aValue_extractionFn() // Data retrieval tests. final IndexedInts row = readSelector.getRow(); - Assert.assertEquals(1, row.size()); - Assert.assertEquals("0.5", readSelector.lookupName(0)); + Assertions.assertEquals(1, row.size()); + Assertions.assertEquals("0.5", readSelector.lookupName(0)); // Informational method tests. - Assert.assertFalse(readSelector.supportsLookupNameUtf8()); - Assert.assertFalse(readSelector.nameLookupPossibleInAdvance()); - Assert.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); - Assert.assertEquals(String.class, readSelector.classOfObject()); - Assert.assertNull(readSelector.idLookup()); + Assertions.assertFalse(readSelector.supportsLookupNameUtf8()); + Assertions.assertFalse(readSelector.nameLookupPossibleInAdvance()); + Assertions.assertEquals(DimensionDictionarySelector.CARDINALITY_UNKNOWN, readSelector.getValueCardinality()); + Assertions.assertEquals(String.class, readSelector.classOfObject()); + Assertions.assertNull(readSelector.idLookup()); // Value matcher tests. - Assert.assertTrue(readSelector.makeValueMatcher("0.5").matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher("2").matches(false)); - Assert.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.5")) + Assertions.assertTrue(readSelector.makeValueMatcher("0.5").matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher("2").matches(false)); + Assertions.assertTrue(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("0.5")) .matches(false)); - Assert.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("2")).matches(false)); + Assertions.assertFalse(readSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo("2")).matches(false)); } private void writeToMemory(final Float value) diff --git a/processing/src/test/java/org/apache/druid/frame/field/TransformUtilsTest.java b/processing/src/test/java/org/apache/druid/frame/field/TransformUtilsTest.java index 6050416274f9..d4f45149fc44 100644 --- a/processing/src/test/java/org/apache/druid/frame/field/TransformUtilsTest.java +++ b/processing/src/test/java/org/apache/druid/frame/field/TransformUtilsTest.java @@ -23,14 +23,17 @@ import org.apache.datasketches.memory.WritableMemory; import org.apache.druid.frame.FrameType; 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.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import java.util.List; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") public class TransformUtilsTest { private final WritableMemory lhsMemory = WritableMemory.allocate(10); @@ -38,20 +41,15 @@ public class TransformUtilsTest private static final long MEMORY_LOCATION = 0; - private final FrameType frameType; + @Parameter(0) + public FrameType frameType; - public TransformUtilsTest(final FrameType frameType) - { - this.frameType = frameType; - } - - @Parameterized.Parameters(name = "frameType = {0}") - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { return List.of( new Object[]{FrameType.ROW_BASED_V1}, new Object[]{FrameType.ROW_BASED_V2} - ); + ).stream(); } /** @@ -123,11 +121,11 @@ public void doubleTest() ); for (double value : values) { - Assert.assertEquals( - String.valueOf(value), + Assertions.assertEquals( value, TransformUtils.detransformToDouble(TransformUtils.transformFromDouble(value, frameType), frameType), - 0.0 + 0.0, + String.valueOf(value) ); } @@ -140,7 +138,7 @@ public void doubleTest() rhsMemory.putLong(MEMORY_LOCATION, TransformUtils.transformFromDouble(rhs, frameType)); int byteCmp = byteComparison(Double.BYTES); final int expectedCmp = expectedComparison(frameType, lhs, rhs); - Assert.assertEquals(StringUtils.format("compare(%s, %s)", lhs, rhs), signum(expectedCmp), signum(byteCmp)); + Assertions.assertEquals(signum(expectedCmp), signum(byteCmp), StringUtils.format("compare(%s, %s)", lhs, rhs)); } } } @@ -158,7 +156,7 @@ public void longTest() ); for (long value : values) { - Assert.assertEquals( + Assertions.assertEquals( value, TransformUtils.detransformToLong(TransformUtils.transformFromLong(value)) ); @@ -174,11 +172,11 @@ public void longTest() int byteCmp = byteComparison(Long.BYTES); if (byteCmp < 0) { - Assert.assertTrue(lhs < rhs); + Assertions.assertTrue(lhs < rhs); } else if (byteCmp == 0) { - Assert.assertEquals(lhs, rhs); + Assertions.assertEquals(lhs, rhs); } else { - Assert.assertTrue(lhs > rhs); + Assertions.assertTrue(lhs > rhs); } } } @@ -219,11 +217,11 @@ public void floatTest() ); for (float value : values) { - Assert.assertEquals( - String.valueOf(value), + Assertions.assertEquals( value, TransformUtils.detransformToFloat(TransformUtils.transformFromFloat(value, frameType), frameType), - 0.0 + 0.0f, + String.valueOf(value) ); } @@ -235,7 +233,7 @@ public void floatTest() rhsMemory.putLong(MEMORY_LOCATION, TransformUtils.transformFromFloat(rhs, frameType)); final int byteCmp = byteComparison(Long.BYTES); final int expectedCmp = expectedComparison(frameType, lhs, rhs); - Assert.assertEquals(StringUtils.format("compare(%s, %s)", lhs, rhs), signum(expectedCmp), signum(byteCmp)); + Assertions.assertEquals(signum(expectedCmp), signum(byteCmp), StringUtils.format("compare(%s, %s)", lhs, rhs)); } } } diff --git a/processing/src/test/java/org/apache/druid/indexer/granularity/UniformGranularityTest.java b/processing/src/test/java/org/apache/druid/indexer/granularity/UniformGranularityTest.java index e74751773f27..114a90ec9ea5 100644 --- a/processing/src/test/java/org/apache/druid/indexer/granularity/UniformGranularityTest.java +++ b/processing/src/test/java/org/apache/druid/indexer/granularity/UniformGranularityTest.java @@ -33,8 +33,8 @@ 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.ArrayList; import java.util.Collections; @@ -60,14 +60,14 @@ public void testSimple() inputIntervals ); - Assert.assertTrue(spec.isRollup()); + Assertions.assertTrue(spec.isRollup()); - Assert.assertEquals( + Assertions.assertEquals( inputIntervals, Lists.newArrayList(spec.inputIntervals()) ); - Assert.assertEquals( + Assertions.assertEquals( Lists.newArrayList( Intervals.of("2012-01-01T00Z/P1D"), Intervals.of("2012-01-02T00Z/P1D"), @@ -80,55 +80,54 @@ public void testSimple() Lists.newArrayList(spec.sortedBucketIntervals()) ); - - Assert.assertEquals( + Assertions.assertEquals( Optional.absent(), spec.bucketInterval(DateTimes.of("2011-01-12T00Z")) ); - Assert.assertEquals( + Assertions.assertEquals( Optional.of(Intervals.of("2012-01-01T00Z/2012-01-02T00Z")), spec.bucketInterval(DateTimes.of("2012-01-01T00Z")) ); - Assert.assertEquals( + Assertions.assertEquals( Optional.of(Intervals.of("2012-01-10T00Z/2012-01-11T00Z")), spec.bucketInterval(DateTimes.of("2012-01-10T00Z")) ); - Assert.assertEquals( + Assertions.assertEquals( Optional.absent(), spec.bucketInterval(DateTimes.of("2012-01-12T00Z")) ); - Assert.assertEquals( - "2012-01-03T00Z", + Assertions.assertEquals( Optional.of(Intervals.of("2012-01-03T00Z/2012-01-04T00Z")), - spec.bucketInterval(DateTimes.of("2012-01-03T00Z")) + spec.bucketInterval(DateTimes.of("2012-01-03T00Z")), + "2012-01-03T00Z" ); - Assert.assertEquals( - "2012-01-03T01Z", + Assertions.assertEquals( Optional.of(Intervals.of("2012-01-03T00Z/2012-01-04T00Z")), - spec.bucketInterval(DateTimes.of("2012-01-03T01Z")) + spec.bucketInterval(DateTimes.of("2012-01-03T01Z")), + "2012-01-03T01Z" ); - Assert.assertEquals( - "2012-01-04T01Z", + Assertions.assertEquals( Optional.absent(), - spec.bucketInterval(DateTimes.of("2012-01-04T01Z")) + spec.bucketInterval(DateTimes.of("2012-01-04T01Z")), + "2012-01-04T01Z" ); - Assert.assertEquals( - "2012-01-07T23:59:59.999Z", + Assertions.assertEquals( Optional.of(Intervals.of("2012-01-07T00Z/2012-01-08T00Z")), - spec.bucketInterval(DateTimes.of("2012-01-07T23:59:59.999Z")) + spec.bucketInterval(DateTimes.of("2012-01-07T23:59:59.999Z")), + "2012-01-07T23:59:59.999Z" ); - Assert.assertEquals( - "2012-01-08T01Z", + Assertions.assertEquals( Optional.of(Intervals.of("2012-01-08T00Z/2012-01-09T00Z")), - spec.bucketInterval(DateTimes.of("2012-01-08T01Z")) + spec.bucketInterval(DateTimes.of("2012-01-08T01Z")), + "2012-01-08T01Z" ); } @@ -144,7 +143,7 @@ public void testRollupSetting() ); final GranularitySpec spec = new UniformGranularitySpec(Granularities.DAY, Granularities.NONE, false, intervals); - Assert.assertFalse(spec.isRollup()); + Assertions.assertFalse(spec.isRollup()); } @Test @@ -163,15 +162,15 @@ public void testJson() try { final GranularitySpec rtSpec = JSON_MAPPER.readValue(JSON_MAPPER.writeValueAsString(spec), GranularitySpec.class); - Assert.assertEquals( - "Round-trip sortedBucketIntervals", + Assertions.assertEquals( ImmutableList.copyOf(spec.sortedBucketIntervals()), - ImmutableList.copyOf(rtSpec.sortedBucketIntervals().iterator()) + ImmutableList.copyOf(rtSpec.sortedBucketIntervals().iterator()), + "Round-trip sortedBucketIntervals" ); - Assert.assertEquals( - "Round-trip granularity", + Assertions.assertEquals( spec.getSegmentGranularity(), - rtSpec.getSegmentGranularity() + rtSpec.getSegmentGranularity(), + "Round-trip granularity" ); } catch (Exception e) { @@ -211,8 +210,8 @@ public void testEquals() public void equalsCheck(GranularitySpec spec1, GranularitySpec spec2) { - Assert.assertEquals(spec1, spec2); - Assert.assertEquals(spec1.hashCode(), spec2.hashCode()); + Assertions.assertEquals(spec1, spec2); + Assertions.assertEquals(spec1.hashCode(), spec2.hashCode()); } @Test @@ -285,7 +284,7 @@ public void testPeriodSegmentGranularity() ) ); - Assert.assertTrue(spec.sortedBucketIntervals().iterator().hasNext()); + Assertions.assertTrue(spec.sortedBucketIntervals().iterator().hasNext()); final Iterable intervals = spec.sortedBucketIntervals(); ArrayList actualIntervals = new ArrayList<>(); @@ -307,7 +306,7 @@ public void testPeriodSegmentGranularity() new Interval("2012-09-02/2012-09-03", chrono).toDurationMillis() ); - Assert.assertEquals(expectedIntervals, actualIntervals); + Assertions.assertEquals(expectedIntervals, actualIntervals); } @Test @@ -322,16 +321,16 @@ public void testUniformGranularitySpecWithLargeNumberOfIntervalsDoesNotBlowUp() ) ); - Assert.assertTrue(spec != null); + Assertions.assertNotNull(spec); int count = Iterators.size(spec.sortedBucketIntervals().iterator()); // account for three leap years... - Assert.assertEquals(3600 * 24 * 365 * 10 + 3 * 24 * 3600, count); + Assertions.assertEquals(3600 * 24 * 365 * 10 + 3 * 24 * 3600, count); } private void notEqualsCheck(GranularitySpec spec1, GranularitySpec spec2) { - Assert.assertNotEquals(spec1, spec2); - Assert.assertNotEquals(spec1.hashCode(), spec2.hashCode()); + Assertions.assertNotEquals(spec1, spec2); + Assertions.assertNotEquals(spec1.hashCode(), spec2.hashCode()); } } diff --git a/processing/src/test/java/org/apache/druid/java/util/common/MemoryBoundLinkedBlockingQueueTest.java b/processing/src/test/java/org/apache/druid/java/util/common/MemoryBoundLinkedBlockingQueueTest.java index ec36d83f250c..da7d37cee9e6 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/MemoryBoundLinkedBlockingQueueTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/MemoryBoundLinkedBlockingQueueTest.java @@ -20,8 +20,8 @@ package org.apache.druid.java.util.common; import com.google.common.collect.ImmutableList; -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.nio.charset.StandardCharsets; @@ -44,10 +44,10 @@ public void test_offer_emptyQueueWithEnoughCapacity_true() boolean succeeds = queue.offer(new MemoryBoundLinkedBlockingQueue.ObjectContainer<>(item, item.length)); long expectedByteSize = item.length; - Assert.assertTrue(succeeds); - Assert.assertEquals(1, queue.size()); - Assert.assertEquals(expectedByteSize, queue.byteSize()); - Assert.assertEquals(byteCapacity - item.length, queue.remainingCapacity()); + Assertions.assertTrue(succeeds); + Assertions.assertEquals(1, queue.size()); + Assertions.assertEquals(expectedByteSize, queue.byteSize()); + Assertions.assertEquals(byteCapacity - item.length, queue.remainingCapacity()); } @Test @@ -65,10 +65,10 @@ public void test_offer_nonEmptyQueueWithEnoughCapacity_true() boolean succeeds = queue.offer(new MemoryBoundLinkedBlockingQueue.ObjectContainer<>(item2, item2.length)); long expectedByteSize = item1.length + item2.length; - Assert.assertTrue(succeeds); - Assert.assertEquals(2, queue.size()); - Assert.assertEquals(expectedByteSize, queue.byteSize()); - Assert.assertEquals(byteCapacity - expectedByteSize, queue.remainingCapacity()); + Assertions.assertTrue(succeeds); + Assertions.assertEquals(2, queue.size()); + Assertions.assertEquals(expectedByteSize, queue.byteSize()); + Assertions.assertEquals(byteCapacity - expectedByteSize, queue.remainingCapacity()); } @Test @@ -86,10 +86,10 @@ public void test_offer_queueWithoutEnoughCapacity_false() boolean succeeds = queue.offer(new MemoryBoundLinkedBlockingQueue.ObjectContainer<>(item2, item2.length)); long expectedByteSize = item1.length; - Assert.assertFalse(succeeds); - Assert.assertEquals(1, queue.size()); - Assert.assertEquals(expectedByteSize, queue.byteSize()); - Assert.assertEquals(byteCapacity - expectedByteSize, queue.remainingCapacity()); + Assertions.assertFalse(succeeds); + Assertions.assertEquals(1, queue.size()); + Assertions.assertEquals(expectedByteSize, queue.byteSize()); + Assertions.assertEquals(byteCapacity - expectedByteSize, queue.remainingCapacity()); } @Test @@ -103,7 +103,7 @@ public void test_offerWithTimeLimit_interruptedExceptinThrown_throws() ); byte[] item = "item".getBytes(StandardCharsets.UTF_8); - Assert.assertThrows( + Assertions.assertThrows( InterruptedException.class, () -> queue.offer( new MemoryBoundLinkedBlockingQueue.ObjectContainer<>(item, item.length), @@ -112,9 +112,9 @@ public void test_offerWithTimeLimit_interruptedExceptinThrown_throws() ) ); - Assert.assertEquals(0, queue.size()); - Assert.assertEquals(0L, queue.byteSize()); - Assert.assertEquals(byteCapacity, queue.remainingCapacity()); + Assertions.assertEquals(0, queue.size()); + Assertions.assertEquals(0L, queue.byteSize()); + Assertions.assertEquals(byteCapacity, queue.remainingCapacity()); } @Test @@ -141,18 +141,18 @@ public void test_offerWithTimeLimit_fullQueue_waitsTime() throws InterruptedExce ); long end = System.currentTimeMillis(); - Assert.assertFalse(succeeds); - Assert.assertTrue( + Assertions.assertFalse(succeeds); + Assertions.assertTrue( + TimeUnit.MILLISECONDS.toNanos(end - start) >= TimeUnit.MILLISECONDS.toNanos(timeoutMillis), StringUtils.format( "offer only waited at most [%d] nanos instead of expected [%d] nanos", TimeUnit.MILLISECONDS.toNanos(end - start), TimeUnit.MILLISECONDS.toNanos(timeoutMillis) - ), - TimeUnit.MILLISECONDS.toNanos(end - start) >= TimeUnit.MILLISECONDS.toNanos(timeoutMillis) + ) ); - Assert.assertEquals(2, queue.size()); - Assert.assertEquals(10L, queue.byteSize()); - Assert.assertEquals(0L, queue.remainingCapacity()); + Assertions.assertEquals(2, queue.size()); + Assertions.assertEquals(10L, queue.byteSize()); + Assertions.assertEquals(0L, queue.remainingCapacity()); } @Test @@ -167,16 +167,16 @@ public void test_take_nonEmptyQueue_expected() throws InterruptedException MemoryBoundLinkedBlockingQueue.ObjectContainer item2Container = new MemoryBoundLinkedBlockingQueue.ObjectContainer<>(item2, item2.length); MemoryBoundLinkedBlockingQueue queue = setupQueue(byteCapacity, ImmutableList.of()); - Assert.assertTrue(queue.offer(item1Container)); - Assert.assertTrue(queue.offer(item2Container)); + Assertions.assertTrue(queue.offer(item1Container)); + Assertions.assertTrue(queue.offer(item2Container)); MemoryBoundLinkedBlockingQueue.ObjectContainer takenItem = queue.take(); long expectedByteSize = item2.length; - Assert.assertSame(item1Container, takenItem); - Assert.assertEquals(1, queue.size()); - Assert.assertEquals(expectedByteSize, queue.byteSize()); - Assert.assertEquals(byteCapacity - expectedByteSize, queue.remainingCapacity()); + Assertions.assertSame(item1Container, takenItem); + Assertions.assertEquals(1, queue.size()); + Assertions.assertEquals(expectedByteSize, queue.byteSize()); + Assertions.assertEquals(byteCapacity - expectedByteSize, queue.remainingCapacity()); } @Test @@ -189,10 +189,10 @@ public void test_drain_emptyQueue_succeeds() throws InterruptedException int numAdded = queue.drain(buffer, 1, 1, TimeUnit.SECONDS); - Assert.assertTrue(numAdded == 0 && numAdded == buffer.size()); - Assert.assertEquals(0, queue.size()); - Assert.assertEquals(0L, queue.byteSize()); - Assert.assertEquals(byteCapacity, queue.remainingCapacity()); + Assertions.assertTrue(numAdded == 0 && numAdded == buffer.size()); + Assertions.assertEquals(0, queue.size()); + Assertions.assertEquals(0L, queue.byteSize()); + Assertions.assertEquals(byteCapacity, queue.remainingCapacity()); } @Test @@ -209,10 +209,10 @@ public void test_drain_queueWithOneItem_succeeds() throws InterruptedException int numAdded = queue.drain(buffer, 1, 1, TimeUnit.MINUTES); - Assert.assertTrue(numAdded == 1 && numAdded == buffer.size()); - Assert.assertEquals(0, queue.size()); - Assert.assertEquals(0L, queue.byteSize()); - Assert.assertEquals(byteCapacity, queue.remainingCapacity()); + Assertions.assertTrue(numAdded == 1 && numAdded == buffer.size()); + Assertions.assertEquals(0, queue.size()); + Assertions.assertEquals(0L, queue.byteSize()); + Assertions.assertEquals(byteCapacity, queue.remainingCapacity()); } @Test @@ -231,10 +231,10 @@ public void test_drain_queueWithMultipleItems_succeeds() throws InterruptedExcep int numAdded = queue.drain(buffer, 10, 1, TimeUnit.MINUTES); - Assert.assertTrue(numAdded == 2 && numAdded == buffer.size()); - Assert.assertEquals(1, queue.size()); - Assert.assertEquals(item3.length, queue.byteSize()); - Assert.assertEquals(byteCapacity - item3.length, queue.remainingCapacity()); + Assertions.assertTrue(numAdded == 2 && numAdded == buffer.size()); + Assertions.assertEquals(1, queue.size()); + Assertions.assertEquals(item3.length, queue.byteSize()); + Assertions.assertEquals(byteCapacity - item3.length, queue.remainingCapacity()); } @Test @@ -253,10 +253,10 @@ public void test_drain_queueWithFirstItemSizeGreaterThanLimit_succeeds() throws int numAdded = queue.drain(buffer, item1.length - 1, 1, TimeUnit.MINUTES); - Assert.assertTrue(numAdded == 1 && numAdded == buffer.size()); - Assert.assertEquals(2, queue.size()); - Assert.assertEquals(item2.length + item3.length, queue.byteSize()); - Assert.assertEquals(byteCapacity - (item2.length + item3.length), queue.remainingCapacity()); + Assertions.assertTrue(numAdded == 1 && numAdded == buffer.size()); + Assertions.assertEquals(2, queue.size()); + Assertions.assertEquals(item2.length + item3.length, queue.byteSize()); + Assertions.assertEquals(byteCapacity - (item2.length + item3.length), queue.remainingCapacity()); } private static MemoryBoundLinkedBlockingQueue setupQueue( @@ -273,10 +273,10 @@ private static MemoryBoundLinkedBlockingQueue setupQueue( @Nullable LinkedBlockingQueue> underlyingQueue ) { - Assert.assertTrue(getTotalSizeOfItems(items) <= byteCapacity); + Assertions.assertTrue(getTotalSizeOfItems(items) <= byteCapacity); MemoryBoundLinkedBlockingQueue queue = underlyingQueue != null ? new MemoryBoundLinkedBlockingQueue<>(underlyingQueue, byteCapacity) : new MemoryBoundLinkedBlockingQueue<>(byteCapacity); - items.forEach(i -> Assert.assertTrue(queue.offer(i))); + items.forEach(i -> Assertions.assertTrue(queue.offer(i))); return queue; } diff --git a/processing/src/test/java/org/apache/druid/java/util/common/concurrent/ScheduledExecutorsTest.java b/processing/src/test/java/org/apache/druid/java/util/common/concurrent/ScheduledExecutorsTest.java index b256dc8268e8..df046c1c0ade 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/concurrent/ScheduledExecutorsTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/concurrent/ScheduledExecutorsTest.java @@ -20,8 +20,8 @@ package org.apache.druid.java.util.common.concurrent; import org.joda.time.Duration; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -74,14 +74,14 @@ public void testscheduleWithFixedDelay() throws Exception boolean completed = latch.await(5, TimeUnit.SECONDS); exec.shutdown(); - Assert.assertTrue("Should complete within timeout", completed); - Assert.assertEquals("Should have exactly 4 executions", 4, executionCount.get()); + Assertions.assertTrue(completed, "Should complete within timeout"); + Assertions.assertEquals(4, executionCount.get(), "Should have exactly 4 executions"); // Verify first task starts at approximately the initial delay, in real life this is greater than 100ms due to overhead. long firstTaskStart = taskStartTimes.get(0) - startTime; - Assert.assertTrue( - "First task should start at approximately initial delay (100ms), was: " + firstTaskStart, - firstTaskStart > 100 && firstTaskStart < 500 + Assertions.assertTrue( + firstTaskStart > 100 && firstTaskStart < 500, + "First task should start at approximately initial delay (100ms), was: " + firstTaskStart ); // Verify subsequent tasks wait for delay from previous task end @@ -90,9 +90,9 @@ public void testscheduleWithFixedDelay() throws Exception long previousTaskEnd = taskStartTimes.get(i - 1) + taskDuration; long delayBetweenTasks = taskStartTimes.get(i) - previousTaskEnd; // Should be approximately 500ms (the delay between task end and next task start) - Assert.assertTrue( - "Delay from task " + (i - 1) + " end to task " + i + " start should be ~500ms, was: " + delayBetweenTasks, - delayBetweenTasks >= 450 && delayBetweenTasks <= 650 + Assertions.assertTrue( + delayBetweenTasks >= 450 && delayBetweenTasks <= 650, + "Delay from task " + (i - 1) + " end to task " + i + " start should be ~500ms, was: " + delayBetweenTasks ); } } @@ -127,8 +127,8 @@ public void testScheduleWithFixedDelayContinuesAfterException() throws Exception final boolean completed = latch.await(5, TimeUnit.SECONDS); exec.shutdown(); - Assert.assertTrue("Should continue executing after exception", completed); - Assert.assertEquals("Should have exactly 3 executions", 3, executionCount.get()); + Assertions.assertTrue(completed, "Should continue executing after exception"); + Assertions.assertEquals(3, executionCount.get(), "Should have exactly 3 executions"); } @Test @@ -153,11 +153,7 @@ public void testScheduleWithFixedDelayStopsOnSignalStop() throws Exception Thread.sleep(500); exec.shutdown(); - Assert.assertEquals( - "Should execute exactly once before stopping", - 1, - executionCount.get() - ); + Assertions.assertEquals(1, executionCount.get(), "Should execute exactly once before stopping"); } @Test @@ -207,24 +203,24 @@ public void testScheduleAtFixedRateWithLongRunningTask() throws Exception boolean completed = latch.await(10, TimeUnit.SECONDS); exec.shutdown(); - Assert.assertTrue("Should complete within timeout", completed); - Assert.assertEquals("Should have exactly 4 executions", 4, executionStartTimes.size()); + Assertions.assertTrue(completed, "Should complete within timeout"); + Assertions.assertEquals(4, executionStartTimes.size(), "Should have exactly 4 executions"); // Verify first task took longer than period (no pileup should occur) // Second task should start immediately after first task finishes (not during) long timeBetweenFirstAndSecond = executionStartTimes.get(1) - executionStartTimes.get(0); // Should be at least 800ms (first task duration), but not much more since it schedules immediately - Assert.assertTrue( - "Second task should start after first task completes (~800ms), was: " + timeBetweenFirstAndSecond, - timeBetweenFirstAndSecond >= 750 && timeBetweenFirstAndSecond <= 950 + Assertions.assertTrue( + timeBetweenFirstAndSecond >= 750 && timeBetweenFirstAndSecond <= 950, + "Second task should start after first task completes (~800ms), was: " + timeBetweenFirstAndSecond ); // Verify subsequent tasks maintain the period (no catch-up burst) long timeBetweenSecondAndThird = executionStartTimes.get(2) - executionStartTimes.get(1); // Should be approximately 500ms (the period), since tasks now finish quickly - Assert.assertTrue( - "Subsequent tasks should maintain period (~500ms), was: " + timeBetweenSecondAndThird, - timeBetweenSecondAndThird >= 450 && timeBetweenSecondAndThird <= 600 + Assertions.assertTrue( + timeBetweenSecondAndThird >= 450 && timeBetweenSecondAndThird <= 600, + "Subsequent tasks should maintain period (~500ms), was: " + timeBetweenSecondAndThird ); } @@ -274,12 +270,8 @@ public void testScheduleAtFixedRateNoConcurrentExecutionWithMultipleThreads() th final boolean completed = latch.await(10, TimeUnit.SECONDS); exec.shutdown(); - Assert.assertTrue("Should complete within timeout", completed); - Assert.assertEquals( - "Should never have more than 1 concurrent execution", - 1, - maxConcurrentCount.get() - ); + Assertions.assertTrue(completed, "Should complete within timeout"); + Assertions.assertEquals(1, maxConcurrentCount.get(), "Should never have more than 1 concurrent execution"); } @Test @@ -305,11 +297,7 @@ public void testScheduleAtFixedRateStopsOnSignalStop() throws Exception Thread.sleep(500); exec.shutdown(); - Assert.assertEquals( - "Should execute exactly once before stopping", - 1, - executionCount.get() - ); + Assertions.assertEquals(1, executionCount.get(), "Should execute exactly once before stopping"); } @Test @@ -342,7 +330,7 @@ public void testScheduleAtFixedRateContinuesAfterException() throws Exception final boolean completed = latch.await(5, TimeUnit.SECONDS); exec.shutdown(); - Assert.assertTrue("Should continue executing after exception", completed); - Assert.assertEquals("Should have exactly 3 executions", 3, executionCount.get()); + Assertions.assertTrue(completed, "Should continue executing after exception"); + Assertions.assertEquals(3, executionCount.get(), "Should have exactly 3 executions"); } } diff --git a/processing/src/test/java/org/apache/druid/java/util/common/guava/ConcatSequenceTest.java b/processing/src/test/java/org/apache/druid/java/util/common/guava/ConcatSequenceTest.java index 8e26afbf4b40..1e2bb56690c2 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/guava/ConcatSequenceTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/guava/ConcatSequenceTest.java @@ -23,8 +23,8 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; -import junit.framework.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; @@ -128,7 +128,7 @@ public void cleanup(Iterator> iterFromMake) ) ); - Assert.assertEquals( + Assertions.assertEquals( 9, seq.accumulate( 1, @@ -137,14 +137,14 @@ public void cleanup(Iterator> iterFromMake) @Override public Integer accumulate(Integer accumulated, Integer in) { - Assert.assertEquals(accumulated, in); + Assertions.assertEquals(accumulated, in); return accumulated + 1; } } ).intValue() ); - Assert.assertEquals(1, closedCount[0]); + Assertions.assertEquals(1, closedCount[0]); final Yielder yielder = seq.toYielder( 1, @@ -153,16 +153,16 @@ public Integer accumulate(Integer accumulated, Integer in) @Override public Integer accumulate(Integer accumulated, Integer in) { - Assert.assertEquals(accumulated, in); + Assertions.assertEquals(accumulated, in); return accumulated + 1; } } ); - Assert.assertEquals(9, yielder.get().intValue()); + Assertions.assertEquals(9, yielder.get().intValue()); - Assert.assertEquals(1, closedCount[0]); + Assertions.assertEquals(1, closedCount[0]); yielder.close(); - Assert.assertEquals(2, closedCount[0]); + Assertions.assertEquals(2, closedCount[0]); } @Test @@ -276,7 +276,7 @@ public Integer accumulate(Integer accumulated, Integer in) } yielder.close(); - Assert.assertEquals(ImmutableList.of(1, 2, 3, 4, 5, 6), result); + Assertions.assertEquals(ImmutableList.of(1, 2, 3, 4, 5, 6), result); } @SuppressWarnings("unchecked") @@ -302,7 +302,7 @@ public TestSequence apply(Iterable input) ); for (TestSequence sequence : accumulationSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } List> yieldSeqs = Lists.newArrayList(theSequences); @@ -313,7 +313,7 @@ public TestSequence apply(Iterable input) ); for (TestSequence sequence : yieldSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } } } diff --git a/processing/src/test/java/org/apache/druid/java/util/common/guava/MergeSequenceTest.java b/processing/src/test/java/org/apache/druid/java/util/common/guava/MergeSequenceTest.java index f7817c75293a..687087c5b842 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/guava/MergeSequenceTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/guava/MergeSequenceTest.java @@ -23,9 +23,9 @@ import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Test; -import org.junit.internal.matchers.ThrowableMessageMatcher; +import org.hamcrest.MatcherAssert; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -51,7 +51,7 @@ public void testSanity() throws Exception SequenceTestHelper.testAll(seq, Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 8, 9)); for (TestSequence sequence : testSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } } @@ -71,7 +71,7 @@ public void testWorksWhenBeginningOutOfOrder() throws Exception SequenceTestHelper.testAll(seq, Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 8, 9)); for (TestSequence sequence : testSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } } @@ -92,7 +92,7 @@ public void testMergeEmpties() throws Exception SequenceTestHelper.testAll(seq, Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 8, 9)); for (TestSequence sequence : testSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } } @@ -113,7 +113,7 @@ public void testMergeEmpties1() throws Exception SequenceTestHelper.testAll(seq, Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 8, 9)); for (TestSequence sequence : testSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } } @@ -135,7 +135,7 @@ public void testMergeEmpties2() throws Exception SequenceTestHelper.testAll(seq, Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 8, 9)); for (TestSequence sequence : testSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } } @@ -155,7 +155,7 @@ public void testScrewsUpOnOutOfOrder() throws Exception SequenceTestHelper.testAll(seq, Arrays.asList(1, 2, 3, 4, 5, 4, 6, 7, 8, 9)); for (TestSequence sequence : testSeqs) { - Assert.assertTrue(sequence.isClosed()); + Assertions.assertTrue(sequence.isClosed()); } } @@ -204,26 +204,23 @@ public void testTwoExplodingOnGetSequences() Sequences.simple(ImmutableList.of(bomb1, bomb2)) ); - try { - mergeSequence.toYielder( - null, - new YieldingAccumulator() - { - @Override - public Integer accumulate(Integer accumulated, Integer in) + final Exception e1 = Assertions.assertThrows(Exception.class, () -> + mergeSequence.toYielder( + null, + new YieldingAccumulator() { - return in; + @Override + public Integer accumulate(Integer accumulated, Integer in) + { + return in; + } } - } - ); - Assert.fail("Expected exception"); - } - catch (Exception e) { - Assert.assertThat(e, ThrowableMessageMatcher.hasMessage(CoreMatchers.equalTo("get"))); - } + ) + ); + MatcherAssert.assertThat(e1.getMessage(), CoreMatchers.equalTo("get")); - Assert.assertEquals("Closes resources (1)", 1, bomb1.getCloseCount()); - Assert.assertEquals("Closes resources (2)", 1, bomb2.getCloseCount()); + Assertions.assertEquals(1, bomb1.getCloseCount(), "Closes resources (1)"); + Assertions.assertEquals(1, bomb2.getCloseCount(), "Closes resources (2)"); } @Test @@ -240,30 +237,27 @@ public void testTwoExplodingOnCloseSequences() Sequences.simple(ImmutableList.of(bomb1, bomb2)) ); - try { - mergeSequence.toYielder( - null, - new YieldingAccumulator() - { - @Override - public Integer accumulate(Integer accumulated, Integer in) + final Exception e2 = Assertions.assertThrows(Exception.class, () -> + mergeSequence.toYielder( + null, + new YieldingAccumulator() { - if (in > 1) { - throw new RuntimeException("boom"); + @Override + public Integer accumulate(Integer accumulated, Integer in) + { + if (in > 1) { + throw new RuntimeException("boom"); + } + + return in; } - - return in; } - } - ); - Assert.fail("Expected exception"); - } - catch (Exception e) { - Assert.assertThat(e, ThrowableMessageMatcher.hasMessage(CoreMatchers.equalTo("boom"))); - } + ) + ); + MatcherAssert.assertThat(e2.getMessage(), CoreMatchers.equalTo("boom")); - Assert.assertEquals("Closes resources (1)", 1, bomb1.getCloseCount()); - Assert.assertEquals("Closes resources (2)", 1, bomb2.getCloseCount()); + Assertions.assertEquals(1, bomb1.getCloseCount(), "Closes resources (1)"); + Assertions.assertEquals(1, bomb2.getCloseCount(), "Closes resources (2)"); } @Test @@ -278,28 +272,25 @@ public void testOneEmptyOneExplodingSequence() Sequences.simple(ImmutableList.of(Sequences.empty(), bomb)) ); - try { - mergeSequence.toYielder( - null, - new YieldingAccumulator() - { - @Override - public Integer accumulate(Integer accumulated, Integer in) + final Exception e3 = Assertions.assertThrows(Exception.class, () -> + mergeSequence.toYielder( + null, + new YieldingAccumulator() { - if (in > 1) { - throw new RuntimeException("boom"); + @Override + public Integer accumulate(Integer accumulated, Integer in) + { + if (in > 1) { + throw new RuntimeException("boom"); + } + + return in; } - - return in; } - } - ); - Assert.fail("Expected exception"); - } - catch (Exception e) { - Assert.assertThat(e, ThrowableMessageMatcher.hasMessage(CoreMatchers.equalTo("boom"))); - } + ) + ); + MatcherAssert.assertThat(e3.getMessage(), CoreMatchers.equalTo("boom")); - Assert.assertEquals("Closes resources", 1, bomb.getCloseCount()); + Assertions.assertEquals(1, bomb.getCloseCount(), "Closes resources"); } } diff --git a/processing/src/test/java/org/apache/druid/java/util/common/lifecycle/LifecycleTest.java b/processing/src/test/java/org/apache/druid/java/util/common/lifecycle/LifecycleTest.java index dbd0f4ed2d72..62fdf57e259c 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/lifecycle/LifecycleTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/lifecycle/LifecycleTest.java @@ -26,8 +26,8 @@ import com.google.common.util.concurrent.MoreExecutors; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.concurrent.Execs; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -116,8 +116,8 @@ public void stop() finally { lifecycle.stop(); } - Assert.assertEquals(numThreads - 1, threadFailedCount.get()); - Assert.assertEquals(0, handlerFailedCount.get()); + Assertions.assertEquals(numThreads - 1, threadFailedCount.get()); + Assertions.assertEquals(0, handlerFailedCount.get()); executorService.shutdownNow(); } @@ -153,7 +153,7 @@ public void stop() lifecycle.stop(); lifecycle.stop(); lifecycle.stop(); - Assert.assertEquals(0, failedCount.get()); + Assertions.assertEquals(0, failedCount.get()); Exception ex = null; try { exceptionalHandler.stop(); @@ -161,7 +161,7 @@ public void stop() catch (Exception e) { ex = e; } - Assert.assertNotNull("Should have exception", ex); + Assertions.assertNotNull(ex, "Should have exception"); } @Test @@ -187,15 +187,15 @@ public void testSanity() throws Exception lifecycle.start(); - Assert.assertEquals(10, startOrder.size()); - Assert.assertEquals(0, stopOrder.size()); - Assert.assertEquals(expectedOrder, startOrder); + Assertions.assertEquals(10, startOrder.size()); + Assertions.assertEquals(0, stopOrder.size()); + Assertions.assertEquals(expectedOrder, startOrder); lifecycle.stop(); - Assert.assertEquals(10, startOrder.size()); - Assert.assertEquals(10, stopOrder.size()); - Assert.assertEquals(Lists.reverse(expectedOrder), stopOrder); + Assertions.assertEquals(10, startOrder.size()); + Assertions.assertEquals(10, stopOrder.size()); + Assertions.assertEquals(Lists.reverse(expectedOrder), stopOrder); } @Test @@ -251,13 +251,13 @@ public void stop() lifecycle.start(); - Assert.assertEquals(expectedOrder, startOrder); - Assert.assertEquals(0, stopOrder.size()); + Assertions.assertEquals(expectedOrder, startOrder); + Assertions.assertEquals(0, stopOrder.size()); lifecycle.stop(); - Assert.assertEquals(expectedOrder, startOrder); - Assert.assertEquals(expectedStopOrder, stopOrder); + Assertions.assertEquals(expectedOrder, startOrder); + Assertions.assertEquals(expectedStopOrder, stopOrder); } public static class ObjectToBeLifecycled @@ -323,18 +323,18 @@ public void stop() try { lifecycle.addHandler(DUMMY_HANDLER); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (IllegalStateException e) { - Assert.assertTrue(e.getMessage().contains("Cannot add a handler")); + Assertions.assertTrue(e.getMessage().contains("Cannot add a handler")); } try { lifecycle.addMaybeStartHandler(DUMMY_HANDLER); - Assert.fail("Expected exception"); + Assertions.fail("Expected exception"); } catch (IllegalStateException e) { - Assert.assertTrue(e.getMessage().contains("Cannot add a handler")); + Assertions.assertTrue(e.getMessage().contains("Cannot add a handler")); } } } diff --git a/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java b/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java index 1b69d0bdec44..8aed3a87be8b 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java @@ -25,49 +25,40 @@ import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.parsers.AbstractFlatTextFormatParser.FlatTextFormat; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Arrays; -import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") public class FlatTextFormatParserTest extends InitializedNullHandlingTest { - @Parameters(name = "{0}") - public static Collection constructorFeeder() + public static Stream constructorFeeder() { return ImmutableList.of( new Object[]{FlatTextFormat.CSV}, new Object[]{FlatTextFormat.DELIMITED} - ); + ).stream(); } private static final FlatTextFormatParserFactory PARSER_FACTORY = new FlatTextFormatParserFactory(); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - private final FlatTextFormat format; - - public FlatTextFormatParserTest(FlatTextFormat format) - { - this.format = format; - } + @Parameter(0) + public FlatTextFormat format; @Test public void testValidHeader() { final String header = concat(format, "time", "value1", "value2"); final Parser parser = PARSER_FACTORY.get(format, header); - Assert.assertEquals(ImmutableList.of("time", "value1", "value2"), parser.getFieldNames()); + Assertions.assertEquals(ImmutableList.of("time", "value1", "value2"), parser.getFieldNames()); } @Test @@ -75,10 +66,11 @@ public void testDuplicatedColumnName() { final String header = concat(format, "time", "value1", "value2", "value2"); - expectedException.expect(ParseException.class); - expectedException.expectMessage(StringUtils.format("Unable to parse header [%s]", header)); - - PARSER_FACTORY.get(format, header); + Assertions.assertThrows( + ParseException.class, + () -> PARSER_FACTORY.get(format, header), + StringUtils.format("Unable to parse header [%s]", header) + ); } @Test @@ -88,10 +80,10 @@ public void testWithHeader() final Parser parser = PARSER_FACTORY.get(format, header); final String body = concat(format, "hello", "world", "foo"); final Map jsonMap = parser.parseToMap(body); - Assert.assertEquals( - "jsonMap", + Assertions.assertEquals( ImmutableMap.of("time", "hello", "value1", "world", "value2", "foo"), - jsonMap + jsonMap, + "jsonMap" ); } @@ -101,10 +93,10 @@ public void testWithoutHeader() final Parser parser = PARSER_FACTORY.get(format); final String body = concat(format, "hello", "world", "foo"); final Map jsonMap = parser.parseToMap(body); - Assert.assertEquals( - "jsonMap", + Assertions.assertEquals( ImmutableMap.of("column_1", "hello", "column_2", "world", "column_3", "foo"), - jsonMap + jsonMap, + "jsonMap" ); } @@ -121,13 +113,13 @@ public void testWithSkipHeaderRows() }; int index; for (index = 0; index < skipHeaderRows; index++) { - Assert.assertNull(parser.parseToMap(body[index])); + Assertions.assertNull(parser.parseToMap(body[index])); } final Map jsonMap = parser.parseToMap(body[index]); - Assert.assertEquals( - "jsonMap", + Assertions.assertEquals( ImmutableMap.of("column_1", "hello", "column_2", "world", "column_3", "foo"), - jsonMap + jsonMap, + "jsonMap" ); } @@ -140,12 +132,12 @@ public void testWithHeaderRow() concat(format, "time", "value1", "value2"), concat(format, "hello", "world", "foo") }; - Assert.assertNull(parser.parseToMap(body[0])); + Assertions.assertNull(parser.parseToMap(body[0])); final Map jsonMap = parser.parseToMap(body[1]); - Assert.assertEquals( - "jsonMap", + Assertions.assertEquals( ImmutableMap.of("time", "hello", "value1", "world", "value2", "foo"), - jsonMap + jsonMap, + "jsonMap" ); } @@ -158,12 +150,12 @@ public void testWithHeaderRowOfEmptyColumns() concat(format, "time", "", "value2", ""), concat(format, "hello", "world", "foo", "bar") }; - Assert.assertNull(parser.parseToMap(body[0])); + Assertions.assertNull(parser.parseToMap(body[0])); final Map jsonMap = parser.parseToMap(body[1]); - Assert.assertEquals( - "jsonMap", + Assertions.assertEquals( ImmutableMap.of("time", "hello", "column_2", "world", "value2", "foo", "column_4", "bar"), - jsonMap + jsonMap, + "jsonMap" ); } @@ -176,12 +168,12 @@ public void testWithDifferentHeaderRows() concat(format, "time", "value1", "value2"), concat(format, "hello", "world", "foo") }; - Assert.assertNull(parser.parseToMap(body[0])); + Assertions.assertNull(parser.parseToMap(body[0])); Map jsonMap = parser.parseToMap(body[1]); - Assert.assertEquals( - "jsonMap", + Assertions.assertEquals( ImmutableMap.of("time", "hello", "value1", "world", "value2", "foo"), - jsonMap + jsonMap, + "jsonMap" ); parser.startFileFromBeginning(); @@ -189,23 +181,18 @@ public void testWithDifferentHeaderRows() concat(format, "time", "value1", "value2", "value3"), concat(format, "hello", "world", "foo", "bar") }; - Assert.assertNull(parser.parseToMap(body2[0])); + Assertions.assertNull(parser.parseToMap(body2[0])); jsonMap = parser.parseToMap(body2[1]); - Assert.assertEquals( - "jsonMap", + Assertions.assertEquals( ImmutableMap.of("time", "hello", "value1", "world", "value2", "foo", "value3", "bar"), - jsonMap + jsonMap, + "jsonMap" ); } @Test public void testWithoutStartFileFromBeginning() { - expectedException.expect(UnsupportedOperationException.class); - expectedException.expectMessage( - "hasHeaderRow or maxSkipHeaderRows is not supported. Please check the indexTask supports these options." - ); - final int skipHeaderRows = 2; final Parser parser = PARSER_FACTORY.get(format, false, skipHeaderRows, false); final String[] body = new String[]{ @@ -213,7 +200,10 @@ public void testWithoutStartFileFromBeginning() concat(format, "header", "line", "2"), concat(format, "hello", "world", "foo") }; - parser.parseToMap(body[0]); + Assertions.assertThrows( + UnsupportedOperationException.class, + () -> parser.parseToMap(body[0]) + ); } @Test @@ -225,9 +215,9 @@ public void testWithNullValues() concat(format, "time", "value1", "value2"), concat(format, "hello", "world", "") }; - Assert.assertNull(parser.parseToMap(body[0])); + Assertions.assertNull(parser.parseToMap(body[0])); final Map jsonMap = parser.parseToMap(body[1]); - Assert.assertNull(jsonMap.get("value2")); + Assertions.assertNull(jsonMap.get("value2")); } private static class FlatTextFormatParserFactory diff --git a/processing/src/test/java/org/apache/druid/query/DataSourceTest.java b/processing/src/test/java/org/apache/druid/query/DataSourceTest.java index 8453003f7246..4e2c99fc8f1b 100644 --- a/processing/src/test/java/org/apache/druid/query/DataSourceTest.java +++ b/processing/src/test/java/org/apache/druid/query/DataSourceTest.java @@ -42,8 +42,8 @@ import org.apache.druid.segment.join.JoinType; import org.apache.druid.segment.join.JoinableFactoryWrapper; import org.apache.druid.segment.join.NoopJoinableFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; @@ -58,14 +58,14 @@ public void testSerialization() throws IOException DataSource dataSource = new TableDataSource("somedatasource"); String json = JSON_MAPPER.writeValueAsString(dataSource); DataSource serdeDataSource = JSON_MAPPER.readValue(json, DataSource.class); - Assert.assertEquals(dataSource, serdeDataSource); + Assertions.assertEquals(dataSource, serdeDataSource); } @Test public void testLegacyDataSource() throws IOException { DataSource dataSource = JSON_MAPPER.readValue("\"somedatasource\"", DataSource.class); - Assert.assertEquals(new TableDataSource("somedatasource"), dataSource); + Assertions.assertEquals(new TableDataSource("somedatasource"), dataSource); } @Test @@ -75,7 +75,7 @@ public void testTableDataSource() throws IOException "{\"type\":\"table\", \"name\":\"somedatasource\"}", DataSource.class ); - Assert.assertEquals(new TableDataSource("somedatasource"), dataSource); + Assertions.assertEquals(new TableDataSource("somedatasource"), dataSource); } @Test @@ -86,7 +86,7 @@ public void testRestrictedDataSource() throws IOException DataSource.class ); - Assert.assertEquals( + Assertions.assertEquals( RestrictedDataSource.create(TableDataSource.create("somedatasource"), NoRestrictionPolicy.instance()), dataSource ); @@ -107,7 +107,7 @@ public void testQueryDataSource() throws IOException String dataSourceJSON = "{\"type\":\"query\", \"query\":" + JSON_MAPPER.writeValueAsString(query) + "}"; DataSource dataSource = JSON_MAPPER.readValue(dataSourceJSON, DataSource.class); - Assert.assertEquals(new QueryDataSource(query), dataSource); + Assertions.assertEquals(new QueryDataSource(query), dataSource); } @Test @@ -117,18 +117,18 @@ public void testUnionDataSource() throws Exception "{\"type\":\"union\", \"dataSources\":[\"ds1\", \"ds2\"]}", DataSource.class ); - Assert.assertTrue(dataSource instanceof UnionDataSource); - Assert.assertEquals( + Assertions.assertInstanceOf(UnionDataSource.class, dataSource); + Assertions.assertEquals( Lists.newArrayList(new TableDataSource("ds1"), new TableDataSource("ds2")), Lists.newArrayList(dataSource.getChildren()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableSet.of("ds1", "ds2"), dataSource.getTableNames() ); final DataSource serde = JSON_MAPPER.readValue(JSON_MAPPER.writeValueAsString(dataSource), DataSource.class); - Assert.assertEquals(dataSource, serde); + Assertions.assertEquals(dataSource, serde); } @Test @@ -150,7 +150,7 @@ public void testWithPolicies_onUnionDataSource() ); PolicyEnforcer policyEnforcer = new RestrictAllTablesPolicyEnforcer(null); - Assert.assertEquals( + Assertions.assertEquals( unionDataSource.withPolicies(restrictions, policyEnforcer), new UnionDataSource(Lists.newArrayList( RestrictedDataSource.create( @@ -188,13 +188,13 @@ public void testWithPolicies_onUnionDataSource_throwsOnValidation() ); PolicyEnforcer policyEnforcer = new RestrictAllTablesPolicyEnforcer(ImmutableList.of(NoRestrictionPolicy.class.getName())); - DruidException e = Assert.assertThrows( + DruidException e = Assertions.assertThrows( DruidException.class, () -> unionDataSource.withPolicies(restrictions, policyEnforcer) ); - Assert.assertEquals(DruidException.Category.FORBIDDEN, e.getCategory()); - Assert.assertEquals(DruidException.Persona.OPERATOR, e.getTargetPersona()); - Assert.assertEquals( + Assertions.assertEquals(DruidException.Category.FORBIDDEN, e.getCategory()); + Assertions.assertEquals(DruidException.Persona.OPERATOR, e.getTargetPersona()); + Assertions.assertEquals( "Failed security validation with dataSource [table2]", e.getMessage() ); @@ -214,7 +214,7 @@ public void testWithPolicies_onRestrictedDataSource_fromDruidSystem() ); PolicyEnforcer policyEnforcer = new RestrictAllTablesPolicyEnforcer(null); - Assert.assertEquals(restrictedDataSource, restrictedDataSource.withPolicies(noRestrictionPolicy, policyEnforcer)); + Assertions.assertEquals(restrictedDataSource, restrictedDataSource.withPolicies(noRestrictionPolicy, policyEnforcer)); } @Test @@ -230,7 +230,7 @@ public void testWithPolicies_onRestrictedDataSource_samePolicy() ); PolicyEnforcer policyEnforcer = new RestrictAllTablesPolicyEnforcer(null); - Assert.assertEquals(restrictedDataSource, restrictedDataSource.withPolicies(policyMap, policyEnforcer)); + Assertions.assertEquals(restrictedDataSource, restrictedDataSource.withPolicies(policyMap, policyEnforcer)); } @Test @@ -248,20 +248,20 @@ public void testWithPolicies_onRestrictedDataSource_alwaysThrows() ImmutableMap> policyWasNotChecked = ImmutableMap.of(); PolicyEnforcer policyEnforcer = new RestrictAllTablesPolicyEnforcer(null); - ISE e = Assert.assertThrows( + ISE e = Assertions.assertThrows( ISE.class, () -> restrictedDataSource.withPolicies(anotherRestrictions, policyEnforcer) ); - Assert.assertEquals( + Assertions.assertEquals( "Different restrictions on table [table1]: previous policy [RowFilterPolicy{rowFilter=random-column IS NULL}] and new policy [RowFilterPolicy{rowFilter=some-column IS NULL}]", e.getMessage() ); - ISE e3 = Assert.assertThrows( + ISE e3 = Assertions.assertThrows( ISE.class, () -> restrictedDataSource.withPolicies(policyWasNotChecked, policyEnforcer) ); - Assert.assertEquals("Missing policy check result for table [table1]", e3.getMessage()); + Assertions.assertEquals("Missing policy check result for table [table1]", e3.getMessage()); } @Test @@ -269,7 +269,7 @@ public void testWithPolicies_onInlineDataSource() { InlineDataSource inlineDataSource = InlineDataSource.fromIterable(ImmutableList.of(), RowSignature.empty()); DataSource withPolicies = inlineDataSource.withPolicies(ImmutableMap.of(), NoopPolicyEnforcer.instance()); - Assert.assertEquals(inlineDataSource, withPolicies); + Assertions.assertEquals(inlineDataSource, withPolicies); } @Test @@ -289,16 +289,16 @@ public void testWithPolicies_onJoinDataSource() ); final PolicyEnforcer policyEnforcer = NoopPolicyEnforcer.instance(); DataSource mapped = joinDataSource.withPolicies(ImmutableMap.of(), policyEnforcer); - Assert.assertEquals(joinDataSource, mapped); + Assertions.assertEquals(joinDataSource, mapped); // Use stricter enforcer final PolicyEnforcer restrictAllTablesPolicyEnforcer = new RestrictAllTablesPolicyEnforcer(null); // Fail, policy must exist on both tables - Assert.assertThrows( + Assertions.assertThrows( DruidException.class, () -> joinDataSource.withPolicies(ImmutableMap.of(), restrictAllTablesPolicyEnforcer) ); - Assert.assertThrows( + Assertions.assertThrows( DruidException.class, () -> joinDataSource.withPolicies(ImmutableMap.of( "table1", @@ -324,6 +324,6 @@ public void testWithPolicies_onJoinDataSource() joinableFactoryWrapper, JoinAlgorithm.BROADCAST ); - Assert.assertEquals(expected, mapped2); + Assertions.assertEquals(expected, mapped2); } } diff --git a/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java b/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java index 8e6b704411ee..9a233428afe1 100644 --- a/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java +++ b/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java @@ -31,10 +31,8 @@ import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.column.RowSignature; import org.apache.druid.segment.column.ValueType; -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.util.Collections; import java.util.List; @@ -42,9 +40,6 @@ public class InlineDataSourceTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private final AtomicLong iterationCounter = new AtomicLong(); // raw arrays, e.g. double[]{1.0, 2.0} on round trip get deserialized into List, so just model that @@ -98,35 +93,35 @@ public InlineDataSourceTest() @Test public void test_getTableNames() { - Assert.assertEquals(Collections.emptySet(), listDataSource.getTableNames()); - Assert.assertEquals(Collections.emptySet(), iterableDataSource.getTableNames()); + Assertions.assertEquals(Collections.emptySet(), listDataSource.getTableNames()); + Assertions.assertEquals(Collections.emptySet(), iterableDataSource.getTableNames()); } @Test public void test_getColumnNames() { - Assert.assertEquals(expectedColumnNames, listDataSource.getColumnNames()); - Assert.assertEquals(expectedColumnNames, iterableDataSource.getColumnNames()); + Assertions.assertEquals(expectedColumnNames, listDataSource.getColumnNames()); + Assertions.assertEquals(expectedColumnNames, iterableDataSource.getColumnNames()); } @Test public void test_getColumnTypes() { - Assert.assertEquals(expectedColumnTypes, listDataSource.getColumnTypes()); - Assert.assertEquals(expectedColumnTypes, iterableDataSource.getColumnTypes()); + Assertions.assertEquals(expectedColumnTypes, listDataSource.getColumnTypes()); + Assertions.assertEquals(expectedColumnTypes, iterableDataSource.getColumnTypes()); } @Test public void test_getChildren() { - Assert.assertEquals(Collections.emptyList(), listDataSource.getChildren()); - Assert.assertEquals(Collections.emptyList(), iterableDataSource.getChildren()); + Assertions.assertEquals(Collections.emptyList(), listDataSource.getChildren()); + Assertions.assertEquals(Collections.emptyList(), iterableDataSource.getChildren()); } @Test public void test_getRowSignature() { - Assert.assertEquals( + Assertions.assertEquals( RowSignature.builder() .add(ColumnHolder.TIME_COLUMN_NAME, ColumnType.LONG) .add("str", ColumnType.STRING) @@ -141,20 +136,20 @@ public void test_getRowSignature() @Test public void test_isCacheable() { - Assert.assertFalse(listDataSource.isCacheable(true)); - Assert.assertFalse(listDataSource.isCacheable(false)); + Assertions.assertFalse(listDataSource.isCacheable(true)); + Assertions.assertFalse(listDataSource.isCacheable(false)); } @Test public void test_isGlobal() { - Assert.assertTrue(listDataSource.isGlobal()); + Assertions.assertTrue(listDataSource.isGlobal()); } @Test public void test_isConcrete() { - Assert.assertTrue(listDataSource.isProcessable()); + Assertions.assertTrue(listDataSource.isProcessable()); } @Test @@ -163,43 +158,43 @@ public void test_rowAdapter() final RowAdapter adapter = listDataSource.rowAdapter(); final Object[] row = rows.get(1); - Assert.assertEquals(DateTimes.of("2000").getMillis(), adapter.timestampFunction().applyAsLong(row)); - Assert.assertEquals("bar", adapter.columnFunction("str").apply(row)); - Assert.assertEquals(1d, adapter.columnFunction("double").apply(row)); - Assert.assertEquals(ImmutableMap.of("n", "1"), adapter.columnFunction("complex").apply(row)); - Assert.assertEquals(ImmutableList.of(2.0, 4.0), adapter.columnFunction("double_array").apply(row)); + Assertions.assertEquals(DateTimes.of("2000").getMillis(), adapter.timestampFunction().applyAsLong(row)); + Assertions.assertEquals("bar", adapter.columnFunction("str").apply(row)); + Assertions.assertEquals(1d, adapter.columnFunction("double").apply(row)); + Assertions.assertEquals(ImmutableMap.of("n", "1"), adapter.columnFunction("complex").apply(row)); + Assertions.assertEquals(ImmutableList.of(2.0, 4.0), adapter.columnFunction("double_array").apply(row)); } @Test public void test_getRows_list() { - Assert.assertSame(this.rows, listDataSource.getRowsAsList()); + Assertions.assertSame(this.rows, listDataSource.getRowsAsList()); } @Test public void test_getRows_iterable() { final Iterable iterable = iterableDataSource.getRows(); - Assert.assertNotSame(this.rows, iterable); + Assertions.assertNotSame(this.rows, iterable); // No iteration yet. - Assert.assertEquals(0, iterationCounter.get()); + Assertions.assertEquals(0, iterationCounter.get()); assertRowsEqual(this.rows, ImmutableList.copyOf(iterable)); // OK, now we've iterated. - Assert.assertEquals(1, iterationCounter.get()); + Assertions.assertEquals(1, iterationCounter.get()); // Read again, we should iterate again. //noinspection MismatchedQueryAndUpdateOfCollection final List ignored = Lists.newArrayList(iterable); - Assert.assertEquals(2, iterationCounter.get()); + Assertions.assertEquals(2, iterationCounter.get()); } @Test public void test_getRowsAsList_list() { - Assert.assertSame(this.rows, listDataSource.getRowsAsList()); + Assertions.assertSame(this.rows, listDataSource.getRowsAsList()); } @Test @@ -207,29 +202,29 @@ public void test_getRowsAsList_iterable() { final List list = iterableDataSource.getRowsAsList(); - Assert.assertEquals(1, iterationCounter.get()); + Assertions.assertEquals(1, iterationCounter.get()); assertRowsEqual(this.rows, list); // Read again, we should *not* iterate again (in contrast to "test_getRows_iterable"). //noinspection MismatchedQueryAndUpdateOfCollection final List ignored = Lists.newArrayList(list); - Assert.assertEquals(1, iterationCounter.get()); + Assertions.assertEquals(1, iterationCounter.get()); } @Test public void test_withChildren_empty() { - Assert.assertSame(listDataSource, listDataSource.withChildren(Collections.emptyList())); + Assertions.assertSame(listDataSource, listDataSource.withChildren(Collections.emptyList())); } @Test public void test_withChildren_nonEmpty() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Cannot accept children"); - - // Workaround so "withChildren" isn't flagged as unused in the DataSource interface. - ((DataSource) listDataSource).withChildren(ImmutableList.of(new TableDataSource("foo"))); + Assertions.assertThrows( + IllegalArgumentException.class, + // Workaround so "withChildren" isn't flagged as unused in the DataSource interface. + () -> ((DataSource) listDataSource).withChildren(ImmutableList.of(new TableDataSource("foo"))) + ); } @Test @@ -246,7 +241,7 @@ public void test_toString_iterable() { // Verify that toString does not iterate the rows. final String ignored = iterableDataSource.toString(); - Assert.assertEquals(0, iterationCounter.get()); + Assertions.assertEquals(0, iterationCounter.get()); } @Test @@ -258,9 +253,9 @@ public void test_serde_list() throws Exception DataSource.class ); - Assert.assertEquals(listDataSource.getColumnNames(), deserialized.getColumnNames()); - Assert.assertEquals(listDataSource.getColumnTypes(), deserialized.getColumnTypes()); - Assert.assertEquals(listDataSource.getRowSignature(), deserialized.getRowSignature()); + Assertions.assertEquals(listDataSource.getColumnNames(), deserialized.getColumnNames()); + Assertions.assertEquals(listDataSource.getColumnTypes(), deserialized.getColumnTypes()); + Assertions.assertEquals(listDataSource.getRowSignature(), deserialized.getRowSignature()); assertRowsEqual(listDataSource.getRows(), deserialized.getRows()); } @@ -274,13 +269,13 @@ public void test_serde_iterable() throws Exception ); // Lazy iterables turn into Lists upon serialization. - Assert.assertEquals(listDataSource.getColumnNames(), deserialized.getColumnNames()); - Assert.assertEquals(listDataSource.getColumnTypes(), deserialized.getColumnTypes()); - Assert.assertEquals(listDataSource.getRowSignature(), deserialized.getRowSignature()); + Assertions.assertEquals(listDataSource.getColumnNames(), deserialized.getColumnNames()); + Assertions.assertEquals(listDataSource.getColumnTypes(), deserialized.getColumnTypes()); + Assertions.assertEquals(listDataSource.getRowSignature(), deserialized.getRowSignature()); assertRowsEqual(listDataSource.getRows(), deserialized.getRows()); // Should have iterated once. - Assert.assertEquals(1, iterationCounter.get()); + Assertions.assertEquals(1, iterationCounter.get()); } @Test @@ -301,10 +296,10 @@ public void test_serde_untyped() throws Exception DataSource.class ); - Assert.assertEquals(untypedDataSource.getColumnNames(), deserialized.getColumnNames()); - Assert.assertEquals(untypedDataSource.getColumnTypes(), deserialized.getColumnTypes()); - Assert.assertEquals(untypedDataSource.getRowSignature(), deserialized.getRowSignature()); - Assert.assertNull(deserialized.getColumnTypes()); + Assertions.assertEquals(untypedDataSource.getColumnNames(), deserialized.getColumnNames()); + Assertions.assertEquals(untypedDataSource.getColumnTypes(), deserialized.getColumnTypes()); + Assertions.assertEquals(untypedDataSource.getRowSignature(), deserialized.getRowSignature()); + Assertions.assertNull(deserialized.getColumnTypes()); assertRowsEqual(listDataSource.getRows(), deserialized.getRows()); } @@ -320,18 +315,18 @@ private static void assertRowsEqual(final Iterable expectedRows, final final List actualRowsList = (List) actualRows; final int sz = expectedRowsList.size(); - Assert.assertEquals("number of rows", sz, actualRowsList.size()); + Assertions.assertEquals(sz, actualRowsList.size(), "number of rows"); // Super slow for LinkedLists, but we don't expect those to be used here. // (They're generally forbidden in Druid except for special cases.) for (int i = 0; i < sz; i++) { - Assert.assertArrayEquals("row #" + i, expectedRowsList.get(i), actualRowsList.get(i)); + Assertions.assertArrayEquals(expectedRowsList.get(i), actualRowsList.get(i), "row #" + i); } } else { // If they're not both Lists, we don't want to iterate them during equality checks, so do a non-deep check. // This might still return true if whatever class they are has another way of checking equality. But, usually we // expect this to return false. - Assert.assertEquals("rows", expectedRows, actualRows); + Assertions.assertEquals(expectedRows, actualRows, "rows"); } } diff --git a/processing/src/test/java/org/apache/druid/query/QueryContextsTest.java b/processing/src/test/java/org/apache/druid/query/QueryContextsTest.java index 735fabe0f8b3..b4e058547981 100644 --- a/processing/src/test/java/org/apache/druid/query/QueryContextsTest.java +++ b/processing/src/test/java/org/apache/druid/query/QueryContextsTest.java @@ -24,19 +24,14 @@ import org.apache.druid.java.util.common.HumanReadableBytes; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.query.spec.MultipleIntervalSegmentSpec; -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.util.HashMap; import java.util.Map; public class QueryContextsTest { - @Rule - public final ExpectedException exception = ExpectedException.none(); - @Test public void testDefaultQueryTimeout() { @@ -45,7 +40,7 @@ public void testDefaultQueryTimeout() new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), new HashMap<>() ); - Assert.assertEquals(300_000, query.context().getDefaultTimeout()); + Assertions.assertEquals(300_000, query.context().getDefaultTimeout()); } @Test @@ -56,10 +51,10 @@ public void testEmptyQueryTimeout() new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), new HashMap<>() ); - Assert.assertEquals(300_000, query.context().getTimeout()); + Assertions.assertEquals(300_000, query.context().getTimeout()); query = Queries.withDefaultTimeout(query, 60_000); - Assert.assertEquals(60_000, query.context().getTimeout()); + Assertions.assertEquals(60_000, query.context().getTimeout()); } @Test @@ -70,38 +65,42 @@ public void testQueryTimeout() new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), ImmutableMap.of(QueryContexts.TIMEOUT_KEY, 1000) ); - Assert.assertEquals(1000, query.context().getTimeout()); + Assertions.assertEquals(1000, query.context().getTimeout()); query = Queries.withDefaultTimeout(query, 1_000_000); - Assert.assertEquals(1000, query.context().getTimeout()); + Assertions.assertEquals(1000, query.context().getTimeout()); } @Test public void testQueryMaxTimeout() { - exception.expect(BadQueryContextException.class); - exception.expectMessage("Configured timeout = 1000 is more than enforced limit of 100."); Query query = new TestQuery( new TableDataSource("test"), new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), ImmutableMap.of(QueryContexts.TIMEOUT_KEY, 1000) ); - query.context().verifyMaxQueryTimeout(100); + BadQueryContextException ex = Assertions.assertThrows( + BadQueryContextException.class, + () -> query.context().verifyMaxQueryTimeout(100) + ); + Assertions.assertTrue(ex.getMessage().contains("Configured timeout = 1000 is more than enforced limit of 100.")); } @Test public void testMaxScatterGatherBytes() { - exception.expect(BadQueryContextException.class); - exception.expectMessage("Configured maxScatterGatherBytes = 1000 is more than enforced limit of 100."); Query query = new TestQuery( new TableDataSource("test"), new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), ImmutableMap.of(QueryContexts.MAX_SCATTER_GATHER_BYTES_KEY, 1000) ); - Queries.withMaxScatterGatherBytes(query, 100); + BadQueryContextException ex = Assertions.assertThrows( + BadQueryContextException.class, + () -> Queries.withMaxScatterGatherBytes(query, 100) + ); + Assertions.assertTrue(ex.getMessage().contains("Configured maxScatterGatherBytes = 1000 is more than enforced limit of 100.")); } @Test @@ -112,7 +111,7 @@ public void testDisableSegmentPruning() new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), ImmutableMap.of(QueryContexts.SECONDARY_PARTITION_PRUNING_KEY, false) ); - Assert.assertFalse(query.context().isSecondaryPartitionPruningEnabled()); + Assertions.assertFalse(query.context().isSecondaryPartitionPruningEnabled()); } @Test @@ -123,13 +122,13 @@ public void testDefaultSegmentPruning() new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), ImmutableMap.of() ); - Assert.assertTrue(query.context().isSecondaryPartitionPruningEnabled()); + Assertions.assertTrue(query.context().isSecondaryPartitionPruningEnabled()); } @Test public void testDefaultInSubQueryThreshold() { - Assert.assertEquals( + Assertions.assertEquals( QueryContexts.DEFAULT_IN_SUB_QUERY_THRESHOLD, QueryContext.empty().getInSubQueryThreshold() ); @@ -138,7 +137,7 @@ public void testDefaultInSubQueryThreshold() @Test public void testDefaultPlanTimeBoundarySql() { - Assert.assertEquals( + Assertions.assertEquals( QueryContexts.DEFAULT_ENABLE_TIME_BOUNDARY_PLANNING, QueryContext.empty().isTimeBoundaryPlanningEnabled() ); @@ -147,7 +146,7 @@ public void testDefaultPlanTimeBoundarySql() @Test public void testDefaultCloneQueryMode() { - Assert.assertEquals( + Assertions.assertEquals( CloneQueryMode.EXCLUDECLONES, QueryContext.empty().getCloneQueryMode() ); @@ -156,30 +155,29 @@ public void testDefaultCloneQueryMode() @Test public void testCatalogValidationEnabled() { - Assert.assertEquals( + Assertions.assertEquals( QueryContexts.DEFAULT_CATALOG_VALIDATION_ENABLED, QueryContext.empty().isCatalogValidationEnabled() ); - Assert.assertTrue(QueryContext.of(ImmutableMap.of( + Assertions.assertTrue(QueryContext.of(ImmutableMap.of( QueryContexts.CATALOG_VALIDATION_ENABLED, true )).isCatalogValidationEnabled()); - Assert.assertFalse(QueryContext.of(ImmutableMap.of( + Assertions.assertFalse(QueryContext.of(ImmutableMap.of( QueryContexts.CATALOG_VALIDATION_ENABLED, false )).isCatalogValidationEnabled()); } - @Test public void testGetEnableJoinLeftScanDirect() { - Assert.assertFalse(QueryContext.empty().getEnableJoinLeftScanDirect()); - Assert.assertTrue(QueryContext.of(ImmutableMap.of( + Assertions.assertFalse(QueryContext.empty().getEnableJoinLeftScanDirect()); + Assertions.assertTrue(QueryContext.of(ImmutableMap.of( QueryContexts.SQL_JOIN_LEFT_SCAN_DIRECT, true )).getEnableJoinLeftScanDirect()); - Assert.assertFalse(QueryContext.of(ImmutableMap.of( + Assertions.assertFalse(QueryContext.of(ImmutableMap.of( QueryContexts.SQL_JOIN_LEFT_SCAN_DIRECT, false )).getEnableJoinLeftScanDirect()); @@ -189,10 +187,10 @@ public void testGetEnableJoinLeftScanDirect() public void testGetBrokerServiceName() { Map queryContext = new HashMap<>(); - Assert.assertNull(QueryContext.of(queryContext).getBrokerServiceName()); + Assertions.assertNull(QueryContext.of(queryContext).getBrokerServiceName()); queryContext.put(QueryContexts.BROKER_SERVICE_NAME, "hotBroker"); - Assert.assertEquals("hotBroker", QueryContext.of(queryContext).getBrokerServiceName()); + Assertions.assertEquals("hotBroker", QueryContext.of(queryContext).getBrokerServiceName()); } @Test @@ -201,8 +199,7 @@ public void testGetBrokerServiceName_withNonStringValue() Map queryContext = new HashMap<>(); queryContext.put(QueryContexts.BROKER_SERVICE_NAME, 100); - exception.expect(BadQueryContextException.class); - QueryContext.of(queryContext).getBrokerServiceName(); + Assertions.assertThrows(BadQueryContextException.class, () -> QueryContext.of(queryContext).getBrokerServiceName()); } @Test @@ -211,61 +208,63 @@ public void testGetTimeout_withNonNumericValue() Map queryContext = new HashMap<>(); queryContext.put(QueryContexts.TIMEOUT_KEY, "2000'"); - exception.expect(BadQueryContextException.class); - new TestQuery( - new TableDataSource("test"), - new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), - queryContext - ).context().getTimeout(); + Assertions.assertThrows( + BadQueryContextException.class, + () -> new TestQuery( + new TableDataSource("test"), + new MultipleIntervalSegmentSpec(ImmutableList.of(Intervals.of("0/100"))), + queryContext + ).context().getTimeout() + ); } @Test public void testGetAs() { - Assert.assertNull(QueryContexts.getAsString("foo", null, null)); - Assert.assertEquals("default", QueryContexts.getAsString("foo", null, "default")); - Assert.assertEquals("value", QueryContexts.getAsString("foo", "value", "default")); + Assertions.assertNull(QueryContexts.getAsString("foo", null, null)); + Assertions.assertEquals("default", QueryContexts.getAsString("foo", null, "default")); + Assertions.assertEquals("value", QueryContexts.getAsString("foo", "value", "default")); try { QueryContexts.getAsString("foo", 10, null); - Assert.fail(); + Assertions.fail(); } catch (BadQueryContextException e) { // Expected } - Assert.assertFalse(QueryContexts.getAsBoolean("foo", null, false)); - Assert.assertTrue(QueryContexts.getAsBoolean("foo", null, true)); - Assert.assertTrue(QueryContexts.getAsBoolean("foo", "true", false)); - Assert.assertTrue(QueryContexts.getAsBoolean("foo", true, false)); + Assertions.assertFalse(QueryContexts.getAsBoolean("foo", null, false)); + Assertions.assertTrue(QueryContexts.getAsBoolean("foo", null, true)); + Assertions.assertTrue(QueryContexts.getAsBoolean("foo", "true", false)); + Assertions.assertTrue(QueryContexts.getAsBoolean("foo", true, false)); try { QueryContexts.getAsBoolean("foo", 10, false); - Assert.fail(); + Assertions.fail(); } catch (BadQueryContextException e) { // Expected } - Assert.assertEquals(10, QueryContexts.getAsInt("foo", null, 10)); - Assert.assertEquals(20, QueryContexts.getAsInt("foo", "20", 10)); - Assert.assertEquals(20, QueryContexts.getAsInt("foo", 20, 10)); - Assert.assertEquals(20, QueryContexts.getAsInt("foo", 20L, 10)); - Assert.assertEquals(20, QueryContexts.getAsInt("foo", 20D, 10)); + Assertions.assertEquals(10, QueryContexts.getAsInt("foo", null, 10)); + Assertions.assertEquals(20, QueryContexts.getAsInt("foo", "20", 10)); + Assertions.assertEquals(20, QueryContexts.getAsInt("foo", 20, 10)); + Assertions.assertEquals(20, QueryContexts.getAsInt("foo", 20L, 10)); + Assertions.assertEquals(20, QueryContexts.getAsInt("foo", 20D, 10)); try { QueryContexts.getAsInt("foo", true, 20); - Assert.fail(); + Assertions.fail(); } catch (BadQueryContextException e) { // Expected } - Assert.assertEquals(10L, QueryContexts.getAsLong("foo", null, 10)); - Assert.assertEquals(20L, QueryContexts.getAsLong("foo", "20", 10)); - Assert.assertEquals(20L, QueryContexts.getAsLong("foo", 20, 10)); - Assert.assertEquals(20L, QueryContexts.getAsLong("foo", 20L, 10)); - Assert.assertEquals(20L, QueryContexts.getAsLong("foo", 20D, 10)); + Assertions.assertEquals(10L, QueryContexts.getAsLong("foo", null, 10)); + Assertions.assertEquals(20L, QueryContexts.getAsLong("foo", "20", 10)); + Assertions.assertEquals(20L, QueryContexts.getAsLong("foo", 20, 10)); + Assertions.assertEquals(20L, QueryContexts.getAsLong("foo", 20L, 10)); + Assertions.assertEquals(20L, QueryContexts.getAsLong("foo", 20D, 10)); try { QueryContexts.getAsLong("foo", true, 20); - Assert.fail(); + Assertions.fail(); } catch (BadQueryContextException e) { // Expected @@ -275,17 +274,17 @@ public void testGetAs() @Test public void testGetAsHumanReadableBytes() { - Assert.assertEquals( + Assertions.assertEquals( new HumanReadableBytes("500M").getBytes(), QueryContexts.getAsHumanReadableBytes("maxOnDiskStorage", 500_000_000, HumanReadableBytes.ZERO) .getBytes() ); - Assert.assertEquals( + Assertions.assertEquals( new HumanReadableBytes("500M").getBytes(), QueryContexts.getAsHumanReadableBytes("maxOnDiskStorage", "500000000", HumanReadableBytes.ZERO) .getBytes() ); - Assert.assertEquals( + Assertions.assertEquals( new HumanReadableBytes("500M").getBytes(), QueryContexts.getAsHumanReadableBytes("maxOnDiskStorage", "500M", HumanReadableBytes.ZERO) .getBytes() @@ -303,12 +302,12 @@ public void testGetEnum() ) ); - Assert.assertEquals( + Assertions.assertEquals( QueryContexts.Vectorize.FORCE, query.context().getEnum("e1", QueryContexts.Vectorize.class, QueryContexts.Vectorize.FALSE) ); - Assert.assertThrows( + Assertions.assertThrows( BadQueryContextException.class, () -> query.context().getEnum("e2", QueryContexts.Vectorize.class, QueryContexts.Vectorize.FALSE) ); @@ -323,12 +322,12 @@ public void testExecutionModeEnum() ImmutableMap.of(QueryContexts.CTX_EXECUTION_MODE, "SYNC", QueryContexts.CTX_EXECUTION_MODE + "_1", "ASYNC") ); - Assert.assertEquals( + Assertions.assertEquals( ExecutionMode.SYNC, query.context().getEnum(QueryContexts.CTX_EXECUTION_MODE, ExecutionMode.class, ExecutionMode.ASYNC) ); - Assert.assertEquals( + Assertions.assertEquals( ExecutionMode.ASYNC, query.context().getEnum(QueryContexts.CTX_EXECUTION_MODE + "_1", ExecutionMode.class, ExecutionMode.SYNC) ); diff --git a/processing/src/test/java/org/apache/druid/query/TimewarpOperatorTest.java b/processing/src/test/java/org/apache/druid/query/TimewarpOperatorTest.java index 0563b98977b5..94f4c7940431 100644 --- a/processing/src/test/java/org/apache/druid/query/TimewarpOperatorTest.java +++ b/processing/src/test/java/org/apache/druid/query/TimewarpOperatorTest.java @@ -34,12 +34,11 @@ import org.joda.time.DateTimeZone; import org.joda.time.Interval; import org.joda.time.Period; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; - public class TimewarpOperatorTest { TimewarpOperator> testOperator = new TimewarpOperator<>( @@ -55,21 +54,21 @@ public void testComputeOffset() final DateTime t = DateTimes.of("2014-01-23"); final DateTime tOffset = DateTimes.of("2014-01-09"); - Assert.assertEquals(tOffset, t.plus(testOperator.computeOffset(t.getMillis(), DateTimeZone.UTC))); + Assertions.assertEquals(tOffset, t.plus(testOperator.computeOffset(t.getMillis(), DateTimeZone.UTC))); } { final DateTime t = DateTimes.of("2014-08-02"); final DateTime tOffset = DateTimes.of("2014-01-11"); - Assert.assertEquals(tOffset, t.plus(testOperator.computeOffset(t.getMillis(), DateTimeZone.UTC))); + Assertions.assertEquals(tOffset, t.plus(testOperator.computeOffset(t.getMillis(), DateTimeZone.UTC))); } { final DateTime t = DateTimes.of("2014-08-02T-07"); final DateTime tOffset = DateTimes.of("2014-01-11T-08"); - Assert.assertEquals( + Assertions.assertEquals( tOffset, t.plus(testOperator.computeOffset(t.getMillis(), DateTimes.inferTzFromString("America/Los_Angeles"))) ); @@ -116,7 +115,7 @@ public Sequence> run( .aggregators(Collections.singletonList(new CountAggregatorFactory("count"))) .build(); - Assert.assertEquals( + Assertions.assertEquals( Lists.newArrayList( new Result<>( DateTimes.of("2014-07-31"), @@ -134,7 +133,6 @@ public Sequence> run( queryRunner.run(QueryPlus.wrap(query)).toList() ); - TimewarpOperator> timeBoundaryOperator = new TimewarpOperator<>( new Interval(DateTimes.of("2014-01-01"), DateTimes.of("2014-01-15")), new Period("P1W"), @@ -173,7 +171,7 @@ public Sequence> run( .dataSource("dummy") .build(); - Assert.assertEquals( + Assertions.assertEquals( Collections.singletonList( new Result<>( DateTimes.of("2014-08-02"), @@ -226,7 +224,7 @@ public Sequence> run( .aggregators(Collections.singletonList(new CountAggregatorFactory("count"))) .build(); - Assert.assertEquals( + Assertions.assertEquals( Lists.newArrayList( new Result<>( DateTimes.of("2014-07-31T-07"), @@ -286,7 +284,7 @@ public Sequence> run( .aggregators(Collections.singletonList(new CountAggregatorFactory("count"))) .build(); - Assert.assertEquals( + Assertions.assertEquals( Lists.newArrayList( new Result<>( DateTimes.of("2014-07-31T-07"), @@ -311,7 +309,7 @@ public void testEmptyFutureInterval() QueryRunner> queryRunner = testOperator.postProcess( (queryPlus, responseContext) -> { final Query> query = queryPlus.getQuery(); - Assert.assertTrue(query.getIntervals().isEmpty()); + Assertions.assertTrue(query.getIntervals().isEmpty()); return Sequences.empty(); }, DateTimes.of("2014-08-02").getMillis() @@ -324,7 +322,7 @@ public void testEmptyFutureInterval() .aggregators(Collections.singletonList(new CountAggregatorFactory("count"))) .build(); - Assert.assertEquals( + Assertions.assertEquals( Collections.emptyList(), queryRunner.run(QueryPlus.wrap(query)).toList() ); diff --git a/processing/src/test/java/org/apache/druid/query/aggregation/AggregatorFactoryTest.java b/processing/src/test/java/org/apache/druid/query/aggregation/AggregatorFactoryTest.java index ff7b18c3dca2..9e057705c479 100644 --- a/processing/src/test/java/org/apache/druid/query/aggregation/AggregatorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/query/aggregation/AggregatorFactoryTest.java @@ -46,8 +46,8 @@ import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.column.RowSignature; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -61,24 +61,24 @@ public class AggregatorFactoryTest extends InitializedNullHandlingTest @Test public void testMergeAggregators() { - Assert.assertNull(AggregatorFactory.mergeAggregators(null)); - Assert.assertNull(AggregatorFactory.mergeAggregators(ImmutableList.of())); + Assertions.assertNull(AggregatorFactory.mergeAggregators(null)); + Assertions.assertNull(AggregatorFactory.mergeAggregators(ImmutableList.of())); List aggregatorsToBeMerged = new ArrayList<>(); aggregatorsToBeMerged.add(null); - Assert.assertNull(AggregatorFactory.mergeAggregators(aggregatorsToBeMerged)); + Assertions.assertNull(AggregatorFactory.mergeAggregators(aggregatorsToBeMerged)); AggregatorFactory[] emptyAggFactory = new AggregatorFactory[0]; aggregatorsToBeMerged.clear(); aggregatorsToBeMerged.add(emptyAggFactory); - Assert.assertArrayEquals(emptyAggFactory, AggregatorFactory.mergeAggregators(aggregatorsToBeMerged)); + Assertions.assertArrayEquals(emptyAggFactory, AggregatorFactory.mergeAggregators(aggregatorsToBeMerged)); aggregatorsToBeMerged.clear(); aggregatorsToBeMerged.add(emptyAggFactory); aggregatorsToBeMerged.add(null); - Assert.assertNull(AggregatorFactory.mergeAggregators(aggregatorsToBeMerged)); + Assertions.assertNull(AggregatorFactory.mergeAggregators(aggregatorsToBeMerged)); aggregatorsToBeMerged.clear(); AggregatorFactory[] af1 = new AggregatorFactory[]{ @@ -87,7 +87,7 @@ public void testMergeAggregators() AggregatorFactory[] af2 = new AggregatorFactory[]{ new LongMaxAggregatorFactory("name", "fieldName2") }; - Assert.assertArrayEquals( + Assertions.assertArrayEquals( new AggregatorFactory[]{ new LongMaxAggregatorFactory("name", "name") }, @@ -101,7 +101,7 @@ public void testMergeAggregators() af2 = new AggregatorFactory[]{ new DoubleMaxAggregatorFactory("name", "fieldName2") }; - Assert.assertNull(AggregatorFactory.mergeAggregators(ImmutableList.of(af1, af2)) + Assertions.assertNull(AggregatorFactory.mergeAggregators(ImmutableList.of(af1, af2)) ); } @@ -201,7 +201,7 @@ public void testResultArraySignature() ) .build(); - Assert.assertEquals( + Assertions.assertEquals( RowSignature.builder() .addTimeColumn() // aggs @@ -325,8 +325,8 @@ public void testWithName() ); for (AggregatorFactory aggregatorFactory : aggregatorFactories) { - Assert.assertEquals(aggregatorFactory, aggregatorFactory.withName("col")); - Assert.assertEquals("newTest", aggregatorFactory.withName("newTest").getName()); + Assertions.assertEquals(aggregatorFactory, aggregatorFactory.withName("col")); + Assertions.assertEquals("newTest", aggregatorFactory.withName("newTest").getName()); } } } diff --git a/processing/src/test/java/org/apache/druid/query/aggregation/cardinality/CardinalityVectorAggregatorTest.java b/processing/src/test/java/org/apache/druid/query/aggregation/cardinality/CardinalityVectorAggregatorTest.java index 68fd3f8f045e..91d05c676aa4 100644 --- a/processing/src/test/java/org/apache/druid/query/aggregation/cardinality/CardinalityVectorAggregatorTest.java +++ b/processing/src/test/java/org/apache/druid/query/aggregation/cardinality/CardinalityVectorAggregatorTest.java @@ -35,8 +35,8 @@ import org.apache.druid.segment.vector.NoFilterVectorOffset; import org.apache.druid.segment.vector.SingleValueDimensionVectorSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -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.nio.ByteBuffer; @@ -288,11 +288,11 @@ private static void testAggregateStyle1( aggregator.init(buf, position); aggregator.aggregate(buf, position, 0, numRows); - Assert.assertEquals( - "style1", + Assertions.assertEquals( expectedResult, ((HyperLogLogCollector) aggregator.get(buf, position)).estimateCardinality(), - 0.01 + 0.01, + "style1" ); } @@ -319,13 +319,13 @@ private static void testAggregateStyle2( aggregator.aggregate(buf, numRows, positions, rows, positionOffset); - Assert.assertEquals( - "style2", + Assertions.assertEquals( expectedResult, ((HyperLogLogCollector) aggregator.get(buf, positionOffset)) .fold((HyperLogLogCollector) aggregator.get(buf, positionOffset + aggregatorSize)) .estimateCardinality(), - 0.01 + 0.01, + "style2" ); } } diff --git a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/DoubleFirstVectorAggregatorTest.java b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/DoubleFirstVectorAggregatorTest.java index 734d7e3d6e8c..ed7753a6902d 100644 --- a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/DoubleFirstVectorAggregatorTest.java +++ b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/DoubleFirstVectorAggregatorTest.java @@ -38,9 +38,9 @@ import org.apache.druid.segment.vector.VectorObjectSelector; import org.apache.druid.segment.vector.VectorValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -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 javax.annotation.Nullable; import java.nio.ByteBuffer; @@ -75,7 +75,7 @@ public class DoubleFirstVectorAggregatorTest extends InitializedNullHandlingTest private VectorValueSelector longValueSelector; private VectorValueSelector doubleValueSelector; - @Before + @BeforeEach public void setup() { byte[] randomBytes = new byte[1024]; @@ -245,18 +245,18 @@ public ColumnCapabilities getColumnCapabilities(String column) @Test public void testFactory() { - Assert.assertTrue(doubleFirstAggregatorFactory.canVectorize(selectorFactory)); + Assertions.assertTrue(doubleFirstAggregatorFactory.canVectorize(selectorFactory)); VectorAggregator vectorAggregator = doubleFirstAggregatorFactory.factorizeVector(selectorFactory); - Assert.assertNotNull(vectorAggregator); - Assert.assertEquals(DoubleFirstVectorAggregator.class, vectorAggregator.getClass()); + Assertions.assertNotNull(vectorAggregator); + Assertions.assertEquals(DoubleFirstVectorAggregator.class, vectorAggregator.getClass()); } @Test public void testInit() { target.init(buf, 0); - Assert.assertEquals(DateTimes.MAX.getMillis(), buf.getLong(0)); - Assert.assertEquals(0, buf.getDouble(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); + Assertions.assertEquals(DateTimes.MAX.getMillis(), buf.getLong(0)); + Assertions.assertEquals(0, buf.getDouble(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); } @Test @@ -264,8 +264,8 @@ public void testAggregate() { target.aggregate(buf, 0, 0, pairs.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[0].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[0].rhs, result.rhs, EPSILON); } @Test @@ -273,8 +273,8 @@ public void testAggregateWithNulls() { target.aggregate(buf, 0, 0, pairs.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[0].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[0].rhs, result.rhs, EPSILON); } @Test @@ -286,8 +286,8 @@ public void testAggregateBatchWithoutRows() target.aggregate(buf, 3, positions, null, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[i].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[i].rhs, result.rhs, EPSILON); } } @@ -301,8 +301,8 @@ public void testAggregateBatchWithRows() target.aggregate(buf, 3, positions, rows, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(pairs[rows[i]].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[rows[i]].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); } } diff --git a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/FloatFirstVectorAggregatorTest.java b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/FloatFirstVectorAggregatorTest.java index 9d9a02860631..08c452c0eef6 100644 --- a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/FloatFirstVectorAggregatorTest.java +++ b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/FloatFirstVectorAggregatorTest.java @@ -37,9 +37,9 @@ import org.apache.druid.segment.vector.VectorObjectSelector; import org.apache.druid.segment.vector.VectorValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -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 javax.annotation.Nullable; import java.nio.ByteBuffer; @@ -67,8 +67,6 @@ public class FloatFirstVectorAggregatorTest extends InitializedNullHandlingTest private final SerializablePairLongFloat[] nullPairs = {null, null, null, null}; - - private VectorObjectSelector selector; private VectorObjectSelector selector1; private BaseLongVectorValueSelector timeSelector; @@ -80,7 +78,7 @@ public class FloatFirstVectorAggregatorTest extends InitializedNullHandlingTest private VectorColumnSelectorFactory selectorFactory; private VectorValueSelector nonFloatValueSelector; - @Before + @BeforeEach public void setup() { byte[] randomBytes = new byte[1024]; @@ -255,18 +253,18 @@ public ColumnCapabilities getColumnCapabilities(String column) @Test public void testFactory() { - Assert.assertTrue(floatFirstAggregatorFactory.canVectorize(selectorFactory)); + Assertions.assertTrue(floatFirstAggregatorFactory.canVectorize(selectorFactory)); VectorAggregator vectorAggregator = floatFirstAggregatorFactory.factorizeVector(selectorFactory); - Assert.assertNotNull(vectorAggregator); - Assert.assertEquals(FloatFirstVectorAggregator.class, vectorAggregator.getClass()); + Assertions.assertNotNull(vectorAggregator); + Assertions.assertEquals(FloatFirstVectorAggregator.class, vectorAggregator.getClass()); } @Test public void testInit() { target.init(buf, 0); - Assert.assertEquals(DateTimes.MAX.getMillis(), buf.getLong(0)); - Assert.assertEquals(0.0f, buf.getDouble(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); + Assertions.assertEquals(DateTimes.MAX.getMillis(), buf.getLong(0)); + Assertions.assertEquals(0.0f, buf.getDouble(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); } @Test @@ -275,8 +273,8 @@ public void testAggregate() target.init(buf, 0); target.aggregate(buf, 0, 0, VALUES.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[0].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[0].rhs, result.rhs, EPSILON); } @Test @@ -285,8 +283,8 @@ public void testAggregateNulls1() target1.init(buf, 0); target1.aggregate(buf, 0, 0, VALUES.length); Pair result = (Pair) target1.get(buf, 0); - Assert.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); - Assert.assertNull(result.rhs); + Assertions.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); + Assertions.assertNull(result.rhs); } @Test @@ -294,8 +292,8 @@ public void testAggregateWithNulls() { target.aggregate(buf, 0, 0, VALUES.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[0].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[0].rhs, result.rhs, EPSILON); } @Test @@ -307,11 +305,11 @@ public void testAggregateBatchWithoutRows() target.aggregate(buf, 3, positions, null, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); if (NULLS[i]) { - Assert.assertNull(result.rhs); + Assertions.assertNull(result.rhs); } else { - Assert.assertEquals(pairs[i].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[i].rhs, result.rhs, EPSILON); } } } @@ -326,11 +324,11 @@ public void testAggregateBatchWithRows() target.aggregate(buf, 3, positions, rows, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(times[rows[i]], result.lhs.longValue()); + Assertions.assertEquals(times[rows[i]], result.lhs.longValue()); if (NULLS[rows[i]]) { - Assert.assertNull(result.rhs); + Assertions.assertNull(result.rhs); } else { - Assert.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); } } } diff --git a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/LongFirstVectorAggregatorTest.java b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/LongFirstVectorAggregatorTest.java index b15a20a52dca..80bd4937e3c4 100644 --- a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/LongFirstVectorAggregatorTest.java +++ b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/first/LongFirstVectorAggregatorTest.java @@ -37,9 +37,9 @@ import org.apache.druid.segment.vector.VectorObjectSelector; import org.apache.druid.segment.vector.VectorValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -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 javax.annotation.Nullable; import java.nio.ByteBuffer; @@ -75,7 +75,7 @@ public class LongFirstVectorAggregatorTest extends InitializedNullHandlingTest private VectorColumnSelectorFactory selectorFactory; private VectorValueSelector nonLongValueSelector; - @Before + @BeforeEach public void setup() { byte[] randomBytes = new byte[1024]; @@ -228,18 +228,18 @@ public ColumnCapabilities getColumnCapabilities(String column) @Test public void testFactory() { - Assert.assertTrue(longFirstAggregatorFactory.canVectorize(selectorFactory)); + Assertions.assertTrue(longFirstAggregatorFactory.canVectorize(selectorFactory)); VectorAggregator vectorAggregator = longFirstAggregatorFactory.factorizeVector(selectorFactory); - Assert.assertNotNull(vectorAggregator); - Assert.assertEquals(LongFirstVectorAggregator.class, vectorAggregator.getClass()); + Assertions.assertNotNull(vectorAggregator); + Assertions.assertEquals(LongFirstVectorAggregator.class, vectorAggregator.getClass()); } @Test public void testInit() { target.init(buf, 0); - Assert.assertEquals(DateTimes.MAX.getMillis(), buf.getLong(0)); - Assert.assertEquals(0, buf.getLong(FirstLastVectorAggregator.VALUE_OFFSET)); + Assertions.assertEquals(DateTimes.MAX.getMillis(), buf.getLong(0)); + Assertions.assertEquals(0, buf.getLong(FirstLastVectorAggregator.VALUE_OFFSET)); } @Test @@ -247,8 +247,8 @@ public void testAggregate() { target.aggregate(buf, 0, 0, pairs.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[0].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[0].rhs, result.rhs, EPSILON); } @Test @@ -256,8 +256,8 @@ public void testAggregateWithNulls() { target.aggregate(buf, 0, 0, pairs.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[0].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[0].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[0].rhs, result.rhs, EPSILON); } @Test @@ -269,11 +269,11 @@ public void testAggregateBatchWithoutRows() target.aggregate(buf, 3, positions, null, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); if (NULLS[i]) { - Assert.assertNull(result.rhs); + Assertions.assertNull(result.rhs); } else { - Assert.assertEquals(pairs[i].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[i].rhs, result.rhs, EPSILON); } } } @@ -288,11 +288,11 @@ public void testAggregateBatchWithRows() target.aggregate(buf, 3, positions, rows, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(times[rows[i]], result.lhs.longValue()); + Assertions.assertEquals(times[rows[i]], result.lhs.longValue()); if (NULLS[rows[i]]) { - Assert.assertNull(result.rhs); + Assertions.assertNull(result.rhs); } else { - Assert.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); } } } diff --git a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/DoubleLastVectorAggregatorTest.java b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/DoubleLastVectorAggregatorTest.java index 16e1bdb43892..12045e6bc2e6 100644 --- a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/DoubleLastVectorAggregatorTest.java +++ b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/DoubleLastVectorAggregatorTest.java @@ -38,9 +38,9 @@ import org.apache.druid.segment.vector.VectorObjectSelector; import org.apache.druid.segment.vector.VectorValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -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 javax.annotation.Nullable; import java.nio.ByteBuffer; @@ -76,7 +76,7 @@ public class DoubleLastVectorAggregatorTest extends InitializedNullHandlingTest private VectorValueSelector longValueSelector; private VectorValueSelector doubleValueSelector; - @Before + @BeforeEach public void setup() { byte[] randomBytes = new byte[1024]; @@ -246,18 +246,18 @@ public ColumnCapabilities getColumnCapabilities(String column) @Test public void testFactory() { - Assert.assertTrue(doubleLastAggregatorFactory.canVectorize(selectorFactory)); + Assertions.assertTrue(doubleLastAggregatorFactory.canVectorize(selectorFactory)); VectorAggregator vectorAggregator = doubleLastAggregatorFactory.factorizeVector(selectorFactory); - Assert.assertNotNull(vectorAggregator); - Assert.assertEquals(DoubleLastVectorAggregator.class, vectorAggregator.getClass()); + Assertions.assertNotNull(vectorAggregator); + Assertions.assertEquals(DoubleLastVectorAggregator.class, vectorAggregator.getClass()); } @Test public void testInit() { target.init(buf, 0); - Assert.assertEquals(DateTimes.MIN.getMillis(), buf.getLong(0)); - Assert.assertEquals(0, buf.getDouble(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); + Assertions.assertEquals(DateTimes.MIN.getMillis(), buf.getLong(0)); + Assertions.assertEquals(0, buf.getDouble(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); } @Test @@ -265,8 +265,8 @@ public void testAggregate() { target.aggregate(buf, 0, 0, pairs.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[3].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[3].rhs, result.rhs, EPSILON); } @Test @@ -274,8 +274,8 @@ public void testAggregateWithNulls() { target.aggregate(buf, 0, 0, pairs.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[3].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[3].rhs, result.rhs, EPSILON); } @Test @@ -287,8 +287,8 @@ public void testAggregateBatchWithoutRows() target.aggregate(buf, 3, positions, null, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[i].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[i].rhs, result.rhs, EPSILON); } } @@ -302,8 +302,8 @@ public void testAggregateBatchWithRows() target.aggregate(buf, 3, positions, rows, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(pairs[rows[i]].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[rows[i]].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); } } diff --git a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/FloatLastVectorAggregatorTest.java b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/FloatLastVectorAggregatorTest.java index a4f0e4381aa9..0f6a89c7ba99 100644 --- a/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/FloatLastVectorAggregatorTest.java +++ b/processing/src/test/java/org/apache/druid/query/aggregation/firstlast/last/FloatLastVectorAggregatorTest.java @@ -38,9 +38,9 @@ import org.apache.druid.segment.vector.VectorObjectSelector; import org.apache.druid.segment.vector.VectorValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; -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 javax.annotation.Nullable; import java.nio.ByteBuffer; @@ -77,7 +77,7 @@ public class FloatLastVectorAggregatorTest extends InitializedNullHandlingTest private VectorColumnSelectorFactory selectorFactory; private VectorValueSelector nonFloatValueSelector; - @Before + @BeforeEach public void setup() { byte[] randomBytes = new byte[1024]; @@ -230,18 +230,18 @@ public ColumnCapabilities getColumnCapabilities(String column) @Test public void testFactory() { - Assert.assertTrue(floatLastAggregatorFactory.canVectorize(selectorFactory)); + Assertions.assertTrue(floatLastAggregatorFactory.canVectorize(selectorFactory)); VectorAggregator vectorAggregator = floatLastAggregatorFactory.factorizeVector(selectorFactory); - Assert.assertNotNull(vectorAggregator); - Assert.assertEquals(FloatLastVectorAggregator.class, vectorAggregator.getClass()); + Assertions.assertNotNull(vectorAggregator); + Assertions.assertEquals(FloatLastVectorAggregator.class, vectorAggregator.getClass()); } @Test public void testInit() { target.init(buf, 0); - Assert.assertEquals(DateTimes.MIN.getMillis(), buf.getLong(0)); - Assert.assertEquals(0.0f, buf.getFloat(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); + Assertions.assertEquals(DateTimes.MIN.getMillis(), buf.getLong(0)); + Assertions.assertEquals(0.0f, buf.getFloat(FirstLastVectorAggregator.VALUE_OFFSET), EPSILON); } @Test @@ -250,8 +250,8 @@ public void testAggregate() target.init(buf, 0); target.aggregate(buf, 0, 0, VALUES.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[3].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[3].rhs, result.rhs, EPSILON); } @Test @@ -259,8 +259,8 @@ public void testAggregateWithNulls() { target.aggregate(buf, 0, 0, VALUES.length); Pair result = (Pair) target.get(buf, 0); - Assert.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); - Assert.assertEquals(pairs[3].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[3].lhs.longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[3].rhs, result.rhs, EPSILON); } @Test @@ -272,11 +272,11 @@ public void testAggregateBatchWithoutRows() target.aggregate(buf, 3, positions, null, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); + Assertions.assertEquals(pairs[i].getLhs().longValue(), result.lhs.longValue()); if (NULLS[i]) { - Assert.assertNull(result.rhs); + Assertions.assertNull(result.rhs); } else { - Assert.assertEquals(pairs[i].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[i].rhs, result.rhs, EPSILON); } } } @@ -291,11 +291,11 @@ public void testAggregateBatchWithRows() target.aggregate(buf, 3, positions, rows, positionOffset); for (int i = 0; i < positions.length; i++) { Pair result = (Pair) target.get(buf, positions[i] + positionOffset); - Assert.assertEquals(times[rows[i]], result.lhs.longValue()); + Assertions.assertEquals(times[rows[i]], result.lhs.longValue()); if (NULLS[rows[i]]) { - Assert.assertNull(result.rhs); + Assertions.assertNull(result.rhs); } else { - Assert.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); + Assertions.assertEquals(pairs[rows[i]].rhs, result.rhs, EPSILON); } } } diff --git a/processing/src/test/java/org/apache/druid/query/cache/CacheKeyBuilderTest.java b/processing/src/test/java/org/apache/druid/query/cache/CacheKeyBuilderTest.java index 1f29e8a7e8fc..893932eb8ca0 100644 --- a/processing/src/test/java/org/apache/druid/query/cache/CacheKeyBuilderTest.java +++ b/processing/src/test/java/org/apache/druid/query/cache/CacheKeyBuilderTest.java @@ -23,8 +23,8 @@ import com.google.common.collect.Lists; import org.apache.druid.java.util.common.Cacheable; import org.apache.druid.java.util.common.StringUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -67,7 +67,7 @@ public void testCacheKeyBuilder() + cacheable.getCacheKey().length // cacheable + Integer.BYTES + 4 // cacheable list + 12; // type keys - Assert.assertEquals(expectedSize, actual.length); + Assertions.assertEquals(expectedSize, actual.length); final byte[] expected = ByteBuffer.allocate(expectedSize) .put((byte) 10) @@ -102,7 +102,7 @@ public void testCacheKeyBuilder() .put(cacheable.getCacheKey()) .array(); - Assert.assertArrayEquals(expected, actual); + Assertions.assertArrayEquals(expected, actual); } @Test @@ -116,7 +116,7 @@ public void testDifferentOrderList() .appendStringsIgnoringOrder(Lists.newArrayList("BA", "AB")) .build(); - Assert.assertArrayEquals(key1, key2); + Assertions.assertArrayEquals(key1, key2); final Cacheable cacheable1 = () -> new byte[]{1}; @@ -130,7 +130,7 @@ public void testDifferentOrderList() .appendCacheablesIgnoringOrder(Lists.newArrayList(cacheable2, cacheable1)) .build(); - Assert.assertArrayEquals(key1, key2); + Assertions.assertArrayEquals(key1, key2); } @Test @@ -253,7 +253,7 @@ private static void assertNotEqualsEachOther(List keys) { for (int i = 0; i < keys.size(); i++) { for (int j = i + 1; j < keys.size(); j++) { - Assert.assertFalse(Arrays.equals(keys.get(i), keys.get(j))); + Assertions.assertFalse(Arrays.equals(keys.get(i), keys.get(j))); } } } @@ -269,7 +269,7 @@ public void testEmptyOrNullStringLists() .appendStrings(Collections.singletonList("")) .build(); - Assert.assertFalse(Arrays.equals(key1, key2)); + Assertions.assertFalse(Arrays.equals(key1, key2)); key1 = new CacheKeyBuilder((byte) 10) .appendStrings(Collections.singletonList("")) @@ -279,7 +279,7 @@ public void testEmptyOrNullStringLists() .appendStrings(Collections.singletonList(null)) .build(); - Assert.assertArrayEquals(key1, key2); + Assertions.assertArrayEquals(key1, key2); } @Test @@ -293,7 +293,7 @@ public void testEmptyOrNullCacheables() .appendCacheables(Collections.singletonList(null)) .build(); - Assert.assertFalse(Arrays.equals(key1, key2)); + Assertions.assertFalse(Arrays.equals(key1, key2)); } @Test @@ -314,7 +314,7 @@ public void testIgnoringOrder() .put(StringUtils.toUtf8("test2")) .array(); - Assert.assertArrayEquals(expected, actual); + Assertions.assertArrayEquals(expected, actual); final Cacheable c1 = () -> StringUtils.toUtf8("te"); @@ -335,6 +335,6 @@ public void testIgnoringOrder() .put(c3.getCacheKey()) .array(); - Assert.assertArrayEquals(expected, actual); + Assertions.assertArrayEquals(expected, actual); } } diff --git a/processing/src/test/java/org/apache/druid/query/extraction/FunctionalExtractionTest.java b/processing/src/test/java/org/apache/druid/query/extraction/FunctionalExtractionTest.java index 6cda6d76edc6..8c18ab83e04d 100644 --- a/processing/src/test/java/org/apache/druid/query/extraction/FunctionalExtractionTest.java +++ b/processing/src/test/java/org/apache/druid/query/extraction/FunctionalExtractionTest.java @@ -22,14 +22,17 @@ import com.google.common.base.Function; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; -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.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import javax.annotation.Nullable; +import java.util.stream.Stream; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") public class FunctionalExtractionTest { private static class SimpleFunctionExtraction extends FunctionalExtraction @@ -104,9 +107,7 @@ public String apply(@Nullable String input) private static String PRESENT_VALUE = "present_value"; private static String MISSING = "missing"; - - @Parameterized.Parameters(name = "{0}") - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { return ImmutableList.of( new Object[]{"null", NULL_FN}, @@ -114,15 +115,13 @@ public static Iterable constructorFeeder() new Object[]{"empty", EMPTY_STR_FN}, new Object[]{"identity", IDENTITY_FN}, new Object[]{"only_PRESENT", ONLY_PRESENT} - ); + ).stream(); } - private final Function fn; - - public FunctionalExtractionTest(String label, Function fn) - { - this.fn = fn; - } + @Parameter(0) + public String label; + @Parameter(1) + public Function fn; @Test public void testRetainMissing() @@ -135,7 +134,7 @@ public void testRetainMissing() false ); final String out = fn.apply(in); - Assert.assertEquals(out == null ? in : out, exFn.apply(in)); + Assertions.assertEquals(out == null ? in : out, exFn.apply(in)); } @Test @@ -149,7 +148,7 @@ public void testRetainMissingButFound() false ); final String out = fn.apply(in); - Assert.assertEquals(out == null ? in : out, exFn.apply(in)); + Assertions.assertEquals(out == null ? in : out, exFn.apply(in)); } @Test @@ -163,7 +162,7 @@ public void testReplaceMissing() false ); final String out = fn.apply(in); - Assert.assertEquals(out == null ? MISSING : out, exFn.apply(in)); + Assertions.assertEquals(out == null ? MISSING : out, exFn.apply(in)); } @@ -178,7 +177,7 @@ public void testReplaceMissingBlank() false ); final String out = fn.apply(in); - Assert.assertEquals(out == null ? "" : out, exFn.apply(in)); + Assertions.assertEquals(out == null ? "" : out, exFn.apply(in)); } @Test @@ -192,7 +191,7 @@ public void testOnlyOneValuePresent() false ); final String out = fn.apply(in); - Assert.assertEquals(Strings.isNullOrEmpty(out) ? "" : out, exFn.apply(in)); + Assertions.assertEquals(Strings.isNullOrEmpty(out) ? "" : out, exFn.apply(in)); } @Test @@ -205,26 +204,22 @@ public void testNullInputs() false ); if (fn.apply(null) == null) { - Assert.assertEquals(null, exFn.apply(null)); + Assertions.assertEquals(null, exFn.apply(null)); } } - @Test(expected = IllegalArgumentException.class) + @Test public void testBadConfig() { - @SuppressWarnings("unused") // expected exception - final FunctionalExtraction exFn = new SimpleFunctionExtraction( - fn, - true, - MISSING, - false + Assertions.assertThrows(IllegalArgumentException.class, () -> + new SimpleFunctionExtraction(fn, true, MISSING, false) ); } @Test public void testUniqueProjections() { - Assert.assertEquals( + Assertions.assertEquals( ExtractionFn.ExtractionType.MANY_TO_ONE, new SimpleFunctionExtraction( fn, @@ -233,7 +228,7 @@ public void testUniqueProjections() false ).getExtractionType() ); - Assert.assertEquals( + Assertions.assertEquals( ExtractionFn.ExtractionType.MANY_TO_ONE, new SimpleFunctionExtraction( fn, @@ -242,7 +237,7 @@ public void testUniqueProjections() false ).getExtractionType() ); - Assert.assertEquals( + Assertions.assertEquals( ExtractionFn.ExtractionType.ONE_TO_ONE, new SimpleFunctionExtraction( fn, diff --git a/processing/src/test/java/org/apache/druid/query/filter/vector/VectorValueMatcherColumnProcessorFactoryTest.java b/processing/src/test/java/org/apache/druid/query/filter/vector/VectorValueMatcherColumnProcessorFactoryTest.java index 186276e62068..e5b3cfe46244 100644 --- a/processing/src/test/java/org/apache/druid/query/filter/vector/VectorValueMatcherColumnProcessorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/query/filter/vector/VectorValueMatcherColumnProcessorFactoryTest.java @@ -27,9 +27,9 @@ import org.apache.druid.segment.vector.VectorValueSelector; import org.apache.druid.testing.InitializedNullHandlingTest; import org.easymock.EasyMock; -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; public class VectorValueMatcherColumnProcessorFactoryTest extends InitializedNullHandlingTest { @@ -37,7 +37,7 @@ public class VectorValueMatcherColumnProcessorFactoryTest extends InitializedNul private static final int CURRENT_SIZE = 24; private VectorValueSelector vectorValueSelector; - @Before + @BeforeEach public void setup() { vectorValueSelector = EasyMock.createMock(VectorValueSelector.class); @@ -55,17 +55,17 @@ public void testFloat() vectorValueSelector ); - Assert.assertTrue(matcherFactory instanceof FloatVectorValueMatcher); + Assertions.assertInstanceOf(FloatVectorValueMatcher.class, matcherFactory); VectorValueMatcher matcher = matcherFactory.makeMatcher("2.0"); - Assert.assertFalse(matcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); + Assertions.assertFalse(matcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); VectorValueMatcher booleanMatcher = matcherFactory.makeMatcher((String) null); - Assert.assertFalse(booleanMatcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); + Assertions.assertFalse(booleanMatcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); EasyMock.verify(vectorValueSelector); } @@ -78,19 +78,19 @@ public void testDouble() vectorValueSelector ); - Assert.assertTrue(matcherFactory instanceof DoubleVectorValueMatcher); + Assertions.assertInstanceOf(DoubleVectorValueMatcher.class, matcherFactory); VectorValueMatcher matcher = matcherFactory.makeMatcher("1.0"); - Assert.assertFalse(matcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); + Assertions.assertFalse(matcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); VectorValueMatcher booleanMatcher = matcherFactory.makeMatcher((String) null); - Assert.assertFalse(booleanMatcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); + Assertions.assertFalse(booleanMatcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); EasyMock.verify(vectorValueSelector); } @@ -103,17 +103,17 @@ public void testLong() vectorValueSelector ); - Assert.assertTrue(matcherFactory instanceof LongVectorValueMatcher); + Assertions.assertInstanceOf(LongVectorValueMatcher.class, matcherFactory); VectorValueMatcher matcher = matcherFactory.makeMatcher("1"); - Assert.assertFalse(matcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); + Assertions.assertFalse(matcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); VectorValueMatcher booleanMatcher = matcherFactory.makeMatcher((String) null); - Assert.assertFalse(booleanMatcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); + Assertions.assertFalse(booleanMatcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); EasyMock.verify(vectorValueSelector); } @@ -144,17 +144,17 @@ public void testSingleValueString() selector ); - Assert.assertTrue(matcherFactory instanceof SingleValueStringVectorValueMatcher); + Assertions.assertInstanceOf(SingleValueStringVectorValueMatcher.class, matcherFactory); // value exists in column nonboolean matcher VectorValueMatcher matcher = matcherFactory.makeMatcher("any value"); - Assert.assertFalse(matcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); + Assertions.assertFalse(matcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); VectorValueMatcher booleanMatcher = matcherFactory.makeMatcher("another value"); - Assert.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); + Assertions.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); EasyMock.verify(selector, lookup); } @@ -184,18 +184,18 @@ public void testSingleValueStringZeroCardinalityAlwaysBooleanMatcher() selector ); - Assert.assertTrue(matcherFactory instanceof SingleValueStringVectorValueMatcher); + Assertions.assertInstanceOf(SingleValueStringVectorValueMatcher.class, matcherFactory); VectorValueMatcher matcher = matcherFactory.makeMatcher("any value"); - Assert.assertTrue(matcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); + Assertions.assertInstanceOf(BooleanVectorValueMatcher.class, matcher); + Assertions.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); // all are boolean with no valued column i guess VectorValueMatcher anotherMatcher = matcherFactory.makeMatcher((String) null); - Assert.assertTrue(anotherMatcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, anotherMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, anotherMatcher.getCurrentVectorSize()); + Assertions.assertInstanceOf(BooleanVectorValueMatcher.class, anotherMatcher); + Assertions.assertEquals(VECTOR_SIZE, anotherMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, anotherMatcher.getCurrentVectorSize()); EasyMock.verify(selector, lookup); } @@ -224,19 +224,19 @@ public void testSingleValueStringOneCardinalityBooleanMatcherIfNullAndNameLookup selector ); - Assert.assertTrue(matcherFactory instanceof SingleValueStringVectorValueMatcher); + Assertions.assertInstanceOf(SingleValueStringVectorValueMatcher.class, matcherFactory); // false matcher VectorValueMatcher booleanMatcher = matcherFactory.makeMatcher("any value"); - Assert.assertTrue(booleanMatcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); + Assertions.assertInstanceOf(BooleanVectorValueMatcher.class, booleanMatcher); + Assertions.assertEquals(VECTOR_SIZE, booleanMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, booleanMatcher.getCurrentVectorSize()); // true matcher VectorValueMatcher anotherBooleanMatcher = matcherFactory.makeMatcher((String) null); - Assert.assertTrue(anotherBooleanMatcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, anotherBooleanMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, anotherBooleanMatcher.getCurrentVectorSize()); + Assertions.assertInstanceOf(BooleanVectorValueMatcher.class, anotherBooleanMatcher); + Assertions.assertEquals(VECTOR_SIZE, anotherBooleanMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, anotherBooleanMatcher.getCurrentVectorSize()); EasyMock.verify(selector); } @@ -268,12 +268,12 @@ public void testSingleValueStringOneCardinalityBooleanMatcherIfNullAndNameLookup selector ); - Assert.assertTrue(matcherFactory instanceof SingleValueStringVectorValueMatcher); + Assertions.assertInstanceOf(SingleValueStringVectorValueMatcher.class, matcherFactory); VectorValueMatcher matcher = matcherFactory.makeMatcher("any value"); - Assert.assertFalse(matcher instanceof BooleanVectorValueMatcher); - Assert.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); + Assertions.assertFalse(matcher instanceof BooleanVectorValueMatcher); + Assertions.assertEquals(VECTOR_SIZE, matcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, matcher.getCurrentVectorSize()); EasyMock.verify(selector, lookup); } @@ -302,15 +302,15 @@ public void testMultiValueString() selector ); - Assert.assertTrue(matcherFactory instanceof MultiValueStringVectorValueMatcher); + Assertions.assertInstanceOf(MultiValueStringVectorValueMatcher.class, matcherFactory); VectorValueMatcher valueNotExistMatcher = matcherFactory.makeMatcher("any value"); - Assert.assertEquals(VECTOR_SIZE, valueNotExistMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, valueNotExistMatcher.getCurrentVectorSize()); + Assertions.assertEquals(VECTOR_SIZE, valueNotExistMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, valueNotExistMatcher.getCurrentVectorSize()); VectorValueMatcher valueExistMatcher = matcherFactory.makeMatcher((String) null); - Assert.assertEquals(VECTOR_SIZE, valueExistMatcher.getMaxVectorSize()); - Assert.assertEquals(CURRENT_SIZE, valueExistMatcher.getCurrentVectorSize()); + Assertions.assertEquals(VECTOR_SIZE, valueExistMatcher.getMaxVectorSize()); + Assertions.assertEquals(CURRENT_SIZE, valueExistMatcher.getCurrentVectorSize()); EasyMock.verify(selector, lookup); } } diff --git a/processing/src/test/java/org/apache/druid/query/groupby/GroupByQueryTest.java b/processing/src/test/java/org/apache/druid/query/groupby/GroupByQueryTest.java index da07a772a78e..82d61d5c3739 100644 --- a/processing/src/test/java/org/apache/druid/query/groupby/GroupByQueryTest.java +++ b/processing/src/test/java/org/apache/druid/query/groupby/GroupByQueryTest.java @@ -47,8 +47,8 @@ import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.virtual.ExpressionVirtualColumn; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Collections; @@ -90,7 +90,7 @@ public void testQuerySerialization() throws IOException String json = JSON_MAPPER.writeValueAsString(query); Query serdeQuery = JSON_MAPPER.readValue(json, Query.class); - Assert.assertEquals(query, serdeQuery); + Assertions.assertEquals(query, serdeQuery); } @Test @@ -117,7 +117,7 @@ public void testGetRequiredColumns() ) .build(); - Assert.assertEquals(ImmutableSet.of("__time", "quality", "other", "index"), query.getRequiredColumns()); + Assertions.assertEquals(ImmutableSet.of("__time", "quality", "other", "index"), query.getRequiredColumns()); } @Test @@ -138,7 +138,7 @@ public void testRowOrderingMixTypes() ResultRow.of(1, 1f, "a", new Object[]{"1", "2"}), ResultRow.of(1L, 1d, "b", new Object[]{"3"}) ); - Assert.assertEquals(-1, compare); + Assertions.assertEquals(-1, compare); } @Test @@ -163,7 +163,7 @@ public void testSegmentLookUpForNestedQueries() .setGranularity(Granularities.DAY) .build(); ExecutionVertex ev = ExecutionVertex.of(query); - Assert.assertEquals(innerQuerySegmentSpec, ev.getEffectiveQuerySegmentSpec()); + Assertions.assertEquals(innerQuerySegmentSpec, ev.getEffectiveQuerySegmentSpec()); } @Test @@ -203,11 +203,11 @@ public void testAsCursorBuildSpecAllGranularity() .build(); final CursorBuildSpec buildSpec = GroupingEngine.makeCursorBuildSpec(query, null); - Assert.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); - Assert.assertEquals(ImmutableList.of("quality", "market", "v0"), buildSpec.getGroupingColumns()); - Assert.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); - Assert.assertEquals(virtualColumns, buildSpec.getVirtualColumns()); - Assert.assertEquals(List.of(), buildSpec.getPreferredOrdering()); + Assertions.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); + Assertions.assertEquals(ImmutableList.of("quality", "market", "v0"), buildSpec.getGroupingColumns()); + Assertions.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); + Assertions.assertEquals(virtualColumns, buildSpec.getVirtualColumns()); + Assertions.assertEquals(List.of(), buildSpec.getPreferredOrdering()); } @Test @@ -247,20 +247,20 @@ public void testAsCursorBuildSpecDayGranularity() .build(); final CursorBuildSpec buildSpec = GroupingEngine.makeCursorBuildSpec(query, null); - Assert.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); - Assert.assertEquals( + Assertions.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); + Assertions.assertEquals( ImmutableList.of(Granularities.GRANULARITY_VIRTUAL_COLUMN_NAME, "quality", "market", "v0"), buildSpec.getGroupingColumns() ); - Assert.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); - Assert.assertEquals( + Assertions.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); + Assertions.assertEquals( VirtualColumns.create( Granularities.toVirtualColumn(query.getGranularity(), Granularities.GRANULARITY_VIRTUAL_COLUMN_NAME), virtualColumns.getVirtualColumns()[0] ), buildSpec.getVirtualColumns() ); - Assert.assertEquals(Cursors.ascendingTimeOrder(), buildSpec.getPreferredOrdering()); + Assertions.assertEquals(Cursors.ascendingTimeOrder(), buildSpec.getPreferredOrdering()); } @Test @@ -301,20 +301,20 @@ public void testAsCursorBuildSpecDayGranularityNameConflict() .build(); final CursorBuildSpec buildSpec = GroupingEngine.makeCursorBuildSpec(query, null); - Assert.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); - Assert.assertEquals( + Assertions.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); + Assertions.assertEquals( ImmutableList.of(Granularities.GRANULARITY_VIRTUAL_COLUMN_NAME + "0", "quality", "market", "v0"), buildSpec.getGroupingColumns() ); - Assert.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); - Assert.assertEquals( + Assertions.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); + Assertions.assertEquals( VirtualColumns.create( Granularities.toVirtualColumn(query.getGranularity(), Granularities.GRANULARITY_VIRTUAL_COLUMN_NAME + "0"), virtualColumns.getVirtualColumns()[0] ), buildSpec.getVirtualColumns() ); - Assert.assertEquals(Cursors.ascendingTimeOrder(), buildSpec.getPreferredOrdering()); + Assertions.assertEquals(Cursors.ascendingTimeOrder(), buildSpec.getPreferredOrdering()); } @Test diff --git a/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java b/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java index 66a19b0a8a08..998021104423 100644 --- a/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java +++ b/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java @@ -20,27 +20,27 @@ package org.apache.druid.query.groupby.epinephelinae; import org.apache.druid.query.groupby.GroupByStatsProvider; -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.io.TempDir; +import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; public class SpillOutputStreamTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder; @Test public void testSmallWriteStaysInMemory() throws IOException { try (SpillOutputStream out = makeStream(1024)) { out.write(new byte[]{1, 2, 3}); - Assert.assertTrue(out.isInMemory()); - Assert.assertArrayEquals(new byte[]{1, 2, 3}, out.toByteArray()); + Assertions.assertTrue(out.isInMemory()); + Assertions.assertArrayEquals(new byte[]{1, 2, 3}, out.toByteArray()); } } @@ -49,8 +49,8 @@ public void testExactlyAtThresholdStaysInMemory() throws IOException { try (SpillOutputStream out = makeStream(4)) { out.write(new byte[]{1, 2, 3, 4}); - Assert.assertTrue(out.isInMemory()); - Assert.assertArrayEquals(new byte[]{1, 2, 3, 4}, out.toByteArray()); + Assertions.assertTrue(out.isInMemory()); + Assertions.assertArrayEquals(new byte[]{1, 2, 3, 4}, out.toByteArray()); } } @@ -59,10 +59,10 @@ public void testExceedingThresholdSwitchesToDisk() throws IOException { try (SpillOutputStream out = makeStream(4)) { out.write(new byte[]{1, 2, 3, 4, 5}); - Assert.assertFalse(out.isInMemory()); - Assert.assertTrue(out.getFile().exists()); + Assertions.assertFalse(out.isInMemory()); + Assertions.assertTrue(out.getFile().exists()); byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, fileContent); + Assertions.assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, fileContent); } } @@ -71,12 +71,12 @@ public void testSwitchesToDiskOnSecondWrite() throws IOException { try (SpillOutputStream out = makeStream(4)) { out.write(new byte[]{1, 2}); - Assert.assertTrue(out.isInMemory()); + Assertions.assertTrue(out.isInMemory()); out.write(new byte[]{3, 4, 5}); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, fileContent); + Assertions.assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, fileContent); } } @@ -85,8 +85,8 @@ public void testSingleByteWriteStaysInMemory() throws IOException { try (SpillOutputStream out = makeStream(1024)) { out.write(42); - Assert.assertTrue(out.isInMemory()); - Assert.assertArrayEquals(new byte[]{42}, out.toByteArray()); + Assertions.assertTrue(out.isInMemory()); + Assertions.assertArrayEquals(new byte[]{42}, out.toByteArray()); } } @@ -96,12 +96,12 @@ public void testSingleByteWriteTriggersSwitch() throws IOException try (SpillOutputStream out = makeStream(2)) { out.write(1); out.write(2); - Assert.assertTrue(out.isInMemory()); + Assertions.assertTrue(out.isInMemory()); out.write(3); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(new byte[]{1, 2, 3}, fileContent); + Assertions.assertArrayEquals(new byte[]{1, 2, 3}, fileContent); } } @@ -112,15 +112,15 @@ public void testDataIntegrityAcrossSwitch() throws IOException byte[] beforeSwitch = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; byte[] afterSwitch = new byte[]{11, 12, 13, 14, 15}; out.write(beforeSwitch); - Assert.assertTrue(out.isInMemory()); + Assertions.assertTrue(out.isInMemory()); out.write(afterSwitch); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); out.flush(); byte[] expected = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(expected, fileContent); + Assertions.assertArrayEquals(expected, fileContent); } } @@ -130,8 +130,8 @@ public void testWriteWithOffsetAndLength() throws IOException try (SpillOutputStream out = makeStream(1024)) { byte[] data = new byte[]{0, 0, 1, 2, 3, 0, 0}; out.write(data, 2, 3); - Assert.assertTrue(out.isInMemory()); - Assert.assertArrayEquals(new byte[]{1, 2, 3}, out.toByteArray()); + Assertions.assertTrue(out.isInMemory()); + Assertions.assertArrayEquals(new byte[]{1, 2, 3}, out.toByteArray()); } } @@ -141,9 +141,9 @@ public void testWriteWithOffsetAndLengthTriggersDiskSwitch() throws IOException try (SpillOutputStream out = makeStream(2)) { byte[] data = new byte[]{0, 1, 2, 3, 0}; out.write(data, 1, 3); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(new byte[]{1, 2, 3}, fileContent); + Assertions.assertArrayEquals(new byte[]{1, 2, 3}, fileContent); } } @@ -154,10 +154,10 @@ public void testLargeWrite() throws IOException byte[] data = new byte[10_000]; Arrays.fill(data, (byte) 0xAB); out.write(data); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); out.flush(); byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(data, fileContent); + Assertions.assertArrayEquals(data, fileContent); } } @@ -166,9 +166,9 @@ public void testZeroThresholdAlwaysGoesToDisk() throws IOException { try (SpillOutputStream out = makeStream(0)) { out.write(new byte[]{1}); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(new byte[]{1}, fileContent); + Assertions.assertArrayEquals(new byte[]{1}, fileContent); } } @@ -176,8 +176,8 @@ public void testZeroThresholdAlwaysGoesToDisk() throws IOException public void testEmptyStreamIsInMemory() throws IOException { try (SpillOutputStream out = makeStream(1024)) { - Assert.assertTrue(out.isInMemory()); - Assert.assertArrayEquals(new byte[0], out.toByteArray()); + Assertions.assertTrue(out.isInMemory()); + Assertions.assertArrayEquals(new byte[0], out.toByteArray()); } } @@ -188,8 +188,8 @@ public void testMultipleWritesAccumulateInMemory() throws IOException out.write(new byte[]{1, 2}); out.write(new byte[]{3, 4}); out.write(5); - Assert.assertTrue(out.isInMemory()); - Assert.assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, out.toByteArray()); + Assertions.assertTrue(out.isInMemory()); + Assertions.assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, out.toByteArray()); } } @@ -198,14 +198,14 @@ public void testMultipleWritesAfterDiskSwitch() throws IOException { try (SpillOutputStream out = makeStream(4)) { out.write(new byte[]{1, 2, 3, 4, 5}); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); out.write(new byte[]{6, 7}); out.write(8); out.flush(); byte[] fileContent = Files.readAllBytes(out.getFile().toPath()); - Assert.assertArrayEquals(new byte[]{1, 2, 3, 4, 5, 6, 7, 8}, fileContent); + Assertions.assertArrayEquals(new byte[]{1, 2, 3, 4, 5, 6, 7, 8}, fileContent); } } @@ -216,42 +216,43 @@ public void testDiskStorageBytesTracked() throws IOException try (SpillOutputStream out = new SpillOutputStream(storage, 4)) { out.write(new byte[]{1, 2, 3, 4, 5}); - Assert.assertFalse(out.isInMemory()); + Assertions.assertFalse(out.isInMemory()); out.flush(); - Assert.assertTrue(storage.currentSize() > 0); + Assertions.assertTrue(storage.currentSize() > 0); } } - @Test(expected = NullPointerException.class) + @Test public void testToByteArrayThrowsAfterDiskSwitch() throws IOException { try (SpillOutputStream out = makeStream(4)) { out.write(new byte[]{1, 2, 3, 4, 5}); - Assert.assertFalse(out.isInMemory()); - out.toByteArray(); + Assertions.assertFalse(out.isInMemory()); + Assertions.assertThrows(NullPointerException.class, out::toByteArray); } } - @Test(expected = NullPointerException.class) + @Test public void testGetFileThrowsWhenInMemory() throws IOException { try (SpillOutputStream out = makeStream(1024)) { out.write(new byte[]{1, 2, 3}); - Assert.assertTrue(out.isInMemory()); - out.getFile(); + Assertions.assertTrue(out.isInMemory()); + Assertions.assertThrows(NullPointerException.class, out::getFile); } } - @Test(expected = TemporaryStorageFullException.class) + @Test public void testDiskStorageLimitEnforced() throws IOException { LimitedTemporaryStorage storage = makeStorage(10); - - try (SpillOutputStream out = new SpillOutputStream(storage, 4)) { - byte[] data = new byte[100]; - Arrays.fill(data, (byte) 1); - out.write(data); - } + Assertions.assertThrows(TemporaryStorageFullException.class, () -> { + try (SpillOutputStream out = new SpillOutputStream(storage, 4)) { + byte[] data = new byte[100]; + Arrays.fill(data, (byte) 1); + out.write(data); + } + }); } private SpillOutputStream makeStream(long threshold) throws IOException @@ -262,7 +263,7 @@ private SpillOutputStream makeStream(long threshold) throws IOException private LimitedTemporaryStorage makeStorage(long maxBytes) throws IOException { return new LimitedTemporaryStorage( - temporaryFolder.newFolder(), + temporaryFolder, maxBytes, 100, new GroupByStatsProvider.PerQueryStats() diff --git a/processing/src/test/java/org/apache/druid/query/metadata/metadata/ColumnAnalysisTest.java b/processing/src/test/java/org/apache/druid/query/metadata/metadata/ColumnAnalysisTest.java index a62b509228fb..a3e6d429a20e 100644 --- a/processing/src/test/java/org/apache/druid/query/metadata/metadata/ColumnAnalysisTest.java +++ b/processing/src/test/java/org/apache/druid/query/metadata/metadata/ColumnAnalysisTest.java @@ -23,8 +23,8 @@ import org.apache.druid.segment.TestHelper; import org.apache.druid.segment.column.ColumnType; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ColumnAnalysisTest extends InitializedNullHandlingTest { @@ -32,7 +32,7 @@ public class ColumnAnalysisTest extends InitializedNullHandlingTest private void assertSerDe(ColumnAnalysis analysis) throws Exception { - Assert.assertEquals(analysis, MAPPER.readValue(MAPPER.writeValueAsString(analysis), ColumnAnalysis.class)); + Assertions.assertEquals(analysis, MAPPER.readValue(MAPPER.writeValueAsString(analysis), ColumnAnalysis.class)); } @Test @@ -78,8 +78,8 @@ public void testFoldStringColumns() throws Exception ColumnAnalysis fold1 = analysis1.fold(analysis2); ColumnAnalysis fold2 = analysis2.fold(analysis1); - Assert.assertEquals(expected, fold1); - Assert.assertEquals(expected, fold2); + Assertions.assertEquals(expected, fold1); + Assertions.assertEquals(expected, fold2); assertSerDe(fold1); assertSerDe(fold2); @@ -99,7 +99,7 @@ public void testFoldWithNull() throws Exception null, null ); - Assert.assertEquals(analysis1, analysis1.fold(null)); + Assertions.assertEquals(analysis1, analysis1.fold(null)); assertSerDe(analysis1); } @@ -146,8 +146,8 @@ public void testFoldComplexColumns() throws Exception ColumnAnalysis fold1 = analysis1.fold(analysis2); ColumnAnalysis fold2 = analysis2.fold(analysis1); - Assert.assertEquals(expected, fold1); - Assert.assertEquals(expected, fold2); + Assertions.assertEquals(expected, fold1); + Assertions.assertEquals(expected, fold2); assertSerDe(fold1); assertSerDe(fold2); @@ -186,8 +186,8 @@ public void testFoldDifferentTypes() throws Exception final ColumnAnalysis expected2 = ColumnAnalysis.error("cannot_merge_diff_types: [COMPLEX] and [hyperUnique]"); ColumnAnalysis fold1 = analysis1.fold(analysis2); ColumnAnalysis fold2 = analysis2.fold(analysis1); - Assert.assertEquals(expected, fold1); - Assert.assertEquals(expected2, fold2); + Assertions.assertEquals(expected, fold1); + Assertions.assertEquals(expected2, fold2); assertSerDe(fold1); assertSerDe(fold2); @@ -231,8 +231,8 @@ public void testFoldDifferentTypeSignatures() throws Exception ); ColumnAnalysis fold1 = analysis1.fold(analysis2); ColumnAnalysis fold2 = analysis2.fold(analysis1); - Assert.assertEquals(expected, fold1); - Assert.assertEquals(expected2, fold2); + Assertions.assertEquals(expected, fold1); + Assertions.assertEquals(expected2, fold2); assertSerDe(fold1); assertSerDe(fold2); @@ -260,8 +260,8 @@ public void testFoldSameErrors() throws Exception ); ColumnAnalysis fold1 = analysis1.fold(analysis2); ColumnAnalysis fold2 = analysis2.fold(analysis1); - Assert.assertEquals(expected, fold1); - Assert.assertEquals(expected, fold2); + Assertions.assertEquals(expected, fold1); + Assertions.assertEquals(expected, fold2); assertSerDe(fold1); assertSerDe(fold2); @@ -299,8 +299,8 @@ public void testFoldErrorAndNoError() throws Exception ); ColumnAnalysis fold1 = analysis1.fold(analysis2); ColumnAnalysis fold2 = analysis2.fold(analysis1); - Assert.assertEquals(expected, fold1); - Assert.assertEquals(expected, fold2); + Assertions.assertEquals(expected, fold1); + Assertions.assertEquals(expected, fold2); assertSerDe(fold1); assertSerDe(fold2); @@ -328,8 +328,8 @@ public void testFoldDifferentErrors() throws Exception ); ColumnAnalysis fold1 = analysis1.fold(analysis2); ColumnAnalysis fold2 = analysis2.fold(analysis1); - Assert.assertEquals(expected, fold1); - Assert.assertEquals(expected, fold2); + Assertions.assertEquals(expected, fold1); + Assertions.assertEquals(expected, fold2); assertSerDe(fold1); assertSerDe(fold2); diff --git a/processing/src/test/java/org/apache/druid/query/search/SearchQueryRunnerWithCaseTest.java b/processing/src/test/java/org/apache/druid/query/search/SearchQueryRunnerWithCaseTest.java index 11f4d2c6a73d..e2b334468b5c 100644 --- a/processing/src/test/java/org/apache/druid/query/search/SearchQueryRunnerWithCaseTest.java +++ b/processing/src/test/java/org/apache/druid/query/search/SearchQueryRunnerWithCaseTest.java @@ -37,10 +37,11 @@ import org.apache.druid.segment.incremental.IncrementalIndex; import org.apache.druid.testing.InitializedNullHandlingTest; import org.apache.druid.timeline.SegmentId; -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.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.Arrays; @@ -50,12 +51,14 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") public class SearchQueryRunnerWithCaseTest extends InitializedNullHandlingTest { - @Parameterized.Parameters - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { final SearchQueryConfig[] configs = new SearchQueryConfig[3]; configs[0] = new SearchQueryConfig(); @@ -109,7 +112,10 @@ public static Iterable constructorFeeder() )); } - return QueryRunnerTestHelper.transformToConstructionFeeder(runners); + return StreamSupport.stream( + QueryRunnerTestHelper.transformToConstructionFeeder(runners).spliterator(), + false + ); } static SearchQueryRunnerFactory makeRunnerFactory(final SearchQueryConfig config) @@ -121,14 +127,8 @@ static SearchQueryRunnerFactory makeRunnerFactory(final SearchQueryConfig config ); } - private final QueryRunner runner; - - public SearchQueryRunnerWithCaseTest( - QueryRunner runner - ) - { - this.runner = runner; - } + @Parameter(0) + public QueryRunner runner; private Druids.SearchQueryBuilder testBuilder() { @@ -252,31 +252,32 @@ private void checkSearchQuery(SearchQuery searchQuery, Map> Iterable> results = runner.run(QueryPlus.wrap(searchQuery)).toList(); for (Result result : results) { - Assert.assertEquals(DateTimes.of("2011-01-12T00:00:00.000Z"), result.getTimestamp()); - Assert.assertNotNull(result.getValue()); + Assertions.assertEquals(DateTimes.of("2011-01-12T00:00:00.000Z"), result.getTimestamp()); + Assertions.assertNotNull(result.getValue()); Iterable resultValues = result.getValue(); for (SearchHit resultValue : resultValues) { String dimension = resultValue.getDimension(); String theValue = resultValue.getValue(); - Assert.assertTrue( - StringUtils.format("Result had unknown dimension[%s]", dimension), - expectedResults.containsKey(dimension) + Assertions.assertTrue( + expectedResults.containsKey(dimension), + StringUtils.format("Result had unknown dimension[%s]", dimension) ); Set expectedSet = expectedResults.get(dimension); - Assert.assertTrue( - StringUtils.format("Couldn't remove dim[%s], value[%s]", dimension, theValue), expectedSet.remove(theValue) + Assertions.assertTrue( + expectedSet.remove(theValue), + StringUtils.format("Couldn't remove dim[%s], value[%s]", dimension, theValue) ); } } for (Map.Entry> entry : expectedResults.entrySet()) { - Assert.assertTrue( + Assertions.assertTrue( + entry.getValue().isEmpty(), StringUtils.format( "Dimension[%s] should have had everything removed, still has[%s]", entry.getKey(), entry.getValue() - ), - entry.getValue().isEmpty() + ) ); } expectedResults.clear(); diff --git a/processing/src/test/java/org/apache/druid/query/topn/TopNMetricSpecOptimizationsTest.java b/processing/src/test/java/org/apache/druid/query/topn/TopNMetricSpecOptimizationsTest.java index ae42acfa6f4e..1f6ac974c4c2 100644 --- a/processing/src/test/java/org/apache/druid/query/topn/TopNMetricSpecOptimizationsTest.java +++ b/processing/src/test/java/org/apache/druid/query/topn/TopNMetricSpecOptimizationsTest.java @@ -37,8 +37,8 @@ import org.apache.druid.segment.column.ColumnCapabilities; import org.apache.druid.segment.data.IndexedInts; import org.apache.druid.testing.InitializedNullHandlingTest; -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.util.List; @@ -83,8 +83,8 @@ public void testShouldOptimizeLexicographic() arrayProviderToTest.ignoreAfterThreshold(); Pair thePair = arrayProviderToTest.computeStartEnd(cardinality); - Assert.assertEquals(Integer.valueOf(0), thePair.lhs); - Assert.assertEquals(Integer.valueOf(threshold), thePair.rhs); + Assertions.assertEquals(Integer.valueOf(0), thePair.lhs); + Assertions.assertEquals(Integer.valueOf(threshold), thePair.rhs); } @Test @@ -116,8 +116,8 @@ public void testAlsoShouldOptimizeLexicographic() arrayProviderToTest.ignoreAfterThreshold(); Pair thePair = arrayProviderToTest.computeStartEnd(cardinality); - Assert.assertEquals(Integer.valueOf(0), thePair.lhs); - Assert.assertEquals(Integer.valueOf(threshold), thePair.rhs); + Assertions.assertEquals(Integer.valueOf(0), thePair.lhs); + Assertions.assertEquals(Integer.valueOf(threshold), thePair.rhs); } @Test @@ -149,8 +149,8 @@ public void testShouldNotOptimizeLexicographic() arrayProviderToTest.ignoreAfterThreshold(); Pair thePair = arrayProviderToTest.computeStartEnd(cardinality); - Assert.assertEquals(Integer.valueOf(0), thePair.lhs); - Assert.assertEquals(Integer.valueOf(cardinality), thePair.rhs); + Assertions.assertEquals(Integer.valueOf(0), thePair.lhs); + Assertions.assertEquals(Integer.valueOf(cardinality), thePair.rhs); } @Test @@ -182,8 +182,8 @@ public void testAlsoShouldNotOptimizeLexicographic() arrayProviderToTest.ignoreAfterThreshold(); Pair thePair = arrayProviderToTest.computeStartEnd(cardinality); - Assert.assertEquals(Integer.valueOf(0), thePair.lhs); - Assert.assertEquals(Integer.valueOf(cardinality), thePair.rhs); + Assertions.assertEquals(Integer.valueOf(0), thePair.lhs); + Assertions.assertEquals(Integer.valueOf(cardinality), thePair.rhs); } @Test @@ -213,8 +213,8 @@ public void testAgainShouldNotOptimizeLexicographic() ); Pair thePair = arrayProviderToTest.computeStartEnd(cardinality); - Assert.assertEquals(Integer.valueOf(0), thePair.lhs); - Assert.assertEquals(Integer.valueOf(cardinality), thePair.rhs); + Assertions.assertEquals(Integer.valueOf(0), thePair.lhs); + Assertions.assertEquals(Integer.valueOf(cardinality), thePair.rhs); } private TopNCursorInspector makeCursorInspector(String start, String end, int cardinality) diff --git a/processing/src/test/java/org/apache/druid/query/topn/TopNQueryTest.java b/processing/src/test/java/org/apache/druid/query/topn/TopNQueryTest.java index 002660dcc60d..5c088d58ac2c 100644 --- a/processing/src/test/java/org/apache/druid/query/topn/TopNQueryTest.java +++ b/processing/src/test/java/org/apache/druid/query/topn/TopNQueryTest.java @@ -46,19 +46,14 @@ import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.virtual.ExpressionVirtualColumn; import org.apache.druid.testing.InitializedNullHandlingTest; -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.List; public class TopNQueryTest extends InitializedNullHandlingTest { - @Rule - public ExpectedException expectedException = ExpectedException.none(); - private static final ObjectMapper JSON_MAPPER = TestHelper.makeJsonMapper(); @Test @@ -88,10 +83,9 @@ public void testQuerySerialization() throws IOException String json = JSON_MAPPER.writeValueAsString(query); Query serdeQuery = JSON_MAPPER.readValue(json, Query.class); - Assert.assertEquals(query, serdeQuery); + Assertions.assertEquals(query, serdeQuery); } - @Test public void testQuerySerdeWithLookupExtractionFn() throws IOException { @@ -121,7 +115,7 @@ public void testQuerySerdeWithLookupExtractionFn() throws IOException ) .build(); final String str = JSON_MAPPER.writeValueAsString(expectedQuery); - Assert.assertEquals(expectedQuery, JSON_MAPPER.readValue(str, TopNQuery.class)); + Assertions.assertEquals(expectedQuery, JSON_MAPPER.readValue(str, TopNQuery.class)); } @Test @@ -164,95 +158,92 @@ public void testQuerySerdeWithAlphaNumericTopNMetricSpec() throws IOException ) ), TopNQuery.class ); - Assert.assertEquals(expectedQuery, actualQuery); + Assertions.assertEquals(expectedQuery, actualQuery); } @Test - public void testQueryNullDimensionSpec() throws IOException + public void testQueryNullDimensionSpec() { - expectedException.expectMessage("dimensionSpec can't be null"); - - Query query = new TopNQueryBuilder() - .dataSource(QueryRunnerTestHelper.DATA_SOURCE) - .granularity(QueryRunnerTestHelper.ALL_GRAN) - .metric(QueryRunnerTestHelper.INDEX_METRIC) - .threshold(4) - .intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC) - .aggregators( - Lists.newArrayList( - Iterables.concat( - QueryRunnerTestHelper.COMMON_DOUBLE_AGGREGATORS, - Lists.newArrayList( - new DoubleMaxAggregatorFactory("maxIndex", "index"), - new DoubleMinAggregatorFactory("minIndex", "index") + Exception ex = Assertions.assertThrows( + Exception.class, + () -> new TopNQueryBuilder() + .dataSource(QueryRunnerTestHelper.DATA_SOURCE) + .granularity(QueryRunnerTestHelper.ALL_GRAN) + .metric(QueryRunnerTestHelper.INDEX_METRIC) + .threshold(4) + .intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC) + .aggregators( + Lists.newArrayList( + Iterables.concat( + QueryRunnerTestHelper.COMMON_DOUBLE_AGGREGATORS, + Lists.newArrayList( + new DoubleMaxAggregatorFactory("maxIndex", "index"), + new DoubleMinAggregatorFactory("minIndex", "index") + ) ) ) ) - ) - .postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT) - .build(); - - String json = JSON_MAPPER.writeValueAsString(query); - JSON_MAPPER.readValue(json, Query.class); + .postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT) + .build() + ); + Assertions.assertTrue(ex.getMessage().contains("dimensionSpec can't be null")); } @Test - public void testQueryZeroThreshold() throws IOException + public void testQueryZeroThreshold() { - expectedException.expectMessage("Threshold cannot be equal to 0."); - - Query query = new TopNQueryBuilder() - .dataSource(QueryRunnerTestHelper.DATA_SOURCE) - .granularity(QueryRunnerTestHelper.ALL_GRAN) - .metric(QueryRunnerTestHelper.INDEX_METRIC) - .dimension(new LegacyDimensionSpec(QueryRunnerTestHelper.MARKET_DIMENSION)) - .threshold(0) - .intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC) - .aggregators( - Lists.newArrayList( - Iterables.concat( - QueryRunnerTestHelper.COMMON_DOUBLE_AGGREGATORS, - Lists.newArrayList( - new DoubleMaxAggregatorFactory("maxIndex", "index"), - new DoubleMinAggregatorFactory("minIndex", "index") + Exception ex = Assertions.assertThrows( + Exception.class, + () -> new TopNQueryBuilder() + .dataSource(QueryRunnerTestHelper.DATA_SOURCE) + .granularity(QueryRunnerTestHelper.ALL_GRAN) + .metric(QueryRunnerTestHelper.INDEX_METRIC) + .dimension(new LegacyDimensionSpec(QueryRunnerTestHelper.MARKET_DIMENSION)) + .threshold(0) + .intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC) + .aggregators( + Lists.newArrayList( + Iterables.concat( + QueryRunnerTestHelper.COMMON_DOUBLE_AGGREGATORS, + Lists.newArrayList( + new DoubleMaxAggregatorFactory("maxIndex", "index"), + new DoubleMinAggregatorFactory("minIndex", "index") + ) ) ) ) - ) - .postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT) - .build(); - - String json = JSON_MAPPER.writeValueAsString(query); - JSON_MAPPER.readValue(json, Query.class); + .postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT) + .build() + ); + Assertions.assertTrue(ex.getMessage().contains("Threshold cannot be equal to 0.")); } @Test - public void testQueryNullMetric() throws IOException + public void testQueryNullMetric() { - expectedException.expectMessage("must specify a metric"); - - Query query = new TopNQueryBuilder() - .dataSource(QueryRunnerTestHelper.DATA_SOURCE) - .granularity(QueryRunnerTestHelper.ALL_GRAN) - .dimension(new LegacyDimensionSpec(QueryRunnerTestHelper.MARKET_DIMENSION)) - .threshold(2) - .intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC) - .aggregators( - Lists.newArrayList( - Iterables.concat( - QueryRunnerTestHelper.COMMON_DOUBLE_AGGREGATORS, - Lists.newArrayList( - new DoubleMaxAggregatorFactory("maxIndex", "index"), - new DoubleMinAggregatorFactory("minIndex", "index") + Exception ex = Assertions.assertThrows( + Exception.class, + () -> new TopNQueryBuilder() + .dataSource(QueryRunnerTestHelper.DATA_SOURCE) + .granularity(QueryRunnerTestHelper.ALL_GRAN) + .dimension(new LegacyDimensionSpec(QueryRunnerTestHelper.MARKET_DIMENSION)) + .threshold(2) + .intervals(QueryRunnerTestHelper.FULL_ON_INTERVAL_SPEC) + .aggregators( + Lists.newArrayList( + Iterables.concat( + QueryRunnerTestHelper.COMMON_DOUBLE_AGGREGATORS, + Lists.newArrayList( + new DoubleMaxAggregatorFactory("maxIndex", "index"), + new DoubleMinAggregatorFactory("minIndex", "index") + ) ) ) ) - ) - .postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT) - .build(); - - String json = JSON_MAPPER.writeValueAsString(query); - JSON_MAPPER.readValue(json, Query.class); + .postAggregators(QueryRunnerTestHelper.ADD_ROWS_INDEX_CONSTANT) + .build() + ); + Assertions.assertTrue(ex.getMessage().contains("must specify a metric")); } @Test @@ -270,7 +261,7 @@ public void testGetRequiredColumns() .threshold(100) .build(); - Assert.assertEquals(ImmutableSet.of("__time", "other", "index"), query.getRequiredColumns()); + Assertions.assertEquals(ImmutableSet.of("__time", "other", "index"), query.getRequiredColumns()); } @Test @@ -293,11 +284,11 @@ public void testAsCursorBuildSpecAllGranularity() .build(); final CursorBuildSpec buildSpec = TopNQueryEngine.makeCursorBuildSpec(query, null); - Assert.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); - Assert.assertEquals(ImmutableList.of("v"), buildSpec.getGroupingColumns()); - Assert.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); - Assert.assertEquals(virtualColumns, buildSpec.getVirtualColumns()); - Assert.assertEquals(List.of(), buildSpec.getPreferredOrdering()); + Assertions.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); + Assertions.assertEquals(ImmutableList.of("v"), buildSpec.getGroupingColumns()); + Assertions.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); + Assertions.assertEquals(virtualColumns, buildSpec.getVirtualColumns()); + Assertions.assertEquals(List.of(), buildSpec.getPreferredOrdering()); } @Test @@ -320,19 +311,19 @@ public void testAsCursorBuildSpecDayGranularity() .build(); final CursorBuildSpec buildSpec = TopNQueryEngine.makeCursorBuildSpec(query, null); - Assert.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); - Assert.assertEquals( + Assertions.assertEquals(QueryRunnerTestHelper.FIRST_TO_THIRD.getIntervals().get(0), buildSpec.getInterval()); + Assertions.assertEquals( ImmutableList.of(Granularities.GRANULARITY_VIRTUAL_COLUMN_NAME, "v"), buildSpec.getGroupingColumns() ); - Assert.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); - Assert.assertEquals( + Assertions.assertEquals(ImmutableList.of(QueryRunnerTestHelper.ROWS_COUNT, longSum), buildSpec.getAggregators()); + Assertions.assertEquals( VirtualColumns.create( Granularities.toVirtualColumn(query.getGranularity(), Granularities.GRANULARITY_VIRTUAL_COLUMN_NAME), virtualColumns.getVirtualColumns()[0] ), buildSpec.getVirtualColumns() ); - Assert.assertEquals(Cursors.ascendingTimeOrder(), buildSpec.getPreferredOrdering()); + Assertions.assertEquals(Cursors.ascendingTimeOrder(), buildSpec.getPreferredOrdering()); } } diff --git a/processing/src/test/java/org/apache/druid/segment/CursorBuildSpecTest.java b/processing/src/test/java/org/apache/druid/segment/CursorBuildSpecTest.java index 56dd2396d0d0..124d0d0a984b 100644 --- a/processing/src/test/java/org/apache/druid/segment/CursorBuildSpecTest.java +++ b/processing/src/test/java/org/apache/druid/segment/CursorBuildSpecTest.java @@ -31,8 +31,8 @@ import org.apache.druid.segment.column.ColumnType; import org.apache.druid.segment.filter.AndFilter; import org.apache.druid.segment.virtual.ExpressionVirtualColumn; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class CursorBuildSpecTest { @@ -56,21 +56,21 @@ public void testIsCompatibleOrdering() ) .build(); // fail if cursor isn't fully ordered by the preferred ordering of the spec - Assert.assertFalse(spec1.isCompatibleOrdering(ImmutableList.of(OrderBy.ascending(ColumnHolder.TIME_COLUMN_NAME)))); + Assertions.assertFalse(spec1.isCompatibleOrdering(ImmutableList.of(OrderBy.ascending(ColumnHolder.TIME_COLUMN_NAME)))); // pass if the cursor ordering exactly matches - Assert.assertTrue( + Assertions.assertTrue( spec1.isCompatibleOrdering( ImmutableList.of(OrderBy.ascending(ColumnHolder.TIME_COLUMN_NAME), OrderBy.ascending("x")) ) ); // pass if the cursor ordering is exactly the reverse - Assert.assertTrue( + Assertions.assertTrue( spec1.isCompatibleOrdering( ImmutableList.of(OrderBy.descending(ColumnHolder.TIME_COLUMN_NAME), OrderBy.descending("x")) ) ); // pass if the cursor ordering includes additional ordering not specified by the spec preferred ordering - Assert.assertTrue( + Assertions.assertTrue( spec1.isCompatibleOrdering( ImmutableList.of( OrderBy.ascending(ColumnHolder.TIME_COLUMN_NAME), @@ -80,7 +80,7 @@ public void testIsCompatibleOrdering() ) ); // fail if the cursor ordering is different - Assert.assertFalse( + Assertions.assertFalse( spec1.isCompatibleOrdering( ImmutableList.of( OrderBy.ascending(ColumnHolder.TIME_COLUMN_NAME), @@ -90,7 +90,7 @@ public void testIsCompatibleOrdering() ) ); // fail if the cursor ordering is different - Assert.assertFalse( + Assertions.assertFalse( spec1.isCompatibleOrdering( ImmutableList.of(OrderBy.ascending(ColumnHolder.TIME_COLUMN_NAME), OrderBy.descending("x")) ) @@ -100,7 +100,7 @@ public void testIsCompatibleOrdering() CursorBuildSpec spec2 = CursorBuildSpec.builder() .setPhysicalColumns(ImmutableSet.of(ColumnHolder.TIME_COLUMN_NAME, "x", "y")) .build(); - Assert.assertTrue( + Assertions.assertTrue( spec2.isCompatibleOrdering( ImmutableList.of(OrderBy.ascending(ColumnHolder.TIME_COLUMN_NAME), OrderBy.ascending("x")) ) @@ -126,8 +126,8 @@ public void testBuilderAndFilterNoExistingFilterWithPhysicalColumns() builder.andFilter(new EqualityFilter("z", ColumnType.STRING, "hello", null)); - Assert.assertEquals(new EqualityFilter("z", ColumnType.STRING, "hello", null), builder.getFilter()); - Assert.assertEquals( + Assertions.assertEquals(new EqualityFilter("z", ColumnType.STRING, "hello", null), builder.getFilter()); + Assertions.assertEquals( ImmutableSet.of("x", "y", "z"), builder.getPhysicalColumns() ); @@ -152,8 +152,8 @@ public void testBuilderAndFilterNoExistingFilterWithPhysicalColumnsNoNewReferenc builder.andFilter(new EqualityFilter("x", ColumnType.STRING, "hello", null)); - Assert.assertEquals(new EqualityFilter("x", ColumnType.STRING, "hello", null), builder.getFilter()); - Assert.assertEquals( + Assertions.assertEquals(new EqualityFilter("x", ColumnType.STRING, "hello", null), builder.getFilter()); + Assertions.assertEquals( ImmutableSet.of("x", "y"), builder.getPhysicalColumns() ); @@ -179,7 +179,7 @@ public void testBuilderAndFilterExistingFilterWithPhysicalColumns() builder.andFilter(new EqualityFilter("z", ColumnType.STRING, "hello", null)); - Assert.assertEquals( + Assertions.assertEquals( new AndFilter( ImmutableList.of( new EqualityFilter("x", ColumnType.STRING, "foo", null), @@ -188,7 +188,7 @@ public void testBuilderAndFilterExistingFilterWithPhysicalColumns() ), builder.getFilter() ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableSet.of("x", "y", "z"), builder.getPhysicalColumns() ); @@ -202,8 +202,8 @@ public void testBuilderAndFilterNoExistingFilterNoPhysicalColumns() builder.andFilter(new EqualityFilter("z", ColumnType.STRING, "hello", null)); - Assert.assertEquals(new EqualityFilter("z", ColumnType.STRING, "hello", null), builder.getFilter()); - Assert.assertNull( + Assertions.assertEquals(new EqualityFilter("z", ColumnType.STRING, "hello", null), builder.getFilter()); + Assertions.assertNull( builder.getPhysicalColumns() ); } @@ -216,7 +216,7 @@ public void testBuilderAndFilterExistingFilterNoPhysicalColumns() builder.andFilter(new EqualityFilter("z", ColumnType.STRING, "hello", null)); - Assert.assertEquals( + Assertions.assertEquals( new AndFilter( ImmutableList.of( new EqualityFilter("x", ColumnType.STRING, "foo", null), @@ -225,7 +225,7 @@ public void testBuilderAndFilterExistingFilterNoPhysicalColumns() ), builder.getFilter() ); - Assert.assertNull( + Assertions.assertNull( builder.getPhysicalColumns() ); } @@ -248,11 +248,11 @@ public void testBuilderAndFilterNoExistingFilterUsingVirtualColumn() ); builder.andFilter(new RangeFilter("v0", ColumnType.LONG, 1L, 3L, true, true, null)); - Assert.assertEquals( + Assertions.assertEquals( new RangeFilter("v0", ColumnType.LONG, 1L, 3L, true, true, null), builder.getFilter() ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableSet.of("x", "y"), builder.getPhysicalColumns() ); @@ -277,7 +277,7 @@ public void testBuilderAndFilterExistingFilterNewFilterUsingVirtualColumn() ); builder.andFilter(new RangeFilter("v0", ColumnType.LONG, 1L, 3L, true, true, null)); - Assert.assertEquals( + Assertions.assertEquals( new AndFilter( ImmutableList.of( new EqualityFilter("x", ColumnType.STRING, "foo", null), @@ -286,7 +286,7 @@ public void testBuilderAndFilterExistingFilterNewFilterUsingVirtualColumn() ), builder.getFilter() ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableSet.of("x", "y"), builder.getPhysicalColumns() ); @@ -297,11 +297,11 @@ public void testAndFilterNull() { CursorBuildSpec.CursorBuildSpecBuilder builder = CursorBuildSpec.builder(); - Throwable t = Assert.assertThrows( + Throwable t = Assertions.assertThrows( DruidException.class, () -> builder.andFilter(null) ); - Assert.assertEquals("filterToAdd must not be null", t.getMessage()); + Assertions.assertEquals("filterToAdd must not be null", t.getMessage()); } } diff --git a/processing/src/test/java/org/apache/druid/segment/IndexIOTest.java b/processing/src/test/java/org/apache/druid/segment/IndexIOTest.java index df32b3210f64..55a2fc50b5b2 100644 --- a/processing/src/test/java/org/apache/druid/segment/IndexIOTest.java +++ b/processing/src/test/java/org/apache/druid/segment/IndexIOTest.java @@ -40,11 +40,12 @@ import org.apache.druid.segment.incremental.OnheapIncrementalIndex; import org.apache.druid.testing.InitializedNullHandlingTest; import org.joda.time.Interval; -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.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import javax.annotation.Nullable; import java.util.ArrayList; @@ -56,11 +57,14 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; /** * This is mostly a test of the validator */ -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructionFeeder") public class IndexIOTest extends InitializedNullHandlingTest { private static Interval DEFAULT_INTERVAL = Intervals.of("1970-01-01/2000-01-01"); @@ -82,8 +86,7 @@ private static List filterByBitset(List list, BitSet bitSet) return outList; } - @Parameterized.Parameters(name = "{0}, {1}") - public static Iterable constructionFeeder() + public static Stream constructionFeeder() { final Map map = ImmutableMap.of(); @@ -106,7 +109,7 @@ public static Iterable constructionFeeder() final List> maps = ImmutableList.of(map, map00, map10, map0null, map1null, mapAll); - return Iterables.concat( + final Iterable allParams = Iterables.concat( // First iterable tests permutations of the maps which are expected to be equal Iterables.concat( new Iterable>() @@ -225,6 +228,7 @@ public void remove() } ) ); + return StreamSupport.stream(allParams.spliterator(), false); } public static List filterNullValues(List> mapList) @@ -232,20 +236,15 @@ public static List filterNullValues(List> mapList) return Lists.transform(mapList, (Function) input -> Maps.filterValues(input, Objects::nonNull)); } - private final Collection> events1; - private final Collection> events2; - private final Class exception; + @Parameter(0) + public Collection> events1; + + @Parameter(1) + public Collection> events2; + + @Parameter(2) + public Class exception; - public IndexIOTest( - Collection> events1, - Collection> events2, - Class exception - ) - { - this.events1 = events1; - this.events2 = events2; - this.exception = exception; - } final IncrementalIndex incrementalIndex1 = new OnheapIncrementalIndex.Builder() .setIndexSchema( @@ -276,7 +275,7 @@ public IndexIOTest( IndexableAdapter adapter1; IndexableAdapter adapter2; - @Before + @BeforeEach public void setUp() { long timestamp = 0L; @@ -313,7 +312,7 @@ public void testRowValidatorEquals() throws Exception ex = e; } if (exception != null) { - Assert.assertNotNull("Exception was not thrown", ex); + Assertions.assertNotNull(ex, "Exception was not thrown"); if (!exception.isAssignableFrom(ex.getClass())) { throw ex; } diff --git a/processing/src/test/java/org/apache/druid/segment/QueryableIndexCursorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/QueryableIndexCursorFactoryTest.java index 05de6845e53b..11dcff7785ac 100644 --- a/processing/src/test/java/org/apache/druid/segment/QueryableIndexCursorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/QueryableIndexCursorFactoryTest.java @@ -28,24 +28,26 @@ import org.apache.druid.testing.InitializedNullHandlingTest; 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.runner.RunWith; -import org.junit.runners.Parameterized; +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.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Collection; +import java.util.stream.Stream; public class QueryableIndexCursorFactoryTest { - @RunWith(Parameterized.class) + @ParameterizedClass + @MethodSource("constructorFeeder") public static class DimensionDictionarySelectorTest extends InitializedNullHandlingTest { - private final boolean vectorize; + @Parameter(0) + public boolean vectorize; private DimensionDictionarySelector qualitySelector; private DimensionDictionarySelector placementishSelector; @@ -53,18 +55,12 @@ public static class DimensionDictionarySelectorTest extends InitializedNullHandl private Closer closer = Closer.create(); - @Parameterized.Parameters(name = "vectorize = {0}") - public static Collection constructorFeeder() + public static Stream constructorFeeder() { - return Arrays.asList(new Object[]{false}, new Object[]{true}); + return Stream.of(new Object[]{false}, new Object[]{true}); } - public DimensionDictionarySelectorTest(boolean vectorize) - { - this.vectorize = vectorize; - } - - @Before + @BeforeEach public void setUp() { final QueryableIndex index = TestIndex.getMMappedTestIndex(); @@ -94,7 +90,7 @@ public void setUp() } } - @After + @AfterEach public void tearDown() throws IOException { closer.close(); @@ -103,89 +99,89 @@ public void tearDown() throws IOException @Test public void test_getCardinality_quality() { - Assert.assertEquals(9, qualitySelector.getValueCardinality()); + Assertions.assertEquals(9, qualitySelector.getValueCardinality()); } @Test public void test_getCardinality_placementish() { - Assert.assertEquals(9, placementishSelector.getValueCardinality()); + Assertions.assertEquals(9, placementishSelector.getValueCardinality()); } @Test public void test_getCardinality_partialNullColumn() { - Assert.assertEquals(2, partialNullSelector.getValueCardinality()); + Assertions.assertEquals(2, partialNullSelector.getValueCardinality()); } @Test public void test_lookupName_quality() { - Assert.assertEquals("automotive", qualitySelector.lookupName(0)); - Assert.assertEquals("business", qualitySelector.lookupName(1)); - Assert.assertEquals("entertainment", qualitySelector.lookupName(2)); - Assert.assertEquals("health", qualitySelector.lookupName(3)); - Assert.assertEquals("mezzanine", qualitySelector.lookupName(4)); - Assert.assertEquals("news", qualitySelector.lookupName(5)); - Assert.assertEquals("premium", qualitySelector.lookupName(6)); - Assert.assertEquals("technology", qualitySelector.lookupName(7)); - Assert.assertEquals("travel", qualitySelector.lookupName(8)); + Assertions.assertEquals("automotive", qualitySelector.lookupName(0)); + Assertions.assertEquals("business", qualitySelector.lookupName(1)); + Assertions.assertEquals("entertainment", qualitySelector.lookupName(2)); + Assertions.assertEquals("health", qualitySelector.lookupName(3)); + Assertions.assertEquals("mezzanine", qualitySelector.lookupName(4)); + Assertions.assertEquals("news", qualitySelector.lookupName(5)); + Assertions.assertEquals("premium", qualitySelector.lookupName(6)); + Assertions.assertEquals("technology", qualitySelector.lookupName(7)); + Assertions.assertEquals("travel", qualitySelector.lookupName(8)); } @Test public void test_lookupName_placementish() { - Assert.assertEquals("a", placementishSelector.lookupName(0)); - Assert.assertEquals("b", placementishSelector.lookupName(1)); - Assert.assertEquals("e", placementishSelector.lookupName(2)); - Assert.assertEquals("h", placementishSelector.lookupName(3)); - Assert.assertEquals("m", placementishSelector.lookupName(4)); - Assert.assertEquals("n", placementishSelector.lookupName(5)); - Assert.assertEquals("p", placementishSelector.lookupName(6)); - Assert.assertEquals("preferred", placementishSelector.lookupName(7)); - Assert.assertEquals("t", placementishSelector.lookupName(8)); + Assertions.assertEquals("a", placementishSelector.lookupName(0)); + Assertions.assertEquals("b", placementishSelector.lookupName(1)); + Assertions.assertEquals("e", placementishSelector.lookupName(2)); + Assertions.assertEquals("h", placementishSelector.lookupName(3)); + Assertions.assertEquals("m", placementishSelector.lookupName(4)); + Assertions.assertEquals("n", placementishSelector.lookupName(5)); + Assertions.assertEquals("p", placementishSelector.lookupName(6)); + Assertions.assertEquals("preferred", placementishSelector.lookupName(7)); + Assertions.assertEquals("t", placementishSelector.lookupName(8)); } @Test public void test_lookupName_partialNull() { - Assert.assertNull(partialNullSelector.lookupName(0)); - Assert.assertEquals("value", partialNullSelector.lookupName(1)); + Assertions.assertNull(partialNullSelector.lookupName(0)); + Assertions.assertEquals("value", partialNullSelector.lookupName(1)); } @Test public void test_lookupNameUtf8_quality() { - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("automotive")), qualitySelector.lookupNameUtf8(0)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("business")), qualitySelector.lookupNameUtf8(1)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("entertainment")), qualitySelector.lookupNameUtf8(2)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("health")), qualitySelector.lookupNameUtf8(3)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("mezzanine")), qualitySelector.lookupNameUtf8(4)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("news")), qualitySelector.lookupNameUtf8(5)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("premium")), qualitySelector.lookupNameUtf8(6)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("technology")), qualitySelector.lookupNameUtf8(7)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("travel")), qualitySelector.lookupNameUtf8(8)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("automotive")), qualitySelector.lookupNameUtf8(0)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("business")), qualitySelector.lookupNameUtf8(1)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("entertainment")), qualitySelector.lookupNameUtf8(2)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("health")), qualitySelector.lookupNameUtf8(3)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("mezzanine")), qualitySelector.lookupNameUtf8(4)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("news")), qualitySelector.lookupNameUtf8(5)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("premium")), qualitySelector.lookupNameUtf8(6)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("technology")), qualitySelector.lookupNameUtf8(7)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("travel")), qualitySelector.lookupNameUtf8(8)); } @Test public void test_lookupNameUtf8_placementish() { - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("a")), placementishSelector.lookupNameUtf8(0)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("b")), placementishSelector.lookupNameUtf8(1)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("e")), placementishSelector.lookupNameUtf8(2)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("h")), placementishSelector.lookupNameUtf8(3)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("m")), placementishSelector.lookupNameUtf8(4)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("n")), placementishSelector.lookupNameUtf8(5)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("p")), placementishSelector.lookupNameUtf8(6)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("preferred")), placementishSelector.lookupNameUtf8(7)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("t")), placementishSelector.lookupNameUtf8(8)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("a")), placementishSelector.lookupNameUtf8(0)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("b")), placementishSelector.lookupNameUtf8(1)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("e")), placementishSelector.lookupNameUtf8(2)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("h")), placementishSelector.lookupNameUtf8(3)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("m")), placementishSelector.lookupNameUtf8(4)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("n")), placementishSelector.lookupNameUtf8(5)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("p")), placementishSelector.lookupNameUtf8(6)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("preferred")), placementishSelector.lookupNameUtf8(7)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("t")), placementishSelector.lookupNameUtf8(8)); } @Test public void test_lookupNameUtf8_partialNull() { - Assert.assertNull(partialNullSelector.lookupNameUtf8(0)); - Assert.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("value")), partialNullSelector.lookupNameUtf8(1)); + Assertions.assertNull(partialNullSelector.lookupNameUtf8(0)); + Assertions.assertEquals(ByteBuffer.wrap(StringUtils.toUtf8("value")), partialNullSelector.lookupNameUtf8(1)); } @Test @@ -193,25 +189,25 @@ public void test_lookupNameUtf8_buffersAreNotShared() { // Different buffer on different calls; enables callers to safely modify position, limit as promised in // the javadocs. - Assert.assertNotSame(qualitySelector.lookupNameUtf8(0), qualitySelector.lookupNameUtf8(0)); + Assertions.assertNotSame(qualitySelector.lookupNameUtf8(0), qualitySelector.lookupNameUtf8(0)); } @Test public void test_supportsLookupNameUtf8_quality() { - Assert.assertTrue(partialNullSelector.supportsLookupNameUtf8()); + Assertions.assertTrue(partialNullSelector.supportsLookupNameUtf8()); } @Test public void test_supportsLookupNameUtf8_placementish() { - Assert.assertTrue(partialNullSelector.supportsLookupNameUtf8()); + Assertions.assertTrue(partialNullSelector.supportsLookupNameUtf8()); } @Test public void test_supportsLookupNameUtf8_partialNull() { - Assert.assertTrue(partialNullSelector.supportsLookupNameUtf8()); + Assertions.assertTrue(partialNullSelector.supportsLookupNameUtf8()); } } @@ -221,7 +217,7 @@ public static class ManySelectorsOneColumnTest extends InitializedNullHandlingTe private ColumnSelectorFactory columnSelectorFactory; private final Closer closer = Closer.create(); - @Before + @BeforeEach public void setUp() { final QueryableIndex index = TestIndex.getMMappedTestIndex(); @@ -231,7 +227,7 @@ public void setUp() columnSelectorFactory = cursor.getColumnSelectorFactory(); } - @After + @AfterEach public void testDown() throws IOException { closer.close(); @@ -245,7 +241,7 @@ public void testTwoSelectorsOneComplexColumn() final DimensionSelector dimensionSelector = columnSelectorFactory.makeDimensionSelector(DefaultDimensionSpec.of("quality_uniques")); - Assert.assertNull(dimensionSelector.getObject()); + Assertions.assertNull(dimensionSelector.getObject()); } @Test @@ -256,7 +252,7 @@ public void testTwoSelectorsOneNumericColumn() final DimensionSelector dimensionSelector = columnSelectorFactory.makeDimensionSelector(DefaultDimensionSpec.of("index")); - Assert.assertEquals("100.0", dimensionSelector.getObject()); + Assertions.assertEquals("100.0", dimensionSelector.getObject()); } @Test diff --git a/processing/src/test/java/org/apache/druid/segment/data/CompressedColumnarIntsSerializerTest.java b/processing/src/test/java/org/apache/druid/segment/data/CompressedColumnarIntsSerializerTest.java index 8e175ebe22ac..8d21d4b2dacd 100644 --- a/processing/src/test/java/org/apache/druid/segment/data/CompressedColumnarIntsSerializerTest.java +++ b/processing/src/test/java/org/apache/druid/segment/data/CompressedColumnarIntsSerializerTest.java @@ -38,16 +38,15 @@ import org.apache.druid.utils.CloseableUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import java.io.File; import java.io.IOException; @@ -57,54 +56,48 @@ import java.util.Random; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") public class CompressedColumnarIntsSerializerTest { private static final int[] MAX_VALUES = new int[]{0xFF, 0xFFFF, 0xFFFFFF, 0x0FFFFFFF}; private static final int[] CHUNK_FACTORS = new int[]{1, 2, 100, CompressedColumnarIntsSupplier.MAX_INTS_IN_BUFFER}; private final SegmentWriteOutMedium segmentWriteOutMedium = new OffHeapMemorySegmentWriteOutMedium(); - private final CompressionStrategy compressionStrategy; - private final ByteOrder byteOrder; + @Parameter(0) + public CompressionStrategy compressionStrategy; + @Parameter(1) + public ByteOrder byteOrder; private final Random rand = new Random(0); private int[] vals; + @TempDir + public File temporaryFolder; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - public CompressedColumnarIntsSerializerTest( - CompressionStrategy compressionStrategy, - ByteOrder byteOrder - ) - { - this.compressionStrategy = compressionStrategy; - this.byteOrder = byteOrder; - } - - @Parameterized.Parameters(name = "{index}: compression={0}, byteOrder={1}") - public static Iterable compressionStrategiesAndByteOrders() + public static Stream constructorFeeder() { Set> combinations = Sets.cartesianProduct( Sets.newHashSet(CompressionStrategy.noNoneValues()), Sets.newHashSet(ByteOrder.BIG_ENDIAN, ByteOrder.LITTLE_ENDIAN) ); - return Iterables.transform( - combinations, - (Function) input -> new Object[]{input.get(0), input.get(1)} + return StreamSupport.stream( + Iterables.transform( + combinations, + (Function) input -> new Object[]{input.get(0), input.get(1)} + ).spliterator(), + false ); } - @Before + @BeforeEach public void setUp() { vals = null; } - @After + @AfterEach public void tearDown() throws Exception { segmentWriteOutMedium.close(); @@ -156,13 +149,14 @@ public void testMultiValueFileLargeData() throws Exception @Test public void testLargeColumn() throws IOException { - final File columnDir = temporaryFolder.newFolder(); + final File columnDir = new File(temporaryFolder, "columnDir"); + FileUtils.mkdirp(columnDir); final String columnName = "column"; final long numRows = 500_000; // enough values that we expect to switch into large-column mode try ( SegmentWriteOutMedium segmentWriteOutMedium = - TmpFileSegmentWriteOutMediumFactory.instance().makeSegmentWriteOutMedium(temporaryFolder.newFolder()); + TmpFileSegmentWriteOutMediumFactory.instance().makeSegmentWriteOutMedium(new File(temporaryFolder, "medium1")); FileSmoosher smoosher = new FileSmoosher(columnDir) ) { final Random random = new Random(0); @@ -202,39 +196,43 @@ public void testLargeColumn() throws IOException ); try (final ColumnarInts column = columnSupplier.get()) { - Assert.assertEquals(numRows, column.size()); + Assertions.assertEquals(numRows, column.size()); } } } // this test takes ~30 minutes to run - @Ignore + @Disabled @Test public void testTooManyValues() throws IOException { - expectedException.expect(ColumnCapacityExceededException.class); - expectedException.expectMessage(ColumnCapacityExceededException.formatMessage("test")); - try ( - SegmentWriteOutMedium segmentWriteOutMedium = - TmpFileSegmentWriteOutMediumFactory.instance().makeSegmentWriteOutMedium(temporaryFolder.newFolder()) - ) { - CompressedColumnarIntsSerializer serializer = new CompressedColumnarIntsSerializer( - "test", - segmentWriteOutMedium, - "test", - CompressedColumnarIntsSupplier.MAX_INTS_IN_BUFFER, - byteOrder, - compressionStrategy, - GenericIndexedWriter.MAX_FILE_SIZE, - segmentWriteOutMedium.getCloser() - ); - serializer.open(); - - final long numRows = Integer.MAX_VALUE + 100L; - for (long i = 0L; i < numRows; i++) { - serializer.addValue(ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE)); - } - } + Assertions.assertThrows( + ColumnCapacityExceededException.class, + () -> { + try ( + SegmentWriteOutMedium segmentWriteOutMedium = + TmpFileSegmentWriteOutMediumFactory.instance() + .makeSegmentWriteOutMedium(new File(temporaryFolder, "medium2")) + ) { + CompressedColumnarIntsSerializer serializer = new CompressedColumnarIntsSerializer( + "test", + segmentWriteOutMedium, + "test", + CompressedColumnarIntsSupplier.MAX_INTS_IN_BUFFER, + byteOrder, + compressionStrategy, + GenericIndexedWriter.MAX_FILE_SIZE, + segmentWriteOutMedium.getCloser() + ); + serializer.open(); + + final long numRows = Integer.MAX_VALUE + 100L; + for (long i = 0L; i < numRows; i++) { + serializer.addValue(ThreadLocalRandom.current().nextInt(0, Integer.MAX_VALUE)); + } + } + } + ); } private void generateVals(final int totalSize, final int maxValue) @@ -247,7 +245,9 @@ private void generateVals(final int totalSize, final int maxValue) private void checkSerializedSizeAndData(int chunkFactor) throws Exception { - FileSmoosher smoosher = new FileSmoosher(temporaryFolder.newFolder()); + final File smoosherDir = new File(temporaryFolder, StringUtils.replace("smoosher_" + compressionStrategy + "_" + byteOrder.toString(), " ", "")); + FileUtils.mkdirp(smoosherDir); + FileSmoosher smoosher = new FileSmoosher(smoosherDir); CompressedColumnarIntsSerializer writer = new CompressedColumnarIntsSerializer( "test", @@ -275,7 +275,7 @@ private void checkSerializedSizeAndData(int chunkFactor) throws Exception writer.writeTo(writeOutBytes, smoosher); smoosher.close(); - Assert.assertEquals(writtenLength, supplierFromList.getSerializedSize()); + Assertions.assertEquals(writtenLength, supplierFromList.getSerializedSize()); // read from ByteBuffer and check values CompressedColumnarIntsSupplier supplierFromByteBuffer = CompressedColumnarIntsSupplier.fromByteBuffer( @@ -284,9 +284,9 @@ private void checkSerializedSizeAndData(int chunkFactor) throws Exception null ); ColumnarInts columnarInts = supplierFromByteBuffer.get(); - Assert.assertEquals(vals.length, columnarInts.size()); + Assertions.assertEquals(vals.length, columnarInts.size()); for (int i = 0; i < vals.length; ++i) { - Assert.assertEquals(vals[i], columnarInts.get(i)); + Assertions.assertEquals(vals[i], columnarInts.get(i)); } CloseableUtils.closeAndWrapExceptions(columnarInts); CloseableUtils.closeAndWrapExceptions(segmentWriteOutMedium); @@ -329,9 +329,9 @@ private void checkV2SerializedSizeAndData(int chunkFactor) throws Exception null ); ColumnarInts columnarInts = supplierFromByteBuffer.get(); - Assert.assertEquals(vals.length, columnarInts.size()); + Assertions.assertEquals(vals.length, columnarInts.size()); for (int i = 0; i < vals.length; ++i) { - Assert.assertEquals(vals[i], columnarInts.get(i)); + Assertions.assertEquals(vals[i], columnarInts.get(i)); } CloseableUtils.closeAndWrapExceptions(columnarInts); mapper.close(); diff --git a/processing/src/test/java/org/apache/druid/segment/data/NumericNullColumnSelectorTest.java b/processing/src/test/java/org/apache/druid/segment/data/NumericNullColumnSelectorTest.java index add494bc2033..bdbbc813571b 100644 --- a/processing/src/test/java/org/apache/druid/segment/data/NumericNullColumnSelectorTest.java +++ b/processing/src/test/java/org/apache/druid/segment/data/NumericNullColumnSelectorTest.java @@ -30,9 +30,9 @@ import org.apache.druid.segment.vector.NoFilterVectorOffset; import org.apache.druid.segment.vector.VectorOffset; import org.apache.druid.segment.vector.VectorValueSelector; -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.Random; import java.util.concurrent.ThreadLocalRandom; @@ -50,7 +50,7 @@ public class NumericNullColumnSelectorTest new NoFilterOffsetThatCanBeMangledToTestOverlapping(vectorSize, 0, numRows); private ImmutableBitmap[] bitmaps; - @Before + @BeforeEach public void setup() { bitmaps = new ImmutableBitmap[numBitmaps]; @@ -171,19 +171,19 @@ private static void assertOffsetCanReset( { boolean encounteredNull = false; while (readItAll.withinBounds()) { - Assert.assertEquals(bitmap.get(readItAll.getOffset()), selector.isNull()); + Assertions.assertEquals(bitmap.get(readItAll.getOffset()), selector.isNull()); encounteredNull |= selector.isNull(); readItAll.increment(); } readItAll.reset(); - Assert.assertTrue(encounteredNull); + Assertions.assertTrue(encounteredNull); encounteredNull = false; while (readItAll.withinBounds()) { - Assert.assertEquals(bitmap.get(readItAll.getOffset()), selector.isNull()); + Assertions.assertEquals(bitmap.get(readItAll.getOffset()), selector.isNull()); encounteredNull |= selector.isNull(); readItAll.increment(); } - Assert.assertTrue(encounteredNull); + Assertions.assertTrue(encounteredNull); readItAll.reset(); } @@ -200,24 +200,24 @@ private static void assertVectorOffsetCanReset( while (!readAllVectors.isDone()) { nullVector = selector.getNullVector(); for (int i = readAllVectors.getStartOffset(); i < readAllVectors.getCurrentVectorSize(); i++) { - Assert.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); + Assertions.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); encounteredNull |= nullVector[i]; } readAllVectors.advance(); } // reset and read it all again to make sure matches readAllVectors.reset(); - Assert.assertTrue(encounteredNull); + Assertions.assertTrue(encounteredNull); encounteredNull = false; while (!readAllVectors.isDone()) { nullVector = selector.getNullVector(); for (int i = readAllVectors.getStartOffset(); i < readAllVectors.getCurrentVectorSize(); i++) { - Assert.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); + Assertions.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); encounteredNull |= nullVector[i]; } readAllVectors.advance(); } - Assert.assertTrue(encounteredNull); + Assertions.assertTrue(encounteredNull); readAllVectors.reset(); } @@ -234,21 +234,21 @@ public static void assertVectorChillWhenOffsetsOverlap( readAllVectors.mangleOffset(0); nullVector = selector.getNullVector(); for (int i = readAllVectors.getStartOffset(); i < readAllVectors.getCurrentVectorSize(); i++) { - Assert.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); + Assertions.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); encounteredNull |= nullVector[i]; } - Assert.assertTrue(encounteredNull); + Assertions.assertTrue(encounteredNull); // this can't currently happen, but we want to protect selectors in case offsets ever try to overlap readAllVectors.mangleOffset(1); nullVector = selector.getNullVector(); for (int i = readAllVectors.getStartOffset(); i < readAllVectors.getCurrentVectorSize(); i++) { - Assert.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); + Assertions.assertEquals(bitmap.get(readAllVectors.getStartOffset() + i), nullVector[i]); encounteredNull |= nullVector[i]; } readAllVectors.reset(); - Assert.assertTrue(encounteredNull); + Assertions.assertTrue(encounteredNull); } private static class NoFilterOffsetThatCanBeMangledToTestOverlapping implements VectorOffset diff --git a/processing/src/test/java/org/apache/druid/segment/filter/ExtractionDimFilterTest.java b/processing/src/test/java/org/apache/druid/segment/filter/ExtractionDimFilterTest.java index b890e666d36a..62adf5ad53e7 100644 --- a/processing/src/test/java/org/apache/druid/segment/filter/ExtractionDimFilterTest.java +++ b/processing/src/test/java/org/apache/druid/segment/filter/ExtractionDimFilterTest.java @@ -45,48 +45,52 @@ import org.apache.druid.segment.data.RoaringBitmapSerdeFactory; import org.apache.druid.segment.serde.StringUtf8ColumnIndexSupplier; import org.apache.druid.testing.InitializedNullHandlingTest; -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.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.Parameter; +import org.junit.jupiter.params.ParameterizedClass; +import org.junit.jupiter.params.provider.MethodSource; import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Map; +import java.util.stream.Stream; /** * */ -@RunWith(Parameterized.class) +@ParameterizedClass +@MethodSource("constructorFeeder") public class ExtractionDimFilterTest extends InitializedNullHandlingTest { private static final Map EXTRACTION_VALUES = ImmutableMap.of( "foo1", "extractDimVal" ); - @Parameterized.Parameters - public static Iterable constructorFeeder() + public static Stream constructorFeeder() { return ImmutableList.of( new Object[]{new ConciseBitmapFactory(), new ConciseBitmapSerdeFactory()}, new Object[]{new RoaringBitmapFactory(), RoaringBitmapSerdeFactory.getInstance()} - ); + ).stream(); } - public ExtractionDimFilterTest(BitmapFactory bitmapFactory, BitmapSerdeFactory bitmapSerdeFactory) + @Parameter(0) + public BitmapFactory factory; + @Parameter(1) + public BitmapSerdeFactory serdeFactory; + public ImmutableBitmap foo1BitMap; + + @BeforeEach + public void initFields() { - final MutableBitmap mutableBitmap = bitmapFactory.makeEmptyMutableBitmap(); + final MutableBitmap mutableBitmap = factory.makeEmptyMutableBitmap(); mutableBitmap.add(1); - this.foo1BitMap = bitmapFactory.makeImmutableBitmap(mutableBitmap); - this.factory = bitmapFactory; - this.serdeFactory = bitmapSerdeFactory; + foo1BitMap = factory.makeImmutableBitmap(mutableBitmap); } - private final BitmapFactory factory; - private final BitmapSerdeFactory serdeFactory; - private final ImmutableBitmap foo1BitMap; - private final ColumnIndexSelector BITMAP_INDEX_SELECTOR = new ColumnIndexSelector() { @Nullable @@ -171,7 +175,7 @@ public void testEmpty() { Filter extractionFilter = new SelectorDimFilter("foo", "NFDJUKFNDSJFNS", DIM_EXTRACTION_FN).toFilter(); ImmutableBitmap immutableBitmap = Filters.computeDefaultBitmapResults(extractionFilter, BITMAP_INDEX_SELECTOR); - Assert.assertEquals(0, immutableBitmap.size()); + Assertions.assertEquals(0, immutableBitmap.size()); } @Test @@ -179,7 +183,7 @@ public void testNull() { Filter extractionFilter = new SelectorDimFilter("FDHJSFFHDS", "extractDimVal", DIM_EXTRACTION_FN).toFilter(); ImmutableBitmap immutableBitmap = Filters.computeDefaultBitmapResults(extractionFilter, BITMAP_INDEX_SELECTOR); - Assert.assertEquals(0, immutableBitmap.size()); + Assertions.assertEquals(0, immutableBitmap.size()); } @Test @@ -187,13 +191,13 @@ public void testNormal() { Filter extractionFilter = new SelectorDimFilter("foo", "extractDimVal", DIM_EXTRACTION_FN).toFilter(); ImmutableBitmap immutableBitmap = Filters.computeDefaultBitmapResults(extractionFilter, BITMAP_INDEX_SELECTOR); - Assert.assertEquals(1, immutableBitmap.size()); + Assertions.assertEquals(1, immutableBitmap.size()); } @Test public void testOr() { - Assert.assertEquals( + Assertions.assertEquals( 1, Filters.computeDefaultBitmapResults( Filters.toFilter(DimFilters.or(new ExtractionDimFilter("foo", "extractDimVal", DIM_EXTRACTION_FN, null))), @@ -201,7 +205,7 @@ public void testOr() ).size() ); - Assert.assertEquals( + Assertions.assertEquals( 1, Filters.computeDefaultBitmapResults( Filters.toFilter( @@ -218,7 +222,7 @@ public void testOr() @Test public void testAnd() { - Assert.assertEquals( + Assertions.assertEquals( 1, Filters.computeDefaultBitmapResults( Filters.toFilter(DimFilters.or(new ExtractionDimFilter("foo", "extractDimVal", DIM_EXTRACTION_FN, null))), @@ -226,7 +230,7 @@ public void testAnd() ).size() ); - Assert.assertEquals( + Assertions.assertEquals( 1, Filters.computeDefaultBitmapResults( Filters.toFilter( @@ -244,7 +248,7 @@ public void testAnd() public void testNot() { - Assert.assertEquals( + Assertions.assertEquals( 1, Filters.computeDefaultBitmapResults( Filters.toFilter(DimFilters.or(new ExtractionDimFilter("foo", "extractDimVal", DIM_EXTRACTION_FN, null))), @@ -252,7 +256,7 @@ public void testNot() ).size() ); - Assert.assertEquals( + Assertions.assertEquals( 1, Filters.computeDefaultBitmapResults( Filters.toFilter(DimFilters.not(new ExtractionDimFilter("foo", "DOES NOT EXIST", DIM_EXTRACTION_FN, null))), diff --git a/processing/src/test/java/org/apache/druid/segment/join/JoinConditionAnalysisTest.java b/processing/src/test/java/org/apache/druid/segment/join/JoinConditionAnalysisTest.java index 7c77612a9ae5..48485cac415e 100644 --- a/processing/src/test/java/org/apache/druid/segment/join/JoinConditionAnalysisTest.java +++ b/processing/src/test/java/org/apache/druid/segment/join/JoinConditionAnalysisTest.java @@ -25,8 +25,8 @@ import org.apache.druid.java.util.common.Pair; import org.apache.druid.math.expr.Expr; import org.apache.druid.math.expr.ExprMacroTable; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; @@ -41,19 +41,19 @@ public void test_forExpression_simple() final String expression = "x == \"j.y\""; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertTrue(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertTrue(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(Pair.of("x", "y")), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of(), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y")); + Assertions.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y")); } @Test @@ -62,19 +62,19 @@ public void test_forExpression_simpleFlipped() final String expression = "\"j.y\" == x"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertTrue(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertTrue(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(Pair.of("x", "y")), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of(), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y")); + Assertions.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y")); } @Test @@ -83,19 +83,19 @@ public void test_forExpression_leftFunction() final String expression = "x + y == \"j.z\""; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertTrue(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertTrue(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(Pair.of("(+ x y)", "z")), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of(), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("z")); + Assertions.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("z")); } @Test @@ -104,19 +104,19 @@ public void test_forExpression_rightFunction() final String expression = "\"j.x\" + \"j.y\" == z"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertFalse(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertFalse(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of("(== (+ j.x j.y) z)"), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); + Assertions.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); } @Test @@ -125,19 +125,19 @@ public void test_forExpression_mixedFunction() final String expression = "x + \"j.y\" == \"j.z\""; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertFalse(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertFalse(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of("(== (+ x j.y) j.z)"), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); + Assertions.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); } @Test @@ -146,19 +146,19 @@ public void test_forExpression_trueConstant() final String expression = "1 + 1"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertTrue(analysis.canHashJoin()); - Assert.assertTrue(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertTrue(analysis.canHashJoin()); + Assertions.assertTrue(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of("2"), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); + Assertions.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); } @Test @@ -167,19 +167,19 @@ public void test_forExpression_falseConstant() final String expression = "0"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertTrue(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertTrue(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertTrue(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertTrue(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of("0"), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); + Assertions.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); } @Test @@ -188,19 +188,19 @@ public void test_forExpression_onlyLeft() final String expression = "x == 1"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertFalse(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertFalse(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of("(== x 1)"), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); + Assertions.assertTrue(analysis.getRightEquiConditionKeys().isEmpty()); } @Test @@ -209,19 +209,19 @@ public void test_forExpression_onlyRight() final String expression = "\"j.x\" == 1"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertTrue(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertTrue(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(Pair.of("1", "x")), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of(), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("x")); + Assertions.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("x")); } @Test @@ -230,19 +230,19 @@ public void test_forExpression_andOfThreeConditions() final String expression = "(x == \"j.y\") && (x + y == \"j.z\") && (z == \"j.zz\")"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertTrue(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertTrue(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(Pair.of("x", "y"), Pair.of("(+ x y)", "z"), Pair.of("z", "zz")), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of(), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y", "z", "zz")); + Assertions.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y", "z", "zz")); } @Test @@ -251,19 +251,19 @@ public void test_forExpression_mixedAndWithOr() final String expression = "(x == \"j.y\") && ((x + y == \"j.z\") || (z == \"j.zz\"))"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(expression, analysis.getOriginalExpression()); - Assert.assertFalse(analysis.canHashJoin()); - Assert.assertFalse(analysis.isAlwaysTrue()); - Assert.assertFalse(analysis.isAlwaysFalse()); - Assert.assertEquals( + Assertions.assertEquals(expression, analysis.getOriginalExpression()); + Assertions.assertFalse(analysis.canHashJoin()); + Assertions.assertFalse(analysis.isAlwaysTrue()); + Assertions.assertFalse(analysis.isAlwaysFalse()); + Assertions.assertEquals( ImmutableList.of(Pair.of("x", "y")), equalitiesToPairs(analysis.getEquiConditions()) ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableList.of("(|| (== (+ x y) j.z) (== z j.zz))"), exprsToStrings(analysis.getNonEquiConditions()) ); - Assert.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y")); + Assertions.assertEquals(analysis.getRightEquiConditionKeys(), ImmutableSet.of("y")); } @Test @@ -272,7 +272,7 @@ public void test_getRequiredColumns() final String expression = "(x == \"j.y\") && ((x + y == \"j.z\") || (z == \"j.zz\"))"; final JoinConditionAnalysis analysis = analyze(expression); - Assert.assertEquals(ImmutableSet.of("x", "j.y", "y", "j.z", "z", "j.zz"), analysis.getRequiredColumns()); + Assertions.assertEquals(ImmutableSet.of("x", "j.y", "y", "j.z", "z", "j.zz"), analysis.getRequiredColumns()); } @Test diff --git a/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java b/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java index f2b613e45a1b..5479379e31c6 100644 --- a/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java +++ b/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java @@ -29,10 +29,10 @@ import org.apache.druid.segment.column.ValueType; import org.apache.druid.segment.join.Joinable; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.Assert; -import org.junit.Before; import org.junit.Ignore; -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.Collections; import java.util.HashMap; @@ -50,7 +50,7 @@ public class LookupJoinableTest extends InitializedNullHandlingTest private LookupJoinable target; - @Before + @BeforeEach public void setUp() { final Map lookupMap = new HashMap<>(); @@ -69,8 +69,8 @@ public void setUp() public void getAvailableColumnShouldReturnOnlyTwoColumns() { List colummns = target.getAvailableColumns(); - Assert.assertEquals(2, colummns.size()); - Assert.assertEquals( + Assertions.assertEquals(2, colummns.size()); + Assertions.assertEquals( ImmutableList.of(LookupColumnSelectorFactory.KEY_COLUMN, LookupColumnSelectorFactory.VALUE_COLUMN), colummns ); @@ -80,42 +80,42 @@ public void getAvailableColumnShouldReturnOnlyTwoColumns() public void getCardinalityForUnknownColumnShouldReturnUnknown() { int cardinality = target.getCardinality(UNKNOWN_COLUMN); - Assert.assertEquals(Joinable.CARDINALITY_UNKNOWN, cardinality); + Assertions.assertEquals(Joinable.CARDINALITY_UNKNOWN, cardinality); } @Test public void getCardinalityForKeyColumnShouldReturnUnknown() { int cardinality = target.getCardinality(LookupColumnSelectorFactory.KEY_COLUMN); - Assert.assertEquals(Joinable.CARDINALITY_UNKNOWN, cardinality); + Assertions.assertEquals(Joinable.CARDINALITY_UNKNOWN, cardinality); } @Test public void getCardinalityForValueColumnShouldReturnUnknown() { int cardinality = target.getCardinality(LookupColumnSelectorFactory.VALUE_COLUMN); - Assert.assertEquals(Joinable.CARDINALITY_UNKNOWN, cardinality); + Assertions.assertEquals(Joinable.CARDINALITY_UNKNOWN, cardinality); } @Test public void getColumnCapabilitiesForKeyColumnShouldReturnStringCaps() { ColumnCapabilities capabilities = target.getColumnCapabilities(LookupColumnSelectorFactory.KEY_COLUMN); - Assert.assertEquals(ValueType.STRING, capabilities.getType()); + Assertions.assertEquals(ValueType.STRING, capabilities.getType()); } @Test public void getColumnCapabilitiesForValueColumnShouldReturnStringCaps() { ColumnCapabilities capabilities = target.getColumnCapabilities(LookupColumnSelectorFactory.VALUE_COLUMN); - Assert.assertEquals(ValueType.STRING, capabilities.getType()); + Assertions.assertEquals(ValueType.STRING, capabilities.getType()); } @Test public void getColumnCapabilitiesForUnknownColumnShouldReturnNull() { ColumnCapabilities capabilities = target.getColumnCapabilities(UNKNOWN_COLUMN); - Assert.assertNull(capabilities); + Assertions.assertNull(capabilities); } @Test @@ -130,7 +130,7 @@ public void getCorrelatedColummnValuesMissingSearchColumnShouldReturnEmptySet() false ); - Assert.assertFalse(correlatedValues.isPresent()); + Assertions.assertFalse(correlatedValues.isPresent()); } @Test @@ -145,7 +145,7 @@ public void getCorrelatedColummnValuesMissingRetrievalColumnShouldReturnEmptySet false ); - Assert.assertFalse(correlatedValues.isPresent()); + Assertions.assertFalse(correlatedValues.isPresent()); } @Test @@ -158,7 +158,7 @@ public void getCorrelatedColumnValuesForSearchKeyAndRetrieveKeyColumnShouldRetur 0, false ); - Assert.assertEquals(Optional.of(ImmutableSet.of(SEARCH_KEY_VALUE)), correlatedValues); + Assertions.assertEquals(Optional.of(ImmutableSet.of(SEARCH_KEY_VALUE)), correlatedValues); } @Test @@ -171,7 +171,7 @@ public void getCorrelatedColumnValuesForSearchKeyAndRetrieveValueColumnShouldRet 0, false ); - Assert.assertEquals(Optional.of(ImmutableSet.of(SEARCH_VALUE_VALUE)), correlatedValues); + Assertions.assertEquals(Optional.of(ImmutableSet.of(SEARCH_VALUE_VALUE)), correlatedValues); } @Test @@ -184,7 +184,7 @@ public void getCorrelatedColumnValuesForSearchKeyMissingAndRetrieveValueColumnSh 0, false ); - Assert.assertEquals(Optional.of(Collections.singleton(null)), correlatedValues); + Assertions.assertEquals(Optional.of(Collections.singleton(null)), correlatedValues); } @Test @@ -197,7 +197,7 @@ public void getCorrelatedColumnValuesForSearchValueAndRetrieveValueColumnAndNonK 10, false ); - Assert.assertEquals(Optional.empty(), correlatedValues); + Assertions.assertEquals(Optional.empty(), correlatedValues); correlatedValues = target.getCorrelatedColumnValues( LookupColumnSelectorFactory.VALUE_COLUMN, SEARCH_VALUE_VALUE, @@ -205,7 +205,7 @@ public void getCorrelatedColumnValuesForSearchValueAndRetrieveValueColumnAndNonK 10, false ); - Assert.assertEquals(Optional.empty(), correlatedValues); + Assertions.assertEquals(Optional.empty(), correlatedValues); } @Test @@ -218,7 +218,7 @@ public void getCorrelatedColumnValuesForSearchValueAndRetrieveValueColumnShouldR 0, true ); - Assert.assertEquals(Optional.of(ImmutableSet.of(SEARCH_VALUE_VALUE)), correlatedValues); + Assertions.assertEquals(Optional.of(ImmutableSet.of(SEARCH_VALUE_VALUE)), correlatedValues); } @Test @@ -231,7 +231,7 @@ public void getCorrelatedColumnValuesForSearchValueAndRetrieveKeyColumnShouldRet 10, true ); - Assert.assertEquals(Optional.of(ImmutableSet.of(SEARCH_KEY_VALUE)), correlatedValues); + Assertions.assertEquals(Optional.of(ImmutableSet.of(SEARCH_KEY_VALUE)), correlatedValues); } @Test @@ -249,7 +249,7 @@ public void getCorrelatedColumnValuesForSearchValueAndRetrieveKeyColumnWithMaxLi 0, true ); - Assert.assertEquals(Optional.empty(), correlatedValues); + Assertions.assertEquals(Optional.empty(), correlatedValues); } @Test @@ -262,7 +262,7 @@ public void getCorrelatedColumnValuesForSearchUnknownValueAndRetrieveKeyColumnSh 10, true ); - Assert.assertEquals(Optional.of(ImmutableSet.of()), correlatedValues); + Assertions.assertEquals(Optional.of(ImmutableSet.of()), correlatedValues); } @Test @@ -274,7 +274,7 @@ public void getMatchableColumnValuesIfAllUniqueForValueColumnShouldReturnEmpty() Integer.MAX_VALUE ); - Assert.assertEquals(ImmutableSet.of(), values.getColumnValues()); + Assertions.assertEquals(ImmutableSet.of(), values.getColumnValues()); } @Test @@ -286,7 +286,7 @@ public void getMatchableColumnValuesIfAllUniqueForKeyColumnShouldReturnValues() Integer.MAX_VALUE ); - Assert.assertEquals( + Assertions.assertEquals( ImmutableSet.of(SEARCH_KEY_VALUE, "foo", "bar", ""), values.getColumnValues() ); @@ -301,7 +301,7 @@ public void getMatchableColumnValuesWithIncludeNullIfAllUniqueForKeyColumnShould Integer.MAX_VALUE ); - Assert.assertEquals( + Assertions.assertEquals( Sets.newHashSet(SEARCH_KEY_VALUE, "foo", "bar", "", null), values.getColumnValues() ); @@ -316,6 +316,6 @@ public void getMatchableColumnValuesIfAllUniqueForKeyColumnWithLowMaxValuesShoul 1 ); - Assert.assertEquals(ImmutableSet.of(), values.getColumnValues()); + Assertions.assertEquals(ImmutableSet.of(), values.getColumnValues()); } } diff --git a/processing/src/test/java/org/apache/druid/segment/nested/ScalarDoubleColumnSupplierTest.java b/processing/src/test/java/org/apache/druid/segment/nested/ScalarDoubleColumnSupplierTest.java index 22d4d7650854..ff61782e5fb6 100644 --- a/processing/src/test/java/org/apache/druid/segment/nested/ScalarDoubleColumnSupplierTest.java +++ b/processing/src/test/java/org/apache/druid/segment/nested/ScalarDoubleColumnSupplierTest.java @@ -26,6 +26,7 @@ import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.druid.guice.BuiltInTypesModule; +import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.concurrent.Execs; import org.apache.druid.java.util.common.io.Closer; import org.apache.druid.java.util.common.io.smoosh.FileSmoosher; @@ -53,13 +54,12 @@ import org.apache.druid.segment.writeout.SegmentWriteOutMediumFactory; import org.apache.druid.segment.writeout.TmpFileSegmentWriteOutMediumFactory; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -80,8 +80,8 @@ public class ScalarDoubleColumnSupplierTest extends InitializedNullHandlingTest { private static final String NO_MATCH = "no"; - @Rule - public final TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + public File tempFolder; BitmapSerdeFactory bitmapSerdeFactory = RoaringBitmapSerdeFactory.getInstance(); DefaultBitmapResultFactory resultFactory = new DefaultBitmapResultFactory(bitmapSerdeFactory.getBitmapFactory()); @@ -101,17 +101,17 @@ public class ScalarDoubleColumnSupplierTest extends InitializedNullHandlingTest ByteBuffer baseBuffer; - @BeforeClass + @BeforeAll public static void staticSetup() { BuiltInTypesModule.registerHandlersAndSerde(); } - @Before + @BeforeEach public void setup() throws IOException { final String fileNameBase = "test"; - fileMapper = smooshify(fileNameBase, tempFolder.newFolder(), data); + fileMapper = smooshify(fileNameBase, FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir"), data); baseBuffer = fileMapper.mapFile(fileNameBase); } @@ -127,7 +127,7 @@ private SmooshedFileMapper smooshify( ScalarDoubleColumnSerializer serializer = new ScalarDoubleColumnSerializer( fileNameBase, NestedCommonFormatColumnFormatSpec.getEffectiveFormatSpec(null, IndexSpec.getDefault().getEffectiveSpec()), - writeOutMediumFactory.makeSegmentWriteOutMedium(tempFolder.newFolder()), + writeOutMediumFactory.makeSegmentWriteOutMedium(FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir")), closer ); @@ -149,7 +149,7 @@ private SmooshedFileMapper smooshify( SortedValueDictionary globalDictionarySortedCollector = mergable.getValueDictionary(); mergable.mergeFieldsInto(sortedFields); - serializer.openDictionaryWriter(tempFolder.newFolder()); + serializer.openDictionaryWriter(FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir")); serializer.serializeDictionaries( globalDictionarySortedCollector.getSortedStrings(), globalDictionarySortedCollector.getSortedLongs(), @@ -175,7 +175,7 @@ private SmooshedFileMapper smooshify( } } - @After + @AfterEach public void teardown() throws IOException { closer.close(); @@ -242,7 +242,7 @@ public void testConcurrency() throws ExecutionException, InterruptedException } threadsStartLatch.countDown(); Futures.allAsList(futures).get(); - Assert.assertEquals(expectedReason, failureReason.get()); + Assertions.assertEquals(expectedReason, failureReason.get()); } finally { executorService.shutdownNow(); @@ -262,7 +262,7 @@ private void smokeTest(ScalarDoubleColumnAndIndexSupplier supplier, ScalarDouble NullValueIndex nullValueIndex = supplier.as(NullValueIndex.class); SortedMap fields = column.getFieldTypeInfo(); - Assert.assertEquals( + Assertions.assertEquals( ImmutableMap.of(NestedPathFinder.JSON_PATH_ROOT, new FieldTypeInfo.MutableTypeSet().add(ColumnType.DOUBLE)), fields ); @@ -274,49 +274,49 @@ private void smokeTest(ScalarDoubleColumnAndIndexSupplier supplier, ScalarDouble // to take the null checking path if (row != null) { - Assert.assertEquals(row, valueSelector.getObject()); - Assert.assertEquals(row, valueSelector.getDouble(), 0.0); - Assert.assertFalse(valueSelector.isNull()); - Assert.assertEquals(row, vectorValueSelector.getDoubleVector()[0], 0.0); - Assert.assertEquals(row.longValue(), vectorValueSelector.getLongVector()[0]); - Assert.assertEquals(row.floatValue(), vectorValueSelector.getFloatVector()[0], 0.0); + Assertions.assertEquals(row, valueSelector.getObject()); + Assertions.assertEquals(row, valueSelector.getDouble(), 0.0); + Assertions.assertFalse(valueSelector.isNull()); + Assertions.assertEquals(row, vectorValueSelector.getDoubleVector()[0], 0.0); + Assertions.assertEquals(row.longValue(), vectorValueSelector.getLongVector()[0]); + Assertions.assertEquals(row.floatValue(), vectorValueSelector.getFloatVector()[0], 0.0); boolean[] nullVector = vectorValueSelector.getNullVector(); if (nullVector != null) { - Assert.assertFalse(nullVector[0]); + Assertions.assertFalse(nullVector[0]); } else { - Assert.assertNull(nullVector); + Assertions.assertNull(nullVector); } - Assert.assertTrue(valueSetIndex.forValue(String.valueOf(row)).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(valueIndexes.forValue(row, ColumnType.DOUBLE).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(String.valueOf(row)))) + Assertions.assertTrue(valueSetIndex.forValue(String.valueOf(row)).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(valueIndexes.forValue(row, ColumnType.DOUBLE).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(String.valueOf(row)))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(String.valueOf(row))) + Assertions.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(String.valueOf(row))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(NO_MATCH))) + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(NO_MATCH))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) + Assertions.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); } else { - Assert.assertNull(valueSelector.getObject()); - Assert.assertTrue(valueSelector.isNull()); - Assert.assertTrue(vectorValueSelector.getNullVector()[0]); - Assert.assertTrue(valueSetIndex.forValue(null).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(null)) + Assertions.assertNull(valueSelector.getObject()); + Assertions.assertTrue(valueSelector.isNull()); + Assertions.assertTrue(vectorValueSelector.getNullVector()[0]); + Assertions.assertTrue(valueSetIndex.forValue(null).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(null)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) .computeBitmapResult(resultFactory, false) .get(i)); } diff --git a/processing/src/test/java/org/apache/druid/segment/nested/ScalarLongColumnSupplierTest.java b/processing/src/test/java/org/apache/druid/segment/nested/ScalarLongColumnSupplierTest.java index 3af94680a05e..adb4f29ae8d4 100644 --- a/processing/src/test/java/org/apache/druid/segment/nested/ScalarLongColumnSupplierTest.java +++ b/processing/src/test/java/org/apache/druid/segment/nested/ScalarLongColumnSupplierTest.java @@ -26,6 +26,7 @@ import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.druid.guice.BuiltInTypesModule; +import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.concurrent.Execs; import org.apache.druid.java.util.common.io.Closer; import org.apache.druid.java.util.common.io.smoosh.FileSmoosher; @@ -53,13 +54,12 @@ import org.apache.druid.segment.writeout.SegmentWriteOutMediumFactory; import org.apache.druid.segment.writeout.TmpFileSegmentWriteOutMediumFactory; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -80,8 +80,8 @@ public class ScalarLongColumnSupplierTest extends InitializedNullHandlingTest { private static final String NO_MATCH = "no"; - @Rule - public final TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + public File tempFolder; BitmapSerdeFactory bitmapSerdeFactory = RoaringBitmapSerdeFactory.getInstance(); DefaultBitmapResultFactory resultFactory = new DefaultBitmapResultFactory(bitmapSerdeFactory.getBitmapFactory()); @@ -101,17 +101,17 @@ public class ScalarLongColumnSupplierTest extends InitializedNullHandlingTest ByteBuffer baseBuffer; - @BeforeClass + @BeforeAll public static void staticSetup() { BuiltInTypesModule.registerHandlersAndSerde(); } - @Before + @BeforeEach public void setup() throws IOException { final String fileNameBase = "test"; - fileMapper = smooshify(fileNameBase, tempFolder.newFolder(), data); + fileMapper = smooshify(fileNameBase, FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir"), data); baseBuffer = fileMapper.mapFile(fileNameBase); } @@ -127,7 +127,7 @@ private SmooshedFileMapper smooshify( ScalarLongColumnSerializer serializer = new ScalarLongColumnSerializer( fileNameBase, NestedCommonFormatColumnFormatSpec.getEffectiveFormatSpec(null, IndexSpec.getDefault().getEffectiveSpec()), - writeOutMediumFactory.makeSegmentWriteOutMedium(tempFolder.newFolder()), + writeOutMediumFactory.makeSegmentWriteOutMedium(FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir")), closer ); @@ -149,7 +149,7 @@ private SmooshedFileMapper smooshify( SortedValueDictionary globalDictionarySortedCollector = mergable.getValueDictionary(); mergable.mergeFieldsInto(sortedFields); - serializer.openDictionaryWriter(tempFolder.newFolder()); + serializer.openDictionaryWriter(FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir")); serializer.serializeDictionaries( globalDictionarySortedCollector.getSortedStrings(), globalDictionarySortedCollector.getSortedLongs(), @@ -175,7 +175,7 @@ private SmooshedFileMapper smooshify( } } - @After + @AfterEach public void teardown() throws IOException { closer.close(); @@ -242,7 +242,7 @@ public void testConcurrency() throws ExecutionException, InterruptedException } threadsStartLatch.countDown(); Futures.allAsList(futures).get(); - Assert.assertEquals(expectedReason, failureReason.get()); + Assertions.assertEquals(expectedReason, failureReason.get()); } finally { executorService.shutdownNow(); @@ -262,7 +262,7 @@ private void smokeTest(ScalarLongColumnAndIndexSupplier supplier, ScalarLongColu NullValueIndex nullValueIndex = supplier.as(NullValueIndex.class); SortedMap fields = column.getFieldTypeInfo(); - Assert.assertEquals( + Assertions.assertEquals( ImmutableMap.of(NestedPathFinder.JSON_PATH_ROOT, new FieldTypeInfo.MutableTypeSet().add(ColumnType.LONG)), fields ); @@ -274,49 +274,49 @@ private void smokeTest(ScalarLongColumnAndIndexSupplier supplier, ScalarLongColu // to take the null checking path if (row != null) { - Assert.assertEquals(row, valueSelector.getObject()); - Assert.assertEquals((long) row, valueSelector.getLong()); - Assert.assertFalse(valueSelector.isNull()); - Assert.assertEquals((long) row, vectorValueSelector.getLongVector()[0]); - Assert.assertEquals(row.doubleValue(), vectorValueSelector.getDoubleVector()[0], 0.0); - Assert.assertEquals(row.floatValue(), vectorValueSelector.getFloatVector()[0], 0.0); + Assertions.assertEquals(row, valueSelector.getObject()); + Assertions.assertEquals((long) row, valueSelector.getLong()); + Assertions.assertFalse(valueSelector.isNull()); + Assertions.assertEquals((long) row, vectorValueSelector.getLongVector()[0]); + Assertions.assertEquals(row.doubleValue(), vectorValueSelector.getDoubleVector()[0], 0.0); + Assertions.assertEquals(row.floatValue(), vectorValueSelector.getFloatVector()[0], 0.0); boolean[] nullVector = vectorValueSelector.getNullVector(); if (nullVector != null) { - Assert.assertFalse(nullVector[0]); + Assertions.assertFalse(nullVector[0]); } else { - Assert.assertNull(nullVector); + Assertions.assertNull(nullVector); } - Assert.assertTrue(valueSetIndex.forValue(String.valueOf(row)).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(valueIndexes.forValue(row, ColumnType.LONG).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(String.valueOf(row)))) + Assertions.assertTrue(valueSetIndex.forValue(String.valueOf(row)).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(valueIndexes.forValue(row, ColumnType.LONG).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(String.valueOf(row)))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(String.valueOf(row))) + Assertions.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(String.valueOf(row))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(NO_MATCH))) + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(valueSetIndex.forSortedValues(new TreeSet<>(ImmutableSet.of(NO_MATCH))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) + Assertions.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); } else { - Assert.assertNull(valueSelector.getObject()); - Assert.assertTrue(valueSelector.isNull()); - Assert.assertTrue(vectorValueSelector.getNullVector()[0]); - Assert.assertTrue(valueSetIndex.forValue(null).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(null)) + Assertions.assertNull(valueSelector.getObject()); + Assertions.assertTrue(valueSelector.isNull()); + Assertions.assertTrue(vectorValueSelector.getNullVector()[0]); + Assertions.assertTrue(valueSetIndex.forValue(null).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(null)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) .computeBitmapResult(resultFactory, false) .get(i)); } diff --git a/processing/src/test/java/org/apache/druid/segment/nested/ScalarStringColumnSupplierTest.java b/processing/src/test/java/org/apache/druid/segment/nested/ScalarStringColumnSupplierTest.java index 77470b77fc59..c7bfaebca33c 100644 --- a/processing/src/test/java/org/apache/druid/segment/nested/ScalarStringColumnSupplierTest.java +++ b/processing/src/test/java/org/apache/druid/segment/nested/ScalarStringColumnSupplierTest.java @@ -26,6 +26,7 @@ import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.apache.druid.guice.BuiltInTypesModule; +import org.apache.druid.java.util.common.FileUtils; import org.apache.druid.java.util.common.concurrent.Execs; import org.apache.druid.java.util.common.io.Closer; import org.apache.druid.java.util.common.io.smoosh.FileSmoosher; @@ -54,13 +55,12 @@ import org.apache.druid.segment.writeout.SegmentWriteOutMediumFactory; import org.apache.druid.segment.writeout.TmpFileSegmentWriteOutMediumFactory; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; @@ -80,8 +80,8 @@ public class ScalarStringColumnSupplierTest extends InitializedNullHandlingTest { private static final String NO_MATCH = "no"; - @Rule - public final TemporaryFolder tempFolder = new TemporaryFolder(); + @TempDir + public File tempFolder; BitmapSerdeFactory bitmapSerdeFactory = RoaringBitmapSerdeFactory.getInstance(); DefaultBitmapResultFactory resultFactory = new DefaultBitmapResultFactory(bitmapSerdeFactory.getBitmapFactory()); @@ -101,17 +101,17 @@ public class ScalarStringColumnSupplierTest extends InitializedNullHandlingTest ByteBuffer baseBuffer; - @BeforeClass + @BeforeAll public static void staticSetup() { BuiltInTypesModule.registerHandlersAndSerde(); } - @Before + @BeforeEach public void setup() throws IOException { final String fileNameBase = "test"; - fileMapper = smooshify(fileNameBase, tempFolder.newFolder(), data); + fileMapper = smooshify(fileNameBase, FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir"), data); baseBuffer = fileMapper.mapFile(fileNameBase); } @@ -127,7 +127,7 @@ private SmooshedFileMapper smooshify( ScalarStringColumnSerializer serializer = new ScalarStringColumnSerializer( fileNameBase, NestedCommonFormatColumnFormatSpec.getEffectiveFormatSpec(null, IndexSpec.getDefault().getEffectiveSpec()), - writeOutMediumFactory.makeSegmentWriteOutMedium(tempFolder.newFolder()), + writeOutMediumFactory.makeSegmentWriteOutMedium(FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir")), closer ); @@ -149,7 +149,7 @@ private SmooshedFileMapper smooshify( SortedValueDictionary globalDictionarySortedCollector = mergable.getValueDictionary(); mergable.mergeFieldsInto(sortedFields); - serializer.openDictionaryWriter(tempFolder.newFolder()); + serializer.openDictionaryWriter(FileUtils.createTempDirInLocation(tempFolder.toPath(), "dir")); serializer.serializeDictionaries( globalDictionarySortedCollector.getSortedStrings(), globalDictionarySortedCollector.getSortedLongs(), @@ -175,7 +175,7 @@ private SmooshedFileMapper smooshify( } } - @After + @AfterEach public void teardown() throws IOException { closer.close(); @@ -240,7 +240,7 @@ public void testConcurrency() throws ExecutionException, InterruptedException } threadsStartLatch.countDown(); Futures.allAsList(futures).get(); - Assert.assertEquals(expectedReason, failureReason.get()); + Assertions.assertEquals(expectedReason, failureReason.get()); } finally { executorService.shutdownNow(); @@ -259,61 +259,61 @@ private void smokeTest(ScalarStringColumnAndIndexSupplier supplier, StringUtf8Di NullValueIndex nullValueIndex = supplier.as(NullValueIndex.class); SortedMap fields = column.getFieldTypeInfo(); - Assert.assertEquals(ImmutableMap.of(NestedPathFinder.JSON_PATH_ROOT, new FieldTypeInfo.MutableTypeSet().add(ColumnType.STRING)), fields); + Assertions.assertEquals(ImmutableMap.of(NestedPathFinder.JSON_PATH_ROOT, new FieldTypeInfo.MutableTypeSet().add(ColumnType.STRING)), fields); for (int i = 0; i < data.size(); i++) { String row = data.get(i); if (row != null) { - Assert.assertEquals(row, valueSelector.getObject()); - Assert.assertEquals(row, dimSelector.getObject()); + Assertions.assertEquals(row, valueSelector.getObject()); + Assertions.assertEquals(row, dimSelector.getObject()); String dimSelectorLookupVal = dimSelector.lookupName(dimSelector.getRow().get(0)); - Assert.assertEquals(row, dimSelectorLookupVal); - Assert.assertEquals(dimSelector.idLookup().lookupId(dimSelectorLookupVal), dimSelector.getRow().get(0)); + Assertions.assertEquals(row, dimSelectorLookupVal); + Assertions.assertEquals(dimSelector.idLookup().lookupId(dimSelectorLookupVal), dimSelector.getRow().get(0)); - Assert.assertTrue(valueSetIndex.forValue(row).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(valueIndexes.forValue(row, ColumnType.STRING).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(valueSetIndex.forSortedValues(InDimFilter.ValuesSet.copyOf(ImmutableSet.of(row))) + Assertions.assertTrue(valueSetIndex.forValue(row).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(valueIndexes.forValue(row, ColumnType.STRING).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(valueSetIndex.forSortedValues(InDimFilter.ValuesSet.copyOf(ImmutableSet.of(row))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(row)) + Assertions.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(row)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(valueSetIndex.forSortedValues(InDimFilter.ValuesSet.copyOf(ImmutableSet.of(NO_MATCH))) + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(valueSetIndex.forSortedValues(InDimFilter.ValuesSet.copyOf(ImmutableSet.of(NO_MATCH))) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) + Assertions.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(dimSelector.makeValueMatcher(row).matches(false)); - Assert.assertFalse(dimSelector.makeValueMatcher(NO_MATCH).matches(false)); - Assert.assertTrue(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(row)).matches(false)); - Assert.assertFalse(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(NO_MATCH)).matches(false)); + Assertions.assertTrue(dimSelector.makeValueMatcher(row).matches(false)); + Assertions.assertFalse(dimSelector.makeValueMatcher(NO_MATCH).matches(false)); + Assertions.assertTrue(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(row)).matches(false)); + Assertions.assertFalse(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(NO_MATCH)).matches(false)); } else { - Assert.assertNull(valueSelector.getObject()); + Assertions.assertNull(valueSelector.getObject()); - Assert.assertEquals(0, dimSelector.getRow().get(0)); - Assert.assertNull(dimSelector.getObject()); - Assert.assertNull(dimSelector.lookupName(dimSelector.getRow().get(0))); + Assertions.assertEquals(0, dimSelector.getRow().get(0)); + Assertions.assertNull(dimSelector.getObject()); + Assertions.assertNull(dimSelector.lookupName(dimSelector.getRow().get(0))); - Assert.assertTrue(valueSetIndex.forValue(null).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); - Assert.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(null)) + Assertions.assertTrue(valueSetIndex.forValue(null).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(nullValueIndex.get().computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertTrue(predicateIndex.forPredicate(new SelectorPredicateFactory(null)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); - Assert.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) + Assertions.assertFalse(valueSetIndex.forValue(NO_MATCH).computeBitmapResult(resultFactory, false).get(i)); + Assertions.assertFalse(predicateIndex.forPredicate(new SelectorPredicateFactory(NO_MATCH)) .computeBitmapResult(resultFactory, false) .get(i)); - Assert.assertTrue(dimSelector.makeValueMatcher((String) null).matches(false)); - Assert.assertFalse(dimSelector.makeValueMatcher(NO_MATCH).matches(false)); - Assert.assertTrue(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(null)).matches(false)); - Assert.assertFalse(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(NO_MATCH)).matches(false)); + Assertions.assertTrue(dimSelector.makeValueMatcher((String) null).matches(false)); + Assertions.assertFalse(dimSelector.makeValueMatcher(NO_MATCH).matches(false)); + Assertions.assertTrue(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(null)).matches(false)); + Assertions.assertFalse(dimSelector.makeValueMatcher(StringPredicateDruidPredicateFactory.equalTo(NO_MATCH)).matches(false)); } offset.increment(); diff --git a/processing/src/test/java/org/apache/druid/segment/vector/QueryableIndexVectorColumnSelectorFactoryTest.java b/processing/src/test/java/org/apache/druid/segment/vector/QueryableIndexVectorColumnSelectorFactoryTest.java index b506bd72ceeb..738be8c95d7d 100644 --- a/processing/src/test/java/org/apache/druid/segment/vector/QueryableIndexVectorColumnSelectorFactoryTest.java +++ b/processing/src/test/java/org/apache/druid/segment/vector/QueryableIndexVectorColumnSelectorFactoryTest.java @@ -45,13 +45,13 @@ import org.apache.druid.segment.incremental.IncrementalIndexSchema; import org.apache.druid.segment.writeout.OffHeapMemorySegmentWriteOutMediumFactory; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; @@ -120,20 +120,20 @@ private static Map makeRow( return row; } - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder; Closer closer; ColumnCache theCache; QueryableIndex index; - @Before + @BeforeEach public void setup() throws IOException { closer = Closer.create(); index = IndexBuilder.create(TestHelper.makeJsonMapper()) - .tmpDir(temporaryFolder.newFolder()) + .tmpDir(temporaryFolder) .segmentWriteOutMediumFactory(OffHeapMemorySegmentWriteOutMediumFactory.instance()) .schema( new IncrementalIndexSchema.Builder() @@ -151,7 +151,7 @@ public void setup() throws IOException theCache = new ColumnCache(index, VirtualColumns.EMPTY, closer); } - @After + @AfterEach public void teardown() throws IOException { closer.close(); @@ -168,11 +168,20 @@ public void testSingleValueSelector() ); // cannot make single value selector on multi-value string - Assert.assertThrows(ISE.class, () -> factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(MULTI_STRING))); + Assertions.assertThrows(ISE.class, () -> factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(MULTI_STRING))); // we make nil selectors for number columns though - Assert.assertTrue(factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(DOUBLE)) instanceof NilVectorSelector); - Assert.assertTrue(factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(FLOAT)) instanceof NilVectorSelector); - Assert.assertTrue(factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(LONG)) instanceof NilVectorSelector); + Assertions.assertInstanceOf( + NilVectorSelector.class, + factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(DOUBLE)) + ); + Assertions.assertInstanceOf( + NilVectorSelector.class, + factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(FLOAT)) + ); + Assertions.assertInstanceOf( + NilVectorSelector.class, + factory.makeSingleValueDimensionSelector(DefaultDimensionSpec.of(LONG)) + ); // but we can for real multi-value strings SingleValueDimensionVectorSelector vectorSelector = factory.makeSingleValueDimensionSelector( @@ -184,14 +193,14 @@ public void testSingleValueSelector() int rowCounter = 0; while (!offset.isDone()) { int[] ints = vectorSelector.getRowVector(); - Assert.assertNotNull(ints); + Assertions.assertNotNull(ints); for (int i = 0; i < vectorSelector.getCurrentVectorSize(); i++) { - Assert.assertEquals(RAW_ROWS.get(rowCounter + i).get(STRING), vectorSelector.lookupName(ints[i])); + Assertions.assertEquals(RAW_ROWS.get(rowCounter + i).get(STRING), vectorSelector.lookupName(ints[i])); } Object[] objects = objectSelector.getObjectVector(); for (int i = 0; i < vectorSelector.getCurrentVectorSize(); i++) { - Assert.assertEquals("row " + i, RAW_ROWS.get(rowCounter + i).get(STRING), objects[i]); + Assertions.assertEquals(RAW_ROWS.get(rowCounter + i).get(STRING), objects[i], "row " + i); } rowCounter += objectSelector.getCurrentVectorSize(); offset.advance(); @@ -209,10 +218,10 @@ public void testMultiValueSelector() ); // cannot make these for anything except for multi-value strings - Assert.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(STRING))); - Assert.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(DOUBLE))); - Assert.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(FLOAT))); - Assert.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(LONG))); + Assertions.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(STRING))); + Assertions.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(DOUBLE))); + Assertions.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(FLOAT))); + Assertions.assertThrows(ISE.class, () -> factory.makeMultiValueDimensionSelector(DefaultDimensionSpec.of(LONG))); // but we can for real multi-value strings MultiValueDimensionVectorSelector vectorSelector = factory.makeMultiValueDimensionSelector( @@ -224,25 +233,25 @@ public void testMultiValueSelector() int rowCounter = 0; while (!offset.isDone()) { IndexedInts[] indexedInts = vectorSelector.getRowVector(); - Assert.assertNotNull(indexedInts); + Assertions.assertNotNull(indexedInts); for (int i = 0; i < vectorSelector.getCurrentVectorSize(); i++) { IndexedInts currentRow = indexedInts[i]; if (currentRow.size() == 0) { - Assert.assertNull(RAW_ROWS.get(rowCounter + i).get(MULTI_STRING)); + Assertions.assertNull(RAW_ROWS.get(rowCounter + i).get(MULTI_STRING)); } else if (currentRow.size() == 1) { - Assert.assertEquals(RAW_ROWS.get(rowCounter + i).get(MULTI_STRING), vectorSelector.lookupName(currentRow.get(0))); + Assertions.assertEquals(RAW_ROWS.get(rowCounter + i).get(MULTI_STRING), vectorSelector.lookupName(currentRow.get(0))); } else { // noinspection SSBasedInspection for (int j = 0; j < currentRow.size(); j++) { List expected = (List) RAW_ROWS.get(rowCounter + i).get(MULTI_STRING); - Assert.assertEquals(expected.get(j), vectorSelector.lookupName(currentRow.get(j))); + Assertions.assertEquals(expected.get(j), vectorSelector.lookupName(currentRow.get(j))); } } } Object[] objects = objectSelector.getObjectVector(); for (int i = 0; i < vectorSelector.getCurrentVectorSize(); i++) { - Assert.assertEquals("row " + i, RAW_ROWS.get(rowCounter + i).get(MULTI_STRING), objects[i]); + Assertions.assertEquals(RAW_ROWS.get(rowCounter + i).get(MULTI_STRING), objects[i], "row " + i); } rowCounter += objectSelector.getCurrentVectorSize(); offset.advance(); @@ -260,8 +269,8 @@ public void testNumericSelectors() ); // cannot make these for anything except for multi-value strings - Assert.assertThrows(UOE.class, () -> factory.makeValueSelector(STRING)); - Assert.assertThrows(UOE.class, () -> factory.makeValueSelector(MULTI_STRING)); + Assertions.assertThrows(UOE.class, () -> factory.makeValueSelector(STRING)); + Assertions.assertThrows(UOE.class, () -> factory.makeValueSelector(MULTI_STRING)); VectorValueSelector doubleSelector = factory.makeValueSelector(DOUBLE); VectorValueSelector floatSelector = factory.makeValueSelector(FLOAT); @@ -274,12 +283,12 @@ public void testNumericSelectors() for (int i = 0; i < doubleSelector.getCurrentVectorSize(); i++) { final Object raw = RAW_ROWS.get(rowCounter + i).get(DOUBLE); if (doubleNulls != null && doubleNulls[i]) { - Assert.assertNull(raw); + Assertions.assertNull(raw); } else { if (raw == null) { - Assert.assertEquals(0.0, doubles[i], 0.0); + Assertions.assertEquals(0.0, doubles[i], 0.0); } else { - Assert.assertEquals((double) raw, doubles[i], 0.0); + Assertions.assertEquals((double) raw, doubles[i], 0.0); } } } @@ -289,12 +298,12 @@ public void testNumericSelectors() for (int i = 0; i < floatSelector.getCurrentVectorSize(); i++) { final Object raw = RAW_ROWS.get(rowCounter + i).get(FLOAT); if (floatNulls != null && floatNulls[i]) { - Assert.assertNull(raw); + Assertions.assertNull(raw); } else { if (raw == null) { - Assert.assertEquals(0.0f, floats[i], 0.0); + Assertions.assertEquals(0.0f, floats[i], 0.0); } else { - Assert.assertEquals((float) raw, floats[i], 0.0); + Assertions.assertEquals((float) raw, floats[i], 0.0); } } } @@ -304,12 +313,12 @@ public void testNumericSelectors() for (int i = 0; i < longSelector.getCurrentVectorSize(); i++) { final Object raw = RAW_ROWS.get(rowCounter + i).get(LONG); if (longNulls != null && longNulls[i]) { - Assert.assertNull(raw); + Assertions.assertNull(raw); } else { if (raw == null) { - Assert.assertEquals(0L, longs[i], 0.0); + Assertions.assertEquals(0L, longs[i], 0.0); } else { - Assert.assertEquals((long) raw, longs[i]); + Assertions.assertEquals((long) raw, longs[i]); } } } diff --git a/processing/src/test/java/org/apache/druid/segment/virtual/ListFilteredVirtualColumnSelectorTest.java b/processing/src/test/java/org/apache/druid/segment/virtual/ListFilteredVirtualColumnSelectorTest.java index 3337729b4e35..a9d2ca1f76f6 100644 --- a/processing/src/test/java/org/apache/druid/segment/virtual/ListFilteredVirtualColumnSelectorTest.java +++ b/processing/src/test/java/org/apache/druid/segment/virtual/ListFilteredVirtualColumnSelectorTest.java @@ -47,8 +47,8 @@ import org.apache.druid.segment.index.semantic.DictionaryEncodedStringValueIndex; import org.apache.druid.testing.InitializedNullHandlingTest; 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 java.io.IOException; @@ -76,7 +76,7 @@ public void testListFilteredVirtualColumnNilDimensionSelector() VirtualizedColumnSelectorFactory selectorFactory = makeSelectorFactory(virtualColumn); DimensionSelector selector = selectorFactory.makeDimensionSelector(DefaultDimensionSpec.of(ALLOW_VIRTUAL_NAME)); - Assert.assertNull(selector.getObject()); + Assertions.assertNull(selector.getObject()); } @Test @@ -91,7 +91,7 @@ public void testListFilteredVirtualColumnNilColumnValueSelector() VirtualizedColumnSelectorFactory selectorFactory = makeSelectorFactory(virtualColumn); ColumnValueSelector selector = selectorFactory.makeColumnValueSelector(ALLOW_VIRTUAL_NAME); - Assert.assertNull(selector.getObject()); + Assertions.assertNull(selector.getObject()); } @@ -107,7 +107,7 @@ public void testListFilteredVirtualColumnAllowListDimensionSelector() VirtualizedColumnSelectorFactory selectorFactory = makeSelectorFactory(virtualColumn); DimensionSelector selector = selectorFactory.makeDimensionSelector(DefaultDimensionSpec.of(ALLOW_VIRTUAL_NAME)); - Assert.assertEquals(ImmutableList.of("a", "b"), selector.getObject()); + Assertions.assertEquals(ImmutableList.of("a", "b"), selector.getObject()); assertCapabilities(selectorFactory, ALLOW_VIRTUAL_NAME); } @@ -123,7 +123,7 @@ public void testListFilteredVirtualColumnAllowListColumnValueSelector() VirtualizedColumnSelectorFactory selectorFactory = makeSelectorFactory(virtualColumn); ColumnValueSelector selector = selectorFactory.makeColumnValueSelector(ALLOW_VIRTUAL_NAME); - Assert.assertEquals(ImmutableList.of("a", "b"), selector.getObject()); + Assertions.assertEquals(ImmutableList.of("a", "b"), selector.getObject()); assertCapabilities(selectorFactory, ALLOW_VIRTUAL_NAME); } @@ -139,7 +139,7 @@ public void testListFilteredVirtualColumnDenyListDimensionSelector() VirtualizedColumnSelectorFactory selectorFactory = makeSelectorFactory(virtualColumn); DimensionSelector selector = selectorFactory.makeDimensionSelector(DefaultDimensionSpec.of(DENY_VIRTUAL_NAME)); - Assert.assertEquals(ImmutableList.of("c", "d"), selector.getObject()); + Assertions.assertEquals(ImmutableList.of("c", "d"), selector.getObject()); assertCapabilities(selectorFactory, DENY_VIRTUAL_NAME); } @@ -155,7 +155,7 @@ public void testListFilteredVirtualColumnDenyListColumnValueSelector() VirtualizedColumnSelectorFactory selectorFactory = makeSelectorFactory(virtualColumn); ColumnValueSelector selector = selectorFactory.makeColumnValueSelector(DENY_VIRTUAL_NAME); - Assert.assertEquals(ImmutableList.of("c", "d"), selector.getObject()); + Assertions.assertEquals(ImmutableList.of("c", "d"), selector.getObject()); assertCapabilities(selectorFactory, DENY_VIRTUAL_NAME); } @@ -209,14 +209,14 @@ public void testFilterListFilteredVirtualColumnAllowIndex() throws IOException ); SelectorFilter filter = new SelectorFilter(ALLOW_VIRTUAL_NAME, "a"); - Assert.assertNotNull(filter.getBitmapColumnIndex(bitmapIndexSelector)); + Assertions.assertNotNull(filter.getBitmapColumnIndex(bitmapIndexSelector)); DictionaryEncodedStringValueIndex listFilteredIndex = bitmapIndexSelector.getIndexSupplier(ALLOW_VIRTUAL_NAME).as(DictionaryEncodedStringValueIndex.class); - Assert.assertEquals(2, listFilteredIndex.getCardinality()); - Assert.assertEquals("b", listFilteredIndex.getValue(0)); - Assert.assertEquals("c", listFilteredIndex.getValue(1)); - Assert.assertEquals(bitmap, listFilteredIndex.getBitmap(1)); + Assertions.assertEquals(2, listFilteredIndex.getCardinality()); + Assertions.assertEquals("b", listFilteredIndex.getValue(0)); + Assertions.assertEquals("c", listFilteredIndex.getValue(1)); + Assertions.assertEquals(bitmap, listFilteredIndex.getBitmap(1)); EasyMock.verify(queryableIndex, holder, timeHolder, indexSupplier, index, bitmap, bitmapFactory); } @@ -270,12 +270,12 @@ public void testFilterListFilteredVirtualColumnDenyIndex() ); SelectorFilter filter = new SelectorFilter(DENY_VIRTUAL_NAME, "c"); - Assert.assertNotNull(filter.getBitmapColumnIndex(bitmapIndexSelector)); + Assertions.assertNotNull(filter.getBitmapColumnIndex(bitmapIndexSelector)); DictionaryEncodedStringValueIndex listFilteredIndex = bitmapIndexSelector.getIndexSupplier(DENY_VIRTUAL_NAME).as(DictionaryEncodedStringValueIndex.class); - Assert.assertEquals(1, listFilteredIndex.getCardinality()); - Assert.assertEquals(bitmap, listFilteredIndex.getBitmap(1)); + Assertions.assertEquals(1, listFilteredIndex.getCardinality()); + Assertions.assertEquals(bitmap, listFilteredIndex.getBitmap(1)); EasyMock.verify(queryableIndex, holder, timeHolder, indexSupplier, index, bitmap, bitmapFactory); } @@ -287,9 +287,9 @@ public void testFilterListFilteredVirtualColumnDenyIndex() private void assertCapabilities(VirtualizedColumnSelectorFactory selectorFactory, String columnName) { ColumnCapabilities capabilities = selectorFactory.getColumnCapabilities(columnName); - Assert.assertNotNull(capabilities); - Assert.assertEquals(ValueType.STRING, capabilities.getType()); - Assert.assertTrue(capabilities.hasMultipleValues().isMaybeTrue()); + Assertions.assertNotNull(capabilities); + Assertions.assertEquals(ValueType.STRING, capabilities.getType()); + Assertions.assertTrue(capabilities.hasMultipleValues().isMaybeTrue()); } private VirtualizedColumnSelectorFactory makeSelectorFactory(ListFilteredVirtualColumn virtualColumn) diff --git a/processing/src/test/java/org/apache/druid/timeline/partition/NumberedShardSpecTest.java b/processing/src/test/java/org/apache/druid/timeline/partition/NumberedShardSpecTest.java index 12b737211e32..cc837ef99d17 100644 --- a/processing/src/test/java/org/apache/druid/timeline/partition/NumberedShardSpecTest.java +++ b/processing/src/test/java/org/apache/druid/timeline/partition/NumberedShardSpecTest.java @@ -31,8 +31,8 @@ import org.apache.druid.timeline.TimelineObjectHolder; import org.apache.druid.timeline.VersionedIntervalTimeline; import org.joda.time.Interval; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashSet; @@ -56,9 +56,9 @@ public void testSerdeRoundTrip() throws Exception objectMapper.writeValueAsBytes(new NumberedShardSpec(1, 2)), ShardSpec.class ); - Assert.assertEquals(1, spec.getPartitionNum()); - Assert.assertEquals(2, spec.getNumCorePartitions()); - Assert.assertEquals(ShardSpec.Type.NUMBERED, spec.getType()); + Assertions.assertEquals(1, spec.getPartitionNum()); + Assertions.assertEquals(2, spec.getNumCorePartitions()); + Assertions.assertEquals(ShardSpec.Type.NUMBERED, spec.getType()); } @Test @@ -69,8 +69,8 @@ public void testSerdeBackwardsCompat() throws Exception "{\"type\": \"numbered\", \"partitions\": 2, \"partitionNum\": 1}", ShardSpec.class ); - Assert.assertEquals(1, spec.getPartitionNum()); - Assert.assertEquals(2, spec.getNumCorePartitions()); + Assertions.assertEquals(1, spec.getPartitionNum()); + Assertions.assertEquals(2, spec.getNumCorePartitions()); } @Test @@ -94,28 +94,28 @@ public PartitionChunk apply(ShardSpec shardSpec) } ); - Assert.assertEquals(0, chunks.get(0).getChunkNumber()); - Assert.assertEquals(1, chunks.get(1).getChunkNumber()); - Assert.assertEquals(2, chunks.get(2).getChunkNumber()); + Assertions.assertEquals(0, chunks.get(0).getChunkNumber()); + Assertions.assertEquals(1, chunks.get(1).getChunkNumber()); + Assertions.assertEquals(2, chunks.get(2).getChunkNumber()); - Assert.assertTrue(chunks.get(0).isStart()); - Assert.assertFalse(chunks.get(1).isStart()); - Assert.assertFalse(chunks.get(2).isStart()); + Assertions.assertTrue(chunks.get(0).isStart()); + Assertions.assertFalse(chunks.get(1).isStart()); + Assertions.assertFalse(chunks.get(2).isStart()); - Assert.assertFalse(chunks.get(0).isEnd()); - Assert.assertFalse(chunks.get(1).isEnd()); - Assert.assertTrue(chunks.get(2).isEnd()); + Assertions.assertFalse(chunks.get(0).isEnd()); + Assertions.assertFalse(chunks.get(1).isEnd()); + Assertions.assertTrue(chunks.get(2).isEnd()); - Assert.assertTrue(chunks.get(0).abuts(chunks.get(1))); - Assert.assertTrue(chunks.get(1).abuts(chunks.get(2))); + Assertions.assertTrue(chunks.get(0).abuts(chunks.get(1))); + Assertions.assertTrue(chunks.get(1).abuts(chunks.get(2))); - Assert.assertFalse(chunks.get(0).abuts(chunks.get(0))); - Assert.assertFalse(chunks.get(0).abuts(chunks.get(2))); - Assert.assertFalse(chunks.get(1).abuts(chunks.get(0))); - Assert.assertFalse(chunks.get(1).abuts(chunks.get(1))); - Assert.assertFalse(chunks.get(2).abuts(chunks.get(0))); - Assert.assertFalse(chunks.get(2).abuts(chunks.get(1))); - Assert.assertFalse(chunks.get(2).abuts(chunks.get(2))); + Assertions.assertFalse(chunks.get(0).abuts(chunks.get(0))); + Assertions.assertFalse(chunks.get(0).abuts(chunks.get(2))); + Assertions.assertFalse(chunks.get(1).abuts(chunks.get(0))); + Assertions.assertFalse(chunks.get(1).abuts(chunks.get(1))); + Assertions.assertFalse(chunks.get(2).abuts(chunks.get(0))); + Assertions.assertFalse(chunks.get(2).abuts(chunks.get(1))); + Assertions.assertFalse(chunks.get(2).abuts(chunks.get(2))); } @Test @@ -198,10 +198,10 @@ public void testVersionedIntervalTimelineBehaviorForNumberedShardSpec() public void testSharePartitionSpace() { final NumberedShardSpec shardSpec = new NumberedShardSpec(0, 1); - Assert.assertTrue(shardSpec.sharePartitionSpace(NumberedPartialShardSpec.instance())); - Assert.assertTrue(shardSpec.sharePartitionSpace(new HashBasedNumberedPartialShardSpec(null, 0, 1, null))); - Assert.assertTrue(shardSpec.sharePartitionSpace(new SingleDimensionPartialShardSpec("dim", 0, null, null, 1))); - Assert.assertFalse(shardSpec.sharePartitionSpace(new NumberedOverwritePartialShardSpec(0, 2, 1))); + Assertions.assertTrue(shardSpec.sharePartitionSpace(NumberedPartialShardSpec.instance())); + Assertions.assertTrue(shardSpec.sharePartitionSpace(new HashBasedNumberedPartialShardSpec(null, 0, 1, null))); + Assertions.assertTrue(shardSpec.sharePartitionSpace(new SingleDimensionPartialShardSpec("dim", 0, null, null, 1))); + Assertions.assertFalse(shardSpec.sharePartitionSpace(new NumberedOverwritePartialShardSpec(0, 2, 1))); } private void testVersionedIntervalTimelineBehaviorForNumberedShardSpec( @@ -223,7 +223,7 @@ private void testVersionedIntervalTimelineBehaviorForNumberedShardSpec( actualObjects.add(chunk.getObject()); } } - Assert.assertEquals(expectedObjects, actualObjects); + Assertions.assertEquals(expectedObjects, actualObjects); } private static final class OvershadowableString implements Overshadowable From 0202a29b61d6d10ce40d575c84e7ab4b185024b2 Mon Sep 17 00:00:00 2001 From: Clint Wylie Date: Fri, 19 Jun 2026 14:14:49 -0700 Subject: [PATCH 2/4] fix --- .../java/util/common/parsers/FlatTextFormatParserTest.java | 6 +++--- .../java/org/apache/druid/query/InlineDataSourceTest.java | 3 ++- .../druid/segment/join/lookup/LookupJoinableTest.java | 4 ++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java b/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java index 8aed3a87be8b..8f4de4ebb034 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java @@ -66,11 +66,11 @@ public void testDuplicatedColumnName() { final String header = concat(format, "time", "value1", "value2", "value2"); - Assertions.assertThrows( + Throwable t = Assertions.assertThrows( ParseException.class, - () -> PARSER_FACTORY.get(format, header), - StringUtils.format("Unable to parse header [%s]", header) + () -> PARSER_FACTORY.get(format, header) ); + Assertions.assertEquals(StringUtils.format("Unable to parse header [%s]", header), t.getMessage()); } @Test diff --git a/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java b/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java index 9a233428afe1..b783fa46c523 100644 --- a/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java +++ b/processing/src/test/java/org/apache/druid/query/InlineDataSourceTest.java @@ -220,11 +220,12 @@ public void test_withChildren_empty() @Test public void test_withChildren_nonEmpty() { - Assertions.assertThrows( + Throwable t = Assertions.assertThrows( IllegalArgumentException.class, // Workaround so "withChildren" isn't flagged as unused in the DataSource interface. () -> ((DataSource) listDataSource).withChildren(ImmutableList.of(new TableDataSource("foo"))) ); + Assertions.assertEquals("Cannot accept children", t.getMessage()); } @Test diff --git a/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java b/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java index 5479379e31c6..8bb9fc801dc0 100644 --- a/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java +++ b/processing/src/test/java/org/apache/druid/segment/join/lookup/LookupJoinableTest.java @@ -29,9 +29,9 @@ import org.apache.druid.segment.column.ValueType; import org.apache.druid.segment.join.Joinable; import org.apache.druid.testing.InitializedNullHandlingTest; -import org.junit.Ignore; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.util.Collections; @@ -235,7 +235,7 @@ public void getCorrelatedColumnValuesForSearchValueAndRetrieveKeyColumnShouldRet } @Test - @Ignore + @Disabled /** * See {@link LookupJoinable#getCorrelatedColumnValues(String, String, String, long, boolean)} for implementation * details that cause this test to fail. From 4697931743aa9d7b70d63605a094796029f8edb3 Mon Sep 17 00:00:00 2001 From: Clint Wylie Date: Sun, 21 Jun 2026 22:19:04 -0700 Subject: [PATCH 3/4] fix strict --- .../query/groupby/epinephelinae/SpillOutputStreamTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java b/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java index 998021104423..b463132357a7 100644 --- a/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java +++ b/processing/src/test/java/org/apache/druid/query/groupby/epinephelinae/SpillOutputStreamTest.java @@ -243,7 +243,7 @@ public void testGetFileThrowsWhenInMemory() throws IOException } @Test - public void testDiskStorageLimitEnforced() throws IOException + public void testDiskStorageLimitEnforced() { LimitedTemporaryStorage storage = makeStorage(10); Assertions.assertThrows(TemporaryStorageFullException.class, () -> { @@ -255,12 +255,12 @@ public void testDiskStorageLimitEnforced() throws IOException }); } - private SpillOutputStream makeStream(long threshold) throws IOException + private SpillOutputStream makeStream(long threshold) { return new SpillOutputStream(makeStorage(1024 * 1024), threshold); } - private LimitedTemporaryStorage makeStorage(long maxBytes) throws IOException + private LimitedTemporaryStorage makeStorage(long maxBytes) { return new LimitedTemporaryStorage( temporaryFolder, From 9632f330e755a8fdd721449bc9e3042e4a478968 Mon Sep 17 00:00:00 2001 From: Clint Wylie Date: Mon, 22 Jun 2026 12:13:15 -0700 Subject: [PATCH 4/4] assert message --- .../java/util/common/parsers/FlatTextFormatParserTest.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java b/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java index 8f4de4ebb034..07e5eef48bf0 100644 --- a/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java +++ b/processing/src/test/java/org/apache/druid/java/util/common/parsers/FlatTextFormatParserTest.java @@ -200,10 +200,14 @@ public void testWithoutStartFileFromBeginning() concat(format, "header", "line", "2"), concat(format, "hello", "world", "foo") }; - Assertions.assertThrows( + Throwable t = Assertions.assertThrows( UnsupportedOperationException.class, () -> parser.parseToMap(body[0]) ); + Assertions.assertEquals( + "hasHeaderRow or maxSkipHeaderRows is not supported. Please check the indexTask supports these options.", + t.getMessage() + ); } @Test