From 4b4e50ba5f5a4bc69afda2f3114420d826dd21b8 Mon Sep 17 00:00:00 2001 From: Eduard Tudenhoefner Date: Wed, 8 Jul 2026 16:38:50 +0200 Subject: [PATCH] GH-3615: Use assertThat checks in parquet-column tests --- .../arrow/schema/TestSchemaConverter.java | 89 +-- .../apache/parquet/CorruptStatisticsTest.java | 197 +++--- .../apache/parquet/FixedBinaryTestUtils.java | 34 +- .../ParquetPropertiesThreadSafetyTest.java | 14 +- .../parquet/column/TestColumnDescriptor.java | 28 +- .../parquet/column/TestEncodingStats.java | 222 ++++--- .../parquet/column/TestParquetProperties.java | 48 +- .../column/impl/TestColumnReaderImpl.java | 27 +- .../impl/TestCorruptDeltaByteArrays.java | 101 +-- .../parquet/column/mem/TestMemColumn.java | 64 +- .../parquet/column/mem/TestMemPageStore.java | 32 +- .../column/statistics/TestSizeStatistics.java | 47 +- .../column/statistics/TestStatistics.java | 530 ++++++++-------- .../statistics/TestStatisticsNanCount.java | 161 +++-- .../geospatial/TestBoundingBox.java | 594 +++++++++--------- .../geospatial/TestGeospatialStatistics.java | 67 +- .../geospatial/TestGeospatialTypes.java | 197 +++--- .../column/values/TestValuesReaderImpl.java | 42 +- .../bitpacking/TestBitPackingColumn.java | 13 +- .../TestBlockSplitBloomFilter.java | 64 +- .../ByteStreamSplitValuesEndToEndTest.java | 41 +- .../ByteStreamSplitValuesReaderTest.java | 57 +- .../ByteStreamSplitValuesWriterTest.java | 63 +- ...naryPackingValuesWriterForIntegerTest.java | 27 +- ...aBinaryPackingValuesWriterForLongTest.java | 27 +- .../TestDeltaLengthByteArray.java | 13 +- .../deltastrings/TestDeltaByteArray.java | 27 +- .../column/values/dictionary/IntListTest.java | 9 +- .../values/dictionary/TestDictionary.java | 144 +++-- .../DefaultValuesWriterFactoryTest.java | 23 +- .../TestBinaryPlainValuesWriterReader.java | 11 +- .../TestBooleanPlainValuesWriterReader.java | 20 +- ...edLenByteArrayPlainValuesWriterReader.java | 31 +- .../plain/TestPlainValuesWriterReader.java | 36 +- ...LengthBitPackingHybridIntegrationTest.java | 16 +- .../TestRunLengthBitPackingHybridEncoder.java | 88 +-- .../filter2/columnindex/TestRowRanges.java | 216 +++---- .../predicate/TestContainsRewriter.java | 23 +- .../predicate/TestFilterApiMethods.java | 79 ++- .../predicate/TestLogicalInverseRewriter.java | 24 +- .../predicate/TestLogicalInverter.java | 28 +- .../TestSchemaCompatibilityValidator.java | 69 +- .../filter2/predicate/TestValidTypeMap.java | 35 +- ...ntallyUpdatedFilterPredicateEvaluator.java | 37 +- ...entallyUpdatedFilterPredicateResetter.java | 27 +- .../recordlevel/TestValueInspector.java | 51 +- .../columnindex/TestBinaryTruncator.java | 103 +-- .../column/columnindex/TestBoundaryOrder.java | 5 +- .../columnindex/TestColumnIndexBuilder.java | 373 +++++------ .../TestColumnIndexBuilderNaN.java | 286 ++++----- .../column/columnindex/TestIndexIterator.java | 131 ++-- .../columnindex/TestOffsetIndexBuilder.java | 39 +- .../columnindex/TestColumnIndexFilter.java | 10 +- .../io/ExpectationValidatingConverter.java | 4 +- .../ExpectationValidatingRecordConsumer.java | 4 +- .../org/apache/parquet/io/TestColumnIO.java | 120 ++-- .../org/apache/parquet/io/TestFiltered.java | 37 +- .../io/ValidatingRecordConsumerTest.java | 7 +- .../org/apache/parquet/io/api/TestBinary.java | 186 +++--- .../parquet/parser/TestParquetParser.java | 62 +- .../apache/parquet/schema/TestFloat16.java | 360 +++++------ .../parquet/schema/TestMessageType.java | 118 ++-- .../schema/TestPrimitiveComparator.java | 114 ++-- .../schema/TestPrimitiveStringifier.java | 370 +++++------ .../parquet/schema/TestRepetitionType.java | 11 +- .../parquet/schema/TestTypeBuilders.java | 416 ++++++------ .../TestTypeBuildersWithLogicalTypes.java | 320 +++++----- .../apache/parquet/schema/TestTypeUtil.java | 33 +- 68 files changed, 3360 insertions(+), 3542 deletions(-) diff --git a/parquet-arrow/src/test/java/org/apache/parquet/arrow/schema/TestSchemaConverter.java b/parquet-arrow/src/test/java/org/apache/parquet/arrow/schema/TestSchemaConverter.java index 3ed23746b8..c1588bd5d9 100644 --- a/parquet-arrow/src/test/java/org/apache/parquet/arrow/schema/TestSchemaConverter.java +++ b/parquet-arrow/src/test/java/org/apache/parquet/arrow/schema/TestSchemaConverter.java @@ -30,6 +30,7 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT64; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT96; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; @@ -55,7 +56,6 @@ import org.apache.parquet.schema.LogicalTypeAnnotation; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.Types; -import org.junit.Assert; import org.junit.Test; /** @@ -363,54 +363,35 @@ private static Field field(String name, ArrowType type, Field... children) { @Test public void testComplexArrowToParquet() { MessageType parquet = converter.fromArrow(complexArrowSchema).getParquetSchema(); - Assert.assertEquals(complexParquetSchema.toString(), parquet.toString()); // easier to read - Assert.assertEquals(complexParquetSchema, parquet); + assertThat(parquet).asString().isEqualTo(complexParquetSchema.toString()); // easier to read + assertThat(parquet).isEqualTo(complexParquetSchema); } @Test public void testAllArrowToParquet() { MessageType parquet = converter.fromArrow(allTypesArrowSchema).getParquetSchema(); - Assert.assertEquals(allTypesParquetSchema.toString(), parquet.toString()); // easier to read - Assert.assertEquals(allTypesParquetSchema, parquet); + assertThat(parquet).asString().isEqualTo(allTypesParquetSchema.toString()); // easier to read + assertThat(parquet).isEqualTo(allTypesParquetSchema); } @Test public void testSupportedParquetToArrow() { Schema arrow = converter.fromParquet(supportedTypesParquetSchema).getArrowSchema(); - assertEquals(supportedTypesArrowSchema, arrow); + assertThat(arrow).isEqualTo(supportedTypesArrowSchema); } @Test public void testRepeatedParquetToArrow() { Schema arrow = converter.fromParquet(Paper.schema).getArrowSchema(); - assertEquals(paperArrowSchema, arrow); - } - - public void assertEquals(Schema left, Schema right) { - compareFields(left.getFields(), right.getFields()); - Assert.assertEquals(left, right); - } - - /** - * for more pinpointed error on what is different - */ - private void compareFields(List left, List right) { - Assert.assertEquals(left + "\n" + right, left.size(), right.size()); - int size = left.size(); - for (int i = 0; i < size; i++) { - Field expectedField = left.get(i); - Field field = right.get(i); - compareFields(expectedField.getChildren(), field.getChildren()); - Assert.assertEquals(expectedField, field); - } + assertThat(arrow).isEqualTo(paperArrowSchema); } @Test public void testAllMap() { SchemaMapping map = converter.map(allTypesArrowSchema, allTypesParquetSchema); - Assert.assertEquals( - "p, s

, l

, l

, u

, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p", - toSummaryString(map)); + assertThat(toSummaryString(map)) + .isEqualTo( + "p, s

, l

, l

, u

, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p, p"); } private String toSummaryString(SchemaMapping map) { @@ -467,7 +448,7 @@ public String visit(RepeatedTypeMapping repeatedTypeMapping) { @Test public void testRepeatedMap() throws IOException { SchemaMapping map = converter.map(paperArrowSchema, Paper.schema); - Assert.assertEquals("p, s, r

>, r>, p>>", toSummaryString(map)); + assertThat(toSummaryString(map)).isEqualTo("p, s, r

>, r>, p>>"); } @Test @@ -484,13 +465,12 @@ public void testArrowTimeMillisecondToParquet() { MessageType expected = converter .fromArrow(new Schema(asList(field("a", new ArrowType.Time(TimeUnit.MILLISECOND, 32))))) .getParquetSchema(); - Assert.assertEquals( - expected, - Types.buildMessage() + assertThat(Types.buildMessage() .addField(Types.optional(INT32) .as(LogicalTypeAnnotation.timeType(false, MILLIS)) .named("a")) - .named("root")); + .named("root")) + .isEqualTo(expected); } @Test @@ -498,13 +478,12 @@ public void testArrowTimeMicrosecondToParquet() { MessageType expected = converter .fromArrow(new Schema(asList(field("a", new ArrowType.Time(TimeUnit.MICROSECOND, 64))))) .getParquetSchema(); - Assert.assertEquals( - expected, - Types.buildMessage() + assertThat(Types.buildMessage() .addField(Types.optional(INT64) .as(LogicalTypeAnnotation.timeType(false, MICROS)) .named("a")) - .named("root")); + .named("root")) + .isEqualTo(expected); } @Test @@ -515,7 +494,7 @@ public void testParquetInt32TimeMillisToArrow() { .named("a")) .named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Time(TimeUnit.MILLISECOND, 32)))); - Assert.assertEquals(expected, converter.fromParquet(parquet).getArrowSchema()); + assertThat(converter.fromParquet(parquet).getArrowSchema()).isEqualTo(expected); } @Test @@ -526,7 +505,7 @@ public void testParquetInt64TimeMicrosToArrow() { .named("a")) .named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Time(TimeUnit.MICROSECOND, 64)))); - Assert.assertEquals(expected, converter.fromParquet(parquet).getArrowSchema()); + assertThat(converter.fromParquet(parquet).getArrowSchema()).isEqualTo(expected); } @Test @@ -535,7 +514,7 @@ public void testParquetFixedBinaryToArrow() { .addField(Types.optional(FIXED_LEN_BYTE_ARRAY).length(12).named("a")) .named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Binary()))); - Assert.assertEquals(expected, converter.fromParquet(parquet).getArrowSchema()); + assertThat(converter.fromParquet(parquet).getArrowSchema()).isEqualTo(expected); } @Test @@ -550,7 +529,7 @@ public void testParquetMapToArrow() { SchemaMapping mapping = converter.fromParquet(parquet); Schema actual = mapping.getArrowSchema(); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -562,7 +541,7 @@ public void testParquetFixedBinaryToArrowDecimal() { .named("a")) .named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Decimal(8, 2)))); - Assert.assertEquals(expected, converter.fromParquet(parquet).getArrowSchema()); + assertThat(converter.fromParquet(parquet).getArrowSchema()).isEqualTo(expected); } @Test @@ -570,7 +549,7 @@ public void testParquetInt96ToArrowBinary() { MessageType parquet = Types.buildMessage().addField(Types.optional(INT96).named("a")).named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Binary()))); - Assert.assertEquals(expected, converter.fromParquet(parquet).getArrowSchema()); + assertThat(converter.fromParquet(parquet).getArrowSchema()).isEqualTo(expected); } @Test @@ -579,8 +558,8 @@ public void testParquetInt96ToArrowTimestamp() { MessageType parquet = Types.buildMessage().addField(Types.optional(INT96).named("a")).named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Timestamp(TimeUnit.NANOSECOND, null)))); - Assert.assertEquals( - expected, converterInt96ToTimestamp.fromParquet(parquet).getArrowSchema()); + assertThat(converterInt96ToTimestamp.fromParquet(parquet).getArrowSchema()) + .isEqualTo(expected); } @Test @@ -619,13 +598,12 @@ public void testArrowTimestampMillisecondToParquet() { MessageType expected = converter .fromArrow(new Schema(asList(field("a", new ArrowType.Timestamp(TimeUnit.MILLISECOND, "UTC"))))) .getParquetSchema(); - Assert.assertEquals( - expected, - Types.buildMessage() + assertThat(Types.buildMessage() .addField(Types.optional(INT64) .as(LogicalTypeAnnotation.timestampType(true, MILLIS)) .named("a")) - .named("root")); + .named("root")) + .isEqualTo(expected); } @Test @@ -633,13 +611,12 @@ public void testArrowTimestampMicrosecondToParquet() { MessageType expected = converter .fromArrow(new Schema(asList(field("a", new ArrowType.Timestamp(TimeUnit.MICROSECOND, "UTC"))))) .getParquetSchema(); - Assert.assertEquals( - expected, - Types.buildMessage() + assertThat(Types.buildMessage() .addField(Types.optional(INT64) .as(LogicalTypeAnnotation.timestampType(true, MICROS)) .named("a")) - .named("root")); + .named("root")) + .isEqualTo(expected); } @Test @@ -650,7 +627,7 @@ public void testParquetInt64TimestampMillisToArrow() { .named("a")) .named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Timestamp(TimeUnit.MILLISECOND, "UTC")))); - Assert.assertEquals(expected, converter.fromParquet(parquet).getArrowSchema()); + assertThat(converter.fromParquet(parquet).getArrowSchema()).isEqualTo(expected); } @Test @@ -661,7 +638,7 @@ public void testParquetInt64TimestampMicrosToArrow() { .named("a")) .named("root"); Schema expected = new Schema(asList(field("a", new ArrowType.Timestamp(TimeUnit.MICROSECOND, "UTC")))); - Assert.assertEquals(expected, converter.fromParquet(parquet).getArrowSchema()); + assertThat(converter.fromParquet(parquet).getArrowSchema()).isEqualTo(expected); } @Test diff --git a/parquet-column/src/test/java/org/apache/parquet/CorruptStatisticsTest.java b/parquet-column/src/test/java/org/apache/parquet/CorruptStatisticsTest.java index e897b38512..996759cad3 100644 --- a/parquet-column/src/test/java/org/apache/parquet/CorruptStatisticsTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/CorruptStatisticsTest.java @@ -18,8 +18,7 @@ */ package org.apache.parquet; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; import org.junit.Test; @@ -28,100 +27,140 @@ public class CorruptStatisticsTest { @Test public void testOnlyAppliesToBinary() { - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.DOUBLE)); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.DOUBLE)) + .isFalse(); } @Test public void testCorruptStatistics() { - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.4.2 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.100 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.7.999 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.22rc99 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.22rc99-SNAPSHOT (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.1-SNAPSHOT (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.0t-01-abcdefg (build abcd)", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.4.2 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.100 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.7.999 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.22rc99 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.22rc99-SNAPSHOT (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.1-SNAPSHOT (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0t-01-abcdefg (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); - assertTrue(CorruptStatistics.shouldIgnoreStatistics("unparseable string", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics("unparseable string", PrimitiveTypeName.BINARY)) + .isTrue(); // missing semver - assertTrue( - CorruptStatistics.shouldIgnoreStatistics("parquet-mr version (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue( - CorruptStatistics.shouldIgnoreStatistics("parquet-mr version (build abcd)", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); // missing build hash - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.0 (build )", PrimitiveTypeName.BINARY)); - assertTrue( - CorruptStatistics.shouldIgnoreStatistics("parquet-mr version 1.6.0 (build)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics("parquet-mr version (build)", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0 (build )", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0 (build)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics("parquet-mr version (build)", PrimitiveTypeName.BINARY)) + .isTrue(); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "imapla version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "imapla version 1.10.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.8.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.8.1 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.8.1rc3 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.8.1rc3-SNAPSHOT (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.9.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 2.0.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.9.0t-01-abcdefg (build abcd)", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "imapla version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "imapla version 1.10.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.8.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.8.1 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.8.1rc3 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.8.1rc3-SNAPSHOT (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.9.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 2.0.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.9.0t-01-abcdefg (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); // missing semver - assertFalse(CorruptStatistics.shouldIgnoreStatistics("impala version (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics("impala version (build abcd)", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics("impala version (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics("impala version (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); // missing build hash - assertFalse( - CorruptStatistics.shouldIgnoreStatistics("impala version 1.6.0 (build )", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics("impala version 1.6.0 (build)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics("impala version (build)", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics("impala version 1.6.0 (build )", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics("impala version 1.6.0 (build)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics("impala version (build)", PrimitiveTypeName.BINARY)) + .isFalse(); } @Test public void testDistributionCorruptStatistics() { - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.5.0-cdh5.4.999 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.5.0-cdh5.5.0-SNAPSHOT (build 956ed6c14c611b4c4eaaa1d6e5b9a9c6d4dfa336)", - PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.5.0-cdh5.5.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.5.0-cdh5.5.1 (build abcd)", PrimitiveTypeName.BINARY)); - assertFalse(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.5.0-cdh5.6.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.4.10 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.5.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.5.1 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)); - assertTrue(CorruptStatistics.shouldIgnoreStatistics( - "parquet-mr version 1.7.0 (build abcd)", PrimitiveTypeName.BINARY)); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.5.0-cdh5.4.999 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.5.0-cdh5.5.0-SNAPSHOT (build 956ed6c14c611b4c4eaaa1d6e5b9a9c6d4dfa336)", + PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.5.0-cdh5.5.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.5.0-cdh5.5.1 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.5.0-cdh5.6.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isFalse(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.4.10 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.5.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.5.1 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.6.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); + assertThat(CorruptStatistics.shouldIgnoreStatistics( + "parquet-mr version 1.7.0 (build abcd)", PrimitiveTypeName.BINARY)) + .isTrue(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/FixedBinaryTestUtils.java b/parquet-column/src/test/java/org/apache/parquet/FixedBinaryTestUtils.java index 0d54a9595c..ddb6b5ce11 100644 --- a/parquet-column/src/test/java/org/apache/parquet/FixedBinaryTestUtils.java +++ b/parquet-column/src/test/java/org/apache/parquet/FixedBinaryTestUtils.java @@ -19,8 +19,7 @@ package org.apache.parquet; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.math.BigInteger; import java.util.Arrays; @@ -67,27 +66,16 @@ public static Binary getFixedBinary(PrimitiveType type, BigInteger bigInt) { @Test public void testGetFixedBinary() { - assertArrayEquals( - b(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00), - getFixedBinary(10, BigInteger.valueOf(Integer.MIN_VALUE)).getBytes()); - assertArrayEquals( - b(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF), - getFixedBinary(11, BigInteger.valueOf(-1)).getBytes()); - assertArrayEquals( - b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00), - getFixedBinary(12, BigInteger.valueOf(0)).getBytes()); - assertArrayEquals( - b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01), - getFixedBinary(13, BigInteger.valueOf(1)).getBytes()); - assertArrayEquals( - b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFF, 0xFF, 0xFF), - getFixedBinary(14, BigInteger.valueOf(Integer.MAX_VALUE)).getBytes()); - } - - public void assertCorrectBytes(byte[] expectedBytes, int length, BigInteger bigInt) { - byte[] actualBytes = getFixedBinary(length, bigInt).getBytes(); - assertArrayEquals(expectedBytes, actualBytes); - assertEquals(bigInt, new BigInteger(actualBytes)); + assertThat(getFixedBinary(10, BigInteger.valueOf(Integer.MIN_VALUE)).getBytes()) + .isEqualTo(b(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00)); + assertThat(getFixedBinary(11, BigInteger.valueOf(-1)).getBytes()) + .isEqualTo(b(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF)); + assertThat(getFixedBinary(12, BigInteger.valueOf(0)).getBytes()) + .isEqualTo(b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)); + assertThat(getFixedBinary(13, BigInteger.valueOf(1)).getBytes()) + .isEqualTo(b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01)); + assertThat(getFixedBinary(14, BigInteger.valueOf(Integer.MAX_VALUE)).getBytes()) + .isEqualTo(b(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFF, 0xFF, 0xFF)); } private static byte[] b(int... bytes) { diff --git a/parquet-column/src/test/java/org/apache/parquet/column/ParquetPropertiesThreadSafetyTest.java b/parquet-column/src/test/java/org/apache/parquet/column/ParquetPropertiesThreadSafetyTest.java index bb622f1c1f..c6556c4596 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/ParquetPropertiesThreadSafetyTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/ParquetPropertiesThreadSafetyTest.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.column; -import static org.junit.Assert.assertNotSame; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Field; import org.apache.parquet.column.values.factory.ValuesWriterFactory; @@ -39,8 +39,14 @@ public void testBuilderValuesWriterFactoryNotShared() throws Exception { ValuesWriterFactory factory2 = (ValuesWriterFactory) factoryField.get(builder2); ValuesWriterFactory factory3 = (ValuesWriterFactory) factoryField.get(builder3); - assertNotSame("Builder instances should not share ValuesWriterFactory instances", factory1, factory2); - assertNotSame("Builder instances should not share ValuesWriterFactory instances", factory2, factory3); - assertNotSame("Builder instances should not share ValuesWriterFactory instances", factory1, factory3); + assertThat(factory1) + .as("Builder instances should not share ValuesWriterFactory instances") + .isNotSameAs(factory2); + assertThat(factory2) + .as("Builder instances should not share ValuesWriterFactory instances") + .isNotSameAs(factory3); + assertThat(factory1) + .as("Builder instances should not share ValuesWriterFactory instances") + .isNotSameAs(factory3); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/TestColumnDescriptor.java b/parquet-column/src/test/java/org/apache/parquet/column/TestColumnDescriptor.java index 73d6adee12..c27ea509c1 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/TestColumnDescriptor.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/TestColumnDescriptor.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.column; -import static junit.framework.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.schema.PrimitiveType; import org.junit.Test; @@ -30,23 +30,21 @@ private ColumnDescriptor column(String... path) { } @Test - public void testComparesTo() throws Exception { - assertEquals(column("a").compareTo(column("a")), 0); - assertEquals(column("a", "b").compareTo(column("a", "b")), 0); + public void testComparesTo() { + assertThat(column("a")).isEqualByComparingTo(column("a")); + assertThat(column("a", "b")).isEqualByComparingTo(column("a", "b")); - assertEquals(column("a").compareTo(column("b")), -1); - assertEquals(column("b").compareTo(column("a")), 1); - assertEquals(column("a", "a").compareTo(column("a", "b")), -1); - assertEquals(column("b", "a").compareTo(column("a", "a")), 1); + assertThat(column("a")).isLessThan(column("b")); + assertThat(column("b")).isGreaterThan(column("a")); + assertThat(column("a", "a")).isLessThan(column("a", "b")); + assertThat(column("b", "a")).isGreaterThan(column("a", "a")); - assertEquals(column("a").compareTo(column("a", "b")), -1); - assertEquals(column("b").compareTo(column("a", "b")), 1); + assertThat(column("a")).isLessThan(column("a", "b")); + assertThat(column("b")).isGreaterThan(column("a", "b")); - assertEquals(column("a", "b").compareTo(column("a")), 1); - assertEquals(column("a", "b").compareTo(column("b")), -1); + assertThat(column("a", "b")).isGreaterThan(column("a")).isLessThan(column("b")); - assertEquals(column("").compareTo(column("")), 0); - assertEquals(column("").compareTo(column("a")), -1); - assertEquals(column("a").compareTo(column("")), 1); + assertThat(column("")).isEqualByComparingTo(column("")).isLessThan(column("a")); + assertThat(column("a")).isGreaterThan(column("")); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/TestEncodingStats.java b/parquet-column/src/test/java/org/apache/parquet/column/TestEncodingStats.java index ea56693489..70d265be54 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/TestEncodingStats.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/TestEncodingStats.java @@ -19,9 +19,7 @@ package org.apache.parquet.column; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -43,28 +41,28 @@ public void testReusedBuilder() { builder.addDataEncoding(Encoding.PLAIN); EncodingStats stats2 = builder.build(); - assertEquals("Dictionary stats should be correct", 0, stats2.dictStats.size()); - assertEquals("Data stats size should be correct", 1, stats2.dataStats.size()); - assertEquals( - "Data stats content should be correct", - 4, - stats2.dataStats.get(Encoding.PLAIN).intValue()); - - assertEquals("Dictionary stats size should be correct after reuse", 1, stats1.dictStats.size()); - assertEquals( - "Dictionary stats content should be correct", - 1, - stats1.dictStats.get(Encoding.PLAIN).intValue()); - - assertEquals("Data stats size should be correct after reuse", 2, stats1.dataStats.size()); - assertEquals( - "Data stats content should be correct", - 3, - stats1.dataStats.get(Encoding.RLE_DICTIONARY).intValue()); - assertEquals( - "Data stats content should be correct", - 2, - stats1.dataStats.get(Encoding.DELTA_BYTE_ARRAY).intValue()); + assertThat(stats2.dictStats).as("Dictionary stats should be correct").isEmpty(); + assertThat(stats2.dataStats).as("Data stats size should be correct").hasSize(1); + assertThat(stats2.dataStats.get(Encoding.PLAIN).intValue()) + .as("Data stats content should be correct") + .isEqualTo(4); + + assertThat(stats1.dictStats) + .as("Dictionary stats size should be correct after reuse") + .hasSize(1); + assertThat(stats1.dictStats.get(Encoding.PLAIN).intValue()) + .as("Dictionary stats content should be correct") + .isEqualTo(1); + + assertThat(stats1.dataStats) + .as("Data stats size should be correct after reuse") + .hasSize(2); + assertThat(stats1.dataStats.get(Encoding.RLE_DICTIONARY).intValue()) + .as("Data stats content should be correct") + .isEqualTo(3); + assertThat(stats1.dataStats.get(Encoding.DELTA_BYTE_ARRAY).intValue()) + .as("Data stats content should be correct") + .isEqualTo(2); } @Test @@ -72,10 +70,16 @@ public void testNoPages() { EncodingStats.Builder builder = new EncodingStats.Builder(); EncodingStats stats = builder.build(); - assertFalse(stats.usesV2Pages()); - assertFalse("Should not have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertFalse("Should not have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertFalse("Should not have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isFalse(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should not have dictionary-encoded pages") + .isFalse(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should not have non-dictionary pages") + .isFalse(); + assertThat(stats.hasDictionaryPages()) + .as("Should not have dictionary pages") + .isFalse(); } @Test @@ -84,10 +88,16 @@ public void testNoDataPages() { builder.addDictEncoding(Encoding.PLAIN_DICTIONARY); EncodingStats stats = builder.build(); - assertFalse(stats.usesV2Pages()); - assertFalse("Should not have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertFalse("Should not have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertTrue("Should have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isFalse(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should not have dictionary-encoded pages") + .isFalse(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should not have non-dictionary pages") + .isFalse(); + assertThat(stats.hasDictionaryPages()) + .as("Should have dictionary pages") + .isTrue(); } @Test @@ -98,10 +108,16 @@ public void testV1AllDictionary() { builder.addDataEncoding(Encoding.PLAIN_DICTIONARY); EncodingStats stats = builder.build(); - assertFalse(stats.usesV2Pages()); - assertTrue("Should have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertFalse("Should not have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertTrue("Should have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isFalse(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should have dictionary-encoded pages") + .isTrue(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should not have non-dictionary pages") + .isFalse(); + assertThat(stats.hasDictionaryPages()) + .as("Should have dictionary pages") + .isTrue(); } @Test @@ -110,10 +126,16 @@ public void testV1NoDictionary() { builder.addDataEncoding(Encoding.PLAIN); EncodingStats stats = builder.build(); - assertFalse(stats.usesV2Pages()); - assertFalse("Should not have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertTrue("Should have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertFalse("Should not have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isFalse(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should not have dictionary-encoded pages") + .isFalse(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should have non-dictionary pages") + .isTrue(); + assertThat(stats.hasDictionaryPages()) + .as("Should not have dictionary pages") + .isFalse(); } @Test @@ -125,10 +147,16 @@ public void testV1Fallback() { builder.addDataEncoding(Encoding.PLAIN); EncodingStats stats = builder.build(); - assertFalse(stats.usesV2Pages()); - assertTrue("Should have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertTrue("Should have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertTrue("Should have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isFalse(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should have dictionary-encoded pages") + .isTrue(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should have non-dictionary pages") + .isTrue(); + assertThat(stats.hasDictionaryPages()) + .as("Should have dictionary pages") + .isTrue(); } @Test @@ -139,10 +167,16 @@ public void testV2AllDictionary() { builder.addDataEncoding(Encoding.RLE_DICTIONARY); EncodingStats stats = builder.build(); - assertTrue(stats.usesV2Pages()); - assertTrue("Should have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertFalse("Should not have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertTrue("Should have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isTrue(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should have dictionary-encoded pages") + .isTrue(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should not have non-dictionary pages") + .isFalse(); + assertThat(stats.hasDictionaryPages()) + .as("Should have dictionary pages") + .isTrue(); } @Test @@ -153,10 +187,16 @@ public void testV2NoDictionary() { builder.addDataEncoding(Encoding.DELTA_BINARY_PACKED); EncodingStats stats = builder.build(); - assertTrue(stats.usesV2Pages()); - assertFalse("Should not have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertTrue("Should have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertFalse("Should not have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isTrue(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should not have dictionary-encoded pages") + .isFalse(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should have non-dictionary pages") + .isTrue(); + assertThat(stats.hasDictionaryPages()) + .as("Should not have dictionary pages") + .isFalse(); } @Test @@ -169,10 +209,16 @@ public void testV2Fallback() { builder.addDataEncoding(Encoding.DELTA_BYTE_ARRAY); EncodingStats stats = builder.build(); - assertTrue(stats.usesV2Pages()); - assertTrue("Should have dictionary-encoded pages", stats.hasDictionaryEncodedPages()); - assertTrue("Should have non-dictionary pages", stats.hasNonDictionaryEncodedPages()); - assertTrue("Should have dictionary pages", stats.hasDictionaryPages()); + assertThat(stats.usesV2Pages()).isTrue(); + assertThat(stats.hasDictionaryEncodedPages()) + .as("Should have dictionary-encoded pages") + .isTrue(); + assertThat(stats.hasNonDictionaryEncodedPages()) + .as("Should have non-dictionary pages") + .isTrue(); + assertThat(stats.hasDictionaryPages()) + .as("Should have dictionary pages") + .isTrue(); } @Test @@ -186,21 +232,51 @@ public void testCounts() { builder.addDataEncoding(Encoding.DELTA_BYTE_ARRAY); EncodingStats stats = builder.build(); - assertEquals("Count should match", 1, stats.getNumDictionaryPagesEncodedAs(Encoding.PLAIN)); - assertEquals("Count should match", 0, stats.getNumDictionaryPagesEncodedAs(Encoding.PLAIN_DICTIONARY)); - assertEquals("Count should match", 0, stats.getNumDictionaryPagesEncodedAs(Encoding.RLE)); - assertEquals("Count should match", 0, stats.getNumDictionaryPagesEncodedAs(Encoding.BIT_PACKED)); - assertEquals("Count should match", 0, stats.getNumDictionaryPagesEncodedAs(Encoding.DELTA_BYTE_ARRAY)); - assertEquals("Count should match", 0, stats.getNumDictionaryPagesEncodedAs(Encoding.DELTA_BINARY_PACKED)); - assertEquals("Count should match", 0, stats.getNumDictionaryPagesEncodedAs(Encoding.DELTA_LENGTH_BYTE_ARRAY)); - - assertEquals("Count should match", 5, stats.getNumDataPagesEncodedAs(Encoding.RLE_DICTIONARY)); - assertEquals("Count should match", 2, stats.getNumDataPagesEncodedAs(Encoding.DELTA_BYTE_ARRAY)); - assertEquals("Count should match", 0, stats.getNumDataPagesEncodedAs(Encoding.RLE)); - assertEquals("Count should match", 0, stats.getNumDataPagesEncodedAs(Encoding.BIT_PACKED)); - assertEquals("Count should match", 0, stats.getNumDataPagesEncodedAs(Encoding.PLAIN)); - assertEquals("Count should match", 0, stats.getNumDataPagesEncodedAs(Encoding.PLAIN_DICTIONARY)); - assertEquals("Count should match", 0, stats.getNumDataPagesEncodedAs(Encoding.DELTA_BINARY_PACKED)); - assertEquals("Count should match", 0, stats.getNumDataPagesEncodedAs(Encoding.DELTA_LENGTH_BYTE_ARRAY)); + assertThat(stats.getNumDictionaryPagesEncodedAs(Encoding.PLAIN)) + .as("Count should match") + .isEqualTo(1); + assertThat(stats.getNumDictionaryPagesEncodedAs(Encoding.PLAIN_DICTIONARY)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDictionaryPagesEncodedAs(Encoding.RLE)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDictionaryPagesEncodedAs(Encoding.BIT_PACKED)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDictionaryPagesEncodedAs(Encoding.DELTA_BYTE_ARRAY)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDictionaryPagesEncodedAs(Encoding.DELTA_BINARY_PACKED)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDictionaryPagesEncodedAs(Encoding.DELTA_LENGTH_BYTE_ARRAY)) + .as("Count should match") + .isEqualTo(0); + + assertThat(stats.getNumDataPagesEncodedAs(Encoding.RLE_DICTIONARY)) + .as("Count should match") + .isEqualTo(5); + assertThat(stats.getNumDataPagesEncodedAs(Encoding.DELTA_BYTE_ARRAY)) + .as("Count should match") + .isEqualTo(2); + assertThat(stats.getNumDataPagesEncodedAs(Encoding.RLE)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDataPagesEncodedAs(Encoding.BIT_PACKED)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDataPagesEncodedAs(Encoding.PLAIN)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDataPagesEncodedAs(Encoding.PLAIN_DICTIONARY)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDataPagesEncodedAs(Encoding.DELTA_BINARY_PACKED)) + .as("Count should match") + .isEqualTo(0); + assertThat(stats.getNumDataPagesEncodedAs(Encoding.DELTA_LENGTH_BYTE_ARRAY)) + .as("Count should match") + .isEqualTo(0); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/TestParquetProperties.java b/parquet-column/src/test/java/org/apache/parquet/column/TestParquetProperties.java index 8456e42f4f..40e3e904a8 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/TestParquetProperties.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/TestParquetProperties.java @@ -21,9 +21,8 @@ import static org.apache.parquet.hadoop.metadata.CompressionCodecName.GZIP; import static org.apache.parquet.hadoop.metadata.CompressionCodecName.SNAPPY; import static org.apache.parquet.hadoop.metadata.CompressionCodecName.ZSTD; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.MessageTypeParser; @@ -49,20 +48,20 @@ public void setUp() { @Test public void columnCodec_notSet_returnsNull() { ParquetProperties props = ParquetProperties.builder().build(); - assertNull(props.getColumnCodec(colA)); + assertThat(props.getColumnCodec(colA)).isNull(); } @Test public void columnLevel_notSet_returnsNull() { ParquetProperties props = ParquetProperties.builder().build(); - assertNull(props.getColumnCompressionLevel(colA)); + assertThat(props.getColumnCompressionLevel(colA)).isNull(); } @Test public void columnCodec_setForColumn_returnsConfiguredCodec() { ParquetProperties props = ParquetProperties.builder().withCompressionCodec("col_a", ZSTD).build(); - assertEquals(ZSTD, props.getColumnCodec(colA)); + assertThat(props.getColumnCodec(colA)).isEqualTo(ZSTD); } @Test @@ -71,29 +70,29 @@ public void columnCodec_setMultipleTimes_lastValueWins() { .withCompressionCodec("col_a", ZSTD) .withCompressionCodec("col_a", SNAPPY) .build(); - assertEquals(SNAPPY, props.getColumnCodec(colA)); + assertThat(props.getColumnCodec(colA)).isEqualTo(SNAPPY); } @Test public void columnCodec_otherColumnsUnaffected() { ParquetProperties props = ParquetProperties.builder().withCompressionCodec("col_a", ZSTD).build(); - assertNull(props.getColumnCodec(colB)); - assertNull(props.getColumnCodec(colC)); + assertThat(props.getColumnCodec(colB)).isNull(); + assertThat(props.getColumnCodec(colC)).isNull(); } @Test public void columnLevel_setForColumn_returnsConfiguredLevel() { ParquetProperties props = ParquetProperties.builder().withCompressionLevel("col_a", 10).build(); - assertEquals(Integer.valueOf(10), props.getColumnCompressionLevel(colA)); + assertThat(props.getColumnCompressionLevel(colA)).isEqualTo(10); } @Test public void columnLevel_otherColumnsUnaffected() { ParquetProperties props = ParquetProperties.builder().withCompressionLevel("col_a", 10).build(); - assertNull(props.getColumnCompressionLevel(colB)); + assertThat(props.getColumnCompressionLevel(colB)).isNull(); } @Test @@ -106,20 +105,21 @@ public void columnCodecAndLevel_multipleColumns_eachGetsOwn() { .withCompressionLevel("col_c", 5) .build(); - assertEquals(ZSTD, props.getColumnCodec(colA)); - assertEquals(Integer.valueOf(10), props.getColumnCompressionLevel(colA)); + assertThat(props.getColumnCodec(colA)).isEqualTo(ZSTD); + assertThat(props.getColumnCompressionLevel(colA)).isEqualTo(10); - assertEquals(SNAPPY, props.getColumnCodec(colB)); - assertNull(props.getColumnCompressionLevel(colB)); + assertThat(props.getColumnCodec(colB)).isEqualTo(SNAPPY); + assertThat(props.getColumnCompressionLevel(colB)).isNull(); - assertEquals(GZIP, props.getColumnCodec(colC)); - assertEquals(Integer.valueOf(5), props.getColumnCompressionLevel(colC)); + assertThat(props.getColumnCodec(colC)).isEqualTo(GZIP); + assertThat(props.getColumnCompressionLevel(colC)).isEqualTo(5); } @Test public void withCompressionCodec_nullCodec_throwsNullPointerException() { - assertThrows( - NullPointerException.class, () -> ParquetProperties.builder().withCompressionCodec("col_a", null)); + assertThatThrownBy(() -> ParquetProperties.builder().withCompressionCodec("col_a", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("codec cannot be null"); } @Test @@ -132,10 +132,10 @@ public void copyBuilder_preservesColumnCodecAndLevel() { ParquetProperties copy = ParquetProperties.copy(original).build(); - assertEquals(ZSTD, copy.getColumnCodec(colA)); - assertEquals(Integer.valueOf(7), copy.getColumnCompressionLevel(colA)); - assertEquals(SNAPPY, copy.getColumnCodec(colB)); - assertNull(copy.getColumnCompressionLevel(colB)); - assertNull(copy.getColumnCodec(colC)); + assertThat(copy.getColumnCodec(colA)).isEqualTo(ZSTD); + assertThat(copy.getColumnCompressionLevel(colA)).isEqualTo(7); + assertThat(copy.getColumnCodec(colB)).isEqualTo(SNAPPY); + assertThat(copy.getColumnCompressionLevel(colB)).isNull(); + assertThat(copy.getColumnCodec(colC)).isNull(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/impl/TestColumnReaderImpl.java b/parquet-column/src/test/java/org/apache/parquet/column/impl/TestColumnReaderImpl.java index 63b9e957f4..268313db45 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/impl/TestColumnReaderImpl.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/impl/TestColumnReaderImpl.java @@ -18,8 +18,8 @@ */ package org.apache.parquet.column.impl; -import static junit.framework.Assert.assertEquals; import static org.apache.parquet.column.ParquetProperties.WriterVersion.PARQUET_2_0; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.apache.parquet.Version; @@ -38,7 +38,6 @@ import org.apache.parquet.io.api.PrimitiveConverter; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.MessageTypeParser; -import org.junit.Assert; import org.junit.Test; public class TestColumnReaderImpl { @@ -50,7 +49,7 @@ private static final class ValidatingConverter extends PrimitiveConverter { @Override public void addBinary(Binary value) { - assertEquals("bar" + count % 10, value.toStringUsingUTF8()); + assertThat(value.toStringUsingUTF8()).isEqualTo("bar" + count % 10); ++count; } } @@ -66,8 +65,8 @@ public void test() throws Exception { valueCount += dataPage.getValueCount(); rowCount += ((DataPageV2) dataPage).getRowCount(); } - assertEquals(rows, rowCount); - assertEquals(rows, valueCount); + assertThat(rowCount).isEqualTo(rows); + assertThat(valueCount).isEqualTo(rows); MemPageReader pageReader = toReader(pageWriter); validateExpectedValuesAndCount(col, pageReader); } @@ -109,12 +108,12 @@ private void validateExpectedValuesAndCount(ColumnDescriptor col, MemPageReader ColumnReader columnReader = new ColumnReaderImpl(col, pageReader, converter, VersionParser.parse(Version.FULL_VERSION)); for (int i = 0; i < rows; i++) { - assertEquals(0, columnReader.getCurrentRepetitionLevel()); - assertEquals(0, columnReader.getCurrentDefinitionLevel()); + assertThat(columnReader.getCurrentRepetitionLevel()).isEqualTo(0); + assertThat(columnReader.getCurrentDefinitionLevel()).isEqualTo(0); columnReader.writeCurrentValueToConverter(); columnReader.consume(); } - assertEquals(rows, converter.count); + assertThat(converter.count).isEqualTo(rows); } @Test @@ -145,18 +144,18 @@ public void testOptional() throws Exception { valueCount += dataPage.getValueCount(); rowCount += ((DataPageV2) dataPage).getRowCount(); } - assertEquals(rows, rowCount); - assertEquals(rows, valueCount); + assertThat(rowCount).isEqualTo(rows); + assertThat(valueCount).isEqualTo(rows); MemPageReader pageReader = toReader(pageWriter); ValidatingConverter converter = new ValidatingConverter(); ColumnReader columnReader = new ColumnReaderImpl(col, pageReader, converter, VersionParser.parse(Version.FULL_VERSION)); for (int i = 0; i < rows; i++) { - assertEquals(0, columnReader.getCurrentRepetitionLevel()); - assertEquals(0, columnReader.getCurrentDefinitionLevel()); + assertThat(columnReader.getCurrentRepetitionLevel()).isEqualTo(0); + assertThat(columnReader.getCurrentDefinitionLevel()).isEqualTo(0); columnReader.consume(); } - assertEquals(0, converter.count); + assertThat(converter.count).isEqualTo(0); } @Test @@ -165,7 +164,7 @@ public void testDeduplicatedDecodedDictionary() throws Exception { MemPageWriter pageWriter = writeBinaryDictColumn(col); DictionaryPage dictionaryPage = pageWriter.getDictionaryPage(); - Assert.assertNotNull("Expected a dictionary", dictionaryPage); + assertThat(dictionaryPage).as("Expected a dictionary").isNotNull(); Dictionary dict = dictionaryPage.decode(col); diff --git a/parquet-column/src/test/java/org/apache/parquet/column/impl/TestCorruptDeltaByteArrays.java b/parquet-column/src/test/java/org/apache/parquet/column/impl/TestCorruptDeltaByteArrays.java index 105376bfea..9af6817787 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/impl/TestCorruptDeltaByteArrays.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/impl/TestCorruptDeltaByteArrays.java @@ -18,11 +18,8 @@ */ package org.apache.parquet.column.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.lang.reflect.Field; import java.nio.ByteBuffer; @@ -47,43 +44,58 @@ import org.apache.parquet.io.api.Binary; import org.apache.parquet.io.api.PrimitiveConverter; import org.apache.parquet.schema.PrimitiveType; -import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; public class TestCorruptDeltaByteArrays { @Test public void testCorruptDeltaByteArrayVersions() { - assertTrue(CorruptDeltaByteArrays.requiresSequentialReads( - "parquet-mr version 1.6.0 (build abcd)", Encoding.DELTA_BYTE_ARRAY)); - assertTrue(CorruptDeltaByteArrays.requiresSequentialReads((String) null, Encoding.DELTA_BYTE_ARRAY)); - assertTrue(CorruptDeltaByteArrays.requiresSequentialReads((ParsedVersion) null, Encoding.DELTA_BYTE_ARRAY)); - assertTrue(CorruptDeltaByteArrays.requiresSequentialReads((SemanticVersion) null, Encoding.DELTA_BYTE_ARRAY)); - assertTrue(CorruptDeltaByteArrays.requiresSequentialReads( - "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.DELTA_BYTE_ARRAY)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads( - "parquet-mr version 1.6.0 (build abcd)", Encoding.DELTA_BINARY_PACKED)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads((String) null, Encoding.DELTA_LENGTH_BYTE_ARRAY)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads((ParsedVersion) null, Encoding.PLAIN)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads((SemanticVersion) null, Encoding.RLE)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads( - "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.RLE_DICTIONARY)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads( - "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.PLAIN_DICTIONARY)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads( - "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.BIT_PACKED)); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads( - "parquet-mr version 1.8.0 (build abcd)", Encoding.DELTA_BYTE_ARRAY)); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads( + "parquet-mr version 1.6.0 (build abcd)", Encoding.DELTA_BYTE_ARRAY)) + .isTrue(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads((String) null, Encoding.DELTA_BYTE_ARRAY)) + .isTrue(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads((ParsedVersion) null, Encoding.DELTA_BYTE_ARRAY)) + .isTrue(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads((SemanticVersion) null, Encoding.DELTA_BYTE_ARRAY)) + .isTrue(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads( + "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.DELTA_BYTE_ARRAY)) + .isTrue(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads( + "parquet-mr version 1.6.0 (build abcd)", Encoding.DELTA_BINARY_PACKED)) + .isFalse(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads((String) null, Encoding.DELTA_LENGTH_BYTE_ARRAY)) + .isFalse(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads((ParsedVersion) null, Encoding.PLAIN)) + .isFalse(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads((SemanticVersion) null, Encoding.RLE)) + .isFalse(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads( + "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.RLE_DICTIONARY)) + .isFalse(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads( + "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.PLAIN_DICTIONARY)) + .isFalse(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads( + "parquet-mr version 1.8.0-SNAPSHOT (build abcd)", Encoding.BIT_PACKED)) + .isFalse(); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads( + "parquet-mr version 1.8.0 (build abcd)", Encoding.DELTA_BYTE_ARRAY)) + .isFalse(); } @Test public void testEncodingRequiresSequentialRead() { ParsedVersion impala = new ParsedVersion("impala", "1.2.0", "abcd"); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads(impala, Encoding.DELTA_BYTE_ARRAY)); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads(impala, Encoding.DELTA_BYTE_ARRAY)) + .isFalse(); ParsedVersion broken = new ParsedVersion("parquet-mr", "1.8.0-SNAPSHOT", "abcd"); - assertTrue(CorruptDeltaByteArrays.requiresSequentialReads(broken, Encoding.DELTA_BYTE_ARRAY)); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads(broken, Encoding.DELTA_BYTE_ARRAY)) + .isTrue(); ParsedVersion fixed = new ParsedVersion("parquet-mr", "1.8.0", "abcd"); - assertFalse(CorruptDeltaByteArrays.requiresSequentialReads(fixed, Encoding.DELTA_BYTE_ARRAY)); + assertThat(CorruptDeltaByteArrays.requiresSequentialReads(fixed, Encoding.DELTA_BYTE_ARRAY)) + .isFalse(); } private DeltaByteArrayWriter getDeltaByteArrayWriter() { @@ -112,24 +124,19 @@ public void testReassemblyWithCorruptPage() throws Exception { DeltaByteArrayReader firstPageReader = new DeltaByteArrayReader(); firstPageReader.initFromPage(10, ByteBufferInputStream.wrap(firstPageBytes)); for (int i = 0; i < 10; i += 1) { - assertEquals(str(i), firstPageReader.readBytes().toStringUsingUTF8()); + assertThat(firstPageReader.readBytes().toStringUsingUTF8()).isEqualTo(str(i)); } DeltaByteArrayReader corruptPageReader = new DeltaByteArrayReader(); corruptPageReader.initFromPage(10, ByteBufferInputStream.wrap(corruptPageBytes)); - try { - corruptPageReader.readBytes(); - fail("Corrupt page did not throw an exception when read"); - } catch (ArrayIndexOutOfBoundsException e) { - // expected, this is a corrupt page - } + assertThatThrownBy(corruptPageReader::readBytes).isInstanceOf(ArrayIndexOutOfBoundsException.class); DeltaByteArrayReader secondPageReader = new DeltaByteArrayReader(); secondPageReader.initFromPage(10, ByteBufferInputStream.wrap(corruptPageBytes)); secondPageReader.setPreviousReader(firstPageReader); for (int i = 10; i < 20; i += 1) { - assertEquals(secondPageReader.readBytes().toStringUsingUTF8(), str(i)); + assertThat(secondPageReader.readBytes().toStringUsingUTF8()).isEqualTo(str(i)); } } @@ -152,7 +159,7 @@ public void testReassemblyWithoutCorruption() throws Exception { DeltaByteArrayReader firstPageReader = new DeltaByteArrayReader(); firstPageReader.initFromPage(10, ByteBufferInputStream.wrap(firstPageBytes)); for (int i = 0; i < 10; i += 1) { - assertEquals(firstPageReader.readBytes().toStringUsingUTF8(), str(i)); + assertThat(firstPageReader.readBytes().toStringUsingUTF8()).isEqualTo(str(i)); } DeltaByteArrayReader secondPageReader = new DeltaByteArrayReader(); @@ -160,7 +167,7 @@ public void testReassemblyWithoutCorruption() throws Exception { secondPageReader.setPreviousReader(firstPageReader); for (int i = 10; i < 20; i += 1) { - assertEquals(secondPageReader.readBytes().toStringUsingUTF8(), str(i)); + assertThat(secondPageReader.readBytes().toStringUsingUTF8()).isEqualTo(str(i)); } } @@ -183,14 +190,14 @@ public void testOldReassemblyWithoutCorruption() throws Exception { DeltaByteArrayReader firstPageReader = new DeltaByteArrayReader(); firstPageReader.initFromPage(10, ByteBufferInputStream.wrap(firstPageBytes)); for (int i = 0; i < 10; i += 1) { - assertEquals(firstPageReader.readBytes().toStringUsingUTF8(), str(i)); + assertThat(firstPageReader.readBytes().toStringUsingUTF8()).isEqualTo(str(i)); } DeltaByteArrayReader secondPageReader = new DeltaByteArrayReader(); secondPageReader.initFromPage(10, ByteBufferInputStream.wrap(secondPageBytes)); for (int i = 10; i < 20; i += 1) { - assertEquals(secondPageReader.readBytes().toStringUsingUTF8(), str(i)); + assertThat(secondPageReader.readBytes().toStringUsingUTF8()).isEqualTo(str(i)); } } @@ -262,7 +269,7 @@ public void addBinary(Binary value) { columnReader.consume(); } - Assert.assertEquals(values, actualValues); + assertThat(actualValues).isEqualTo(values); } @Test @@ -273,13 +280,17 @@ public void testPreviousReaderSetting() { DeltaByteArrayReader reader = new DeltaByteArrayReader(); reader.setPreviousReader(previousReader); - assertSame(previous, getPrevious(reader)); + assertThat(getPrevious(reader)).isSameAs(previous); reader.setPreviousReader(null); - assertSame("The previous field should have not changed", previous, getPrevious(reader)); + assertThat(getPrevious(reader)) + .as("The previous field should have not changed") + .isSameAs(previous); reader.setPreviousReader(Mockito.mock(DictionaryValuesReader.class)); - assertSame("The previous field should have not changed", previous, getPrevious(reader)); + assertThat(getPrevious(reader)) + .as("The previous field should have not changed") + .isSameAs(previous); } private Binary getPrevious(DeltaByteArrayReader reader) { diff --git a/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemColumn.java b/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemColumn.java index 1ce30006d3..3de8797bc9 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemColumn.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemColumn.java @@ -20,8 +20,7 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.BINARY; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.column.ColumnDescriptor; import org.apache.parquet.column.ColumnReader; @@ -47,7 +46,7 @@ public class TestMemColumn { private static final Logger LOG = LoggerFactory.getLogger(TestMemColumn.class); @Test - public void testMemColumn() throws Exception { + public void testMemColumn() { MessageType schema = MessageTypeParser.parseMessageType("message msg { required group foo { required int64 bar; } }"); ColumnDescriptor path = schema.getColumnDescription(new String[] {"foo", "bar"}); @@ -60,26 +59,20 @@ public void testMemColumn() throws Exception { ColumnReader columnReader = getColumnReader(memPageStore, path, schema); for (int i = 0; i < columnReader.getTotalValueCount(); i++) { - assertEquals(columnReader.getCurrentRepetitionLevel(), 0); - assertEquals(columnReader.getCurrentDefinitionLevel(), 0); - assertEquals(columnReader.getLong(), 42); + assertThat(columnReader.getCurrentRepetitionLevel()).isEqualTo(0); + assertThat(columnReader.getCurrentDefinitionLevel()).isEqualTo(0); + assertThat(columnReader.getLong()).isEqualTo(42); columnReader.consume(); } } - private ColumnWriter getColumnWriter(ColumnDescriptor path, MemPageStore memPageStore) { - ColumnWriteStoreV1 memColumnsStore = newColumnWriteStoreImpl(memPageStore); - ColumnWriter columnWriter = memColumnsStore.getColumnWriter(path); - return columnWriter; - } - private ColumnReader getColumnReader(MemPageStore memPageStore, ColumnDescriptor path, MessageType schema) { return new ColumnReadStoreImpl(memPageStore, new DummyRecordConverter(schema).getRootConverter(), schema, null) .getColumnReader(path); } @Test - public void testMemColumnBinary() throws Exception { + public void testMemColumnBinary() { MessageType mt = MessageTypeParser.parseMessageType("message msg { required group foo { required binary bar; } }"); String[] col = new String[] {"foo", "bar"}; @@ -96,15 +89,15 @@ public void testMemColumnBinary() throws Exception { ColumnReader columnReader = getColumnReader(memPageStore, path, mt); for (int i = 0; i < columnReader.getTotalValueCount(); i++) { - assertEquals(columnReader.getCurrentRepetitionLevel(), 0); - assertEquals(columnReader.getCurrentDefinitionLevel(), 0); - assertEquals(columnReader.getBinary().toStringUsingUTF8(), "42"); + assertThat(columnReader.getCurrentRepetitionLevel()).isEqualTo(0); + assertThat(columnReader.getCurrentDefinitionLevel()).isEqualTo(0); + assertThat(columnReader.getBinary().toStringUsingUTF8()).isEqualTo("42"); columnReader.consume(); } } @Test - public void testMemColumnBinaryExceedIntMaxValue() throws Exception { + public void testMemColumnBinaryExceedIntMaxValue() { MessageType mt = MessageTypeParser.parseMessageType( "message msg { required group v (LIST) { repeated group list { optional binary element; } } }"); String[] col = new String[] {"v", "list", "element"}; @@ -124,14 +117,13 @@ public void testMemColumnBinaryExceedIntMaxValue() throws Exception { memColumnsStore.flush(); ColumnReader columnReader = getColumnReader(memPageStore, path, mt); - assertEquals( - "parquet page value-count should fit on the signed-int range", - columnReader.getTotalValueCount(), - (long) numRows * numEntries); + assertThat(columnReader.getTotalValueCount()) + .as("parquet page value-count should fit on the signed-int range") + .isEqualTo((long) numRows * numEntries); } @Test - public void testMemColumnSeveralPages() throws Exception { + public void testMemColumnSeveralPages() { MessageType mt = MessageTypeParser.parseMessageType("message msg { required group foo { required int64 bar; } }"); String[] col = new String[] {"foo", "bar"}; @@ -149,15 +141,15 @@ public void testMemColumnSeveralPages() throws Exception { ColumnReader columnReader = getColumnReader(memPageStore, path, mt); for (int i = 0; i < columnReader.getTotalValueCount(); i++) { - assertEquals(columnReader.getCurrentRepetitionLevel(), 0); - assertEquals(columnReader.getCurrentDefinitionLevel(), 0); - assertEquals(columnReader.getLong(), 42); + assertThat(columnReader.getCurrentRepetitionLevel()).isEqualTo(0); + assertThat(columnReader.getCurrentDefinitionLevel()).isEqualTo(0); + assertThat(columnReader.getLong()).isEqualTo(42); columnReader.consume(); } } @Test - public void testMemColumnSeveralPagesRepeated() throws Exception { + public void testMemColumnSeveralPagesRepeated() { MessageType mt = MessageTypeParser.parseMessageType("message msg { repeated group foo { repeated int64 bar; } }"); String[] col = new String[] {"foo", "bar"}; @@ -191,10 +183,10 @@ public void testMemColumnSeveralPagesRepeated() throws Exception { int r = rs[i % rs.length]; int d = ds[i % ds.length]; LOG.debug("read i: {}", i); - assertEquals("r row " + i, r, columnReader.getCurrentRepetitionLevel()); - assertEquals("d row " + i, d, columnReader.getCurrentDefinitionLevel()); + assertThat(columnReader.getCurrentRepetitionLevel()).isEqualTo(r); + assertThat(columnReader.getCurrentDefinitionLevel()).isEqualTo(d); if (d == 2) { - assertEquals("data row " + i, i, columnReader.getLong()); + assertThat(columnReader.getLong()).isEqualTo(i); } columnReader.consume(); ++i; @@ -245,7 +237,7 @@ public void testPageSize() { // Check that all the binary_col pages are <= 1024 bytes { PageReader binaryColPageReader = memPageStore.getPageReader(binaryCol); - assertEquals(1230, binaryColPageReader.getTotalValueCount()); + assertThat(binaryColPageReader.getTotalValueCount()).isEqualTo(1230); int pageCnt = 0; int valueCnt = 0; while (valueCnt < binaryColPageReader.getTotalValueCount()) { @@ -257,14 +249,16 @@ public void testPageSize() { pageCnt, page.getCompressedSize(), page.getIndexRowCount().get()); - assertTrue("Compressed size should be less than 1024", page.getCompressedSize() <= 1024); + assertThat(page.getCompressedSize()) + .as("Compressed size should be less than 1024") + .isLessThanOrEqualTo(1024); } } // Check that all the int32_col pages contain <= 10 rows { PageReader int32ColPageReader = memPageStore.getPageReader(int32Col); - assertEquals(1230, int32ColPageReader.getTotalValueCount()); + assertThat(int32ColPageReader.getTotalValueCount()).isEqualTo(1230); int pageCnt = 0; int valueCnt = 0; while (valueCnt < int32ColPageReader.getTotalValueCount()) { @@ -276,9 +270,9 @@ public void testPageSize() { pageCnt, page.getCompressedSize(), page.getIndexRowCount().get()); - assertTrue( - "Row count should be less than 10", - page.getIndexRowCount().get() <= 10); + assertThat(page.getIndexRowCount().get()) + .as("Row count should be less than 10") + .isLessThanOrEqualTo(10); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemPageStore.java b/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemPageStore.java index 41fc52d757..e0b6ae7489 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemPageStore.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/mem/TestMemPageStore.java @@ -20,9 +20,7 @@ import static org.apache.parquet.column.Encoding.BIT_PACKED; import static org.apache.parquet.column.Encoding.PLAIN; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import org.apache.parquet.bytes.BytesInput; @@ -60,7 +58,9 @@ public void test() throws IOException { long totalValueCount = pageReader.getTotalValueCount(); LOG.info("Total value count: " + totalValueCount); - assertEquals("Expected total value count to be 836 (4 pages * 209 values)", 836, totalValueCount); + assertThat(totalValueCount) + .as("Expected total value count to be 836 (4 pages * 209 values)") + .isEqualTo(836); int total = 0; int pageCount = 0; @@ -68,16 +68,24 @@ public void test() throws IOException { DataPage readPage = pageReader.readPage(); // Assert page was successfully read - assertNotNull("Page should not be null", readPage); + assertThat(readPage).as("Page should not be null").isNotNull(); // Assert page has expected value count - assertEquals("Each page should have 209 values", 209, readPage.getValueCount()); + assertThat(readPage.getValueCount()) + .as("Each page should have 209 values") + .isEqualTo(209); // Assert encodings when the implementation is DataPageV1 - assertTrue("Page should be an instance of DataPageV1", readPage instanceof DataPageV1); + assertThat(readPage).as("Page should be an instance of DataPageV1").isInstanceOf(DataPageV1.class); if (readPage instanceof DataPageV1) { DataPageV1 v1 = (DataPageV1) readPage; - assertEquals("Page repetition level encoding should be BIT_PACKED", BIT_PACKED, v1.getRlEncoding()); - assertEquals("Page definition level encoding should be BIT_PACKED", BIT_PACKED, v1.getDlEncoding()); - assertEquals("Page value encoding should be PLAIN", PLAIN, v1.getValueEncoding()); + assertThat(v1.getRlEncoding()) + .as("Page repetition level encoding should be BIT_PACKED") + .isEqualTo(BIT_PACKED); + assertThat(v1.getDlEncoding()) + .as("Page definition level encoding should be BIT_PACKED") + .isEqualTo(BIT_PACKED); + assertThat(v1.getValueEncoding()) + .as("Page value encoding should be PLAIN") + .isEqualTo(PLAIN); } total += readPage.getValueCount(); @@ -85,7 +93,7 @@ public void test() throws IOException { } while (total < totalValueCount); // Assert we read exactly the expected number of pages and values - assertEquals("Should have read 4 pages", 4, pageCount); - assertEquals("Total values read should match totalValueCount", totalValueCount, total); + assertThat(pageCount).as("Should have read 4 pages").isEqualTo(4); + assertThat(total).as("Total values read should match totalValueCount").isEqualTo(totalValueCount); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestSizeStatistics.java b/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestSizeStatistics.java index 786d2be2c3..a798813e0a 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestSizeStatistics.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestSizeStatistics.java @@ -18,14 +18,13 @@ */ package org.apache.parquet.column.statistics; -import java.util.Collections; -import java.util.List; -import java.util.Optional; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import org.apache.parquet.io.api.Binary; import org.apache.parquet.schema.LogicalTypeAnnotation; import org.apache.parquet.schema.PrimitiveType; import org.apache.parquet.schema.Types; -import org.junit.Assert; import org.junit.Test; public class TestSizeStatistics { @@ -46,9 +45,9 @@ public void testAddBinaryType() { builder.add(1, 0); builder.add(1, 1); SizeStatistics statistics = builder.build(); - Assert.assertEquals(Optional.of(3L), statistics.getUnencodedByteArrayDataBytes()); - Assert.assertEquals(List.of(3L, 3L, 1L), statistics.getRepetitionLevelHistogram()); - Assert.assertEquals(List.of(2L, 2L, 3L), statistics.getDefinitionLevelHistogram()); + assertThat(statistics.getUnencodedByteArrayDataBytes()).contains(3L); + assertThat(statistics.getRepetitionLevelHistogram()).containsExactly(3L, 3L, 1L); + assertThat(statistics.getDefinitionLevelHistogram()).containsExactly(2L, 2L, 3L); } @Test @@ -66,9 +65,9 @@ public void testAddNonBinaryType() { builder.add(1, 0); builder.add(1, 0); SizeStatistics statistics = builder.build(); - Assert.assertEquals(Optional.empty(), statistics.getUnencodedByteArrayDataBytes()); - Assert.assertEquals(List.of(2L, 4L), statistics.getRepetitionLevelHistogram()); - Assert.assertEquals(Collections.emptyList(), statistics.getDefinitionLevelHistogram()); + assertThat(statistics.getUnencodedByteArrayDataBytes()).isEmpty(); + assertThat(statistics.getRepetitionLevelHistogram()).containsExactly(2L, 4L); + assertThat(statistics.getDefinitionLevelHistogram()).isEmpty(); } @Test @@ -88,9 +87,9 @@ public void testMergeStatistics() { builder2.add(0, 1, Binary.fromString("e")); SizeStatistics statistics2 = builder2.build(); statistics1.mergeStatistics(statistics2); - Assert.assertEquals(Optional.of(5L), statistics1.getUnencodedByteArrayDataBytes()); - Assert.assertEquals(List.of(3L, 1L, 1L), statistics1.getRepetitionLevelHistogram()); - Assert.assertEquals(List.of(1L, 3L, 1L), statistics1.getDefinitionLevelHistogram()); + assertThat(statistics1.getUnencodedByteArrayDataBytes()).contains(5L); + assertThat(statistics1.getRepetitionLevelHistogram()).containsExactly(3L, 1L, 1L); + assertThat(statistics1.getDefinitionLevelHistogram()).containsExactly(1L, 3L, 1L); } @Test @@ -105,7 +104,9 @@ public void testMergeThrowException() { SizeStatistics.Builder builder2 = SizeStatistics.newBuilder(type2, 1, 1); SizeStatistics statistics1 = builder1.build(); SizeStatistics statistics2 = builder2.build(); - Assert.assertThrows(IllegalArgumentException.class, () -> statistics1.mergeStatistics(statistics2)); + assertThatThrownBy(() -> statistics1.mergeStatistics(statistics2)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot merge SizeStatistics of different types"); } @Test @@ -121,9 +122,9 @@ public void testCopyStatistics() { builder.add(2, 2, Binary.fromString("c")); SizeStatistics statistics = builder.build(); SizeStatistics copy = statistics.copy(); - Assert.assertEquals(Optional.of(3L), copy.getUnencodedByteArrayDataBytes()); - Assert.assertEquals(List.of(1L, 1L, 1L), copy.getRepetitionLevelHistogram()); - Assert.assertEquals(List.of(1L, 1L, 1L), copy.getDefinitionLevelHistogram()); + assertThat(copy.getUnencodedByteArrayDataBytes()).contains(3L); + assertThat(copy.getRepetitionLevelHistogram()).containsExactly(1L, 1L, 1L); + assertThat(copy.getDefinitionLevelHistogram()).containsExactly(1L, 1L, 1L); } @Test @@ -132,13 +133,13 @@ public void testOmittedHistogram() { .as(LogicalTypeAnnotation.stringType()) .named("a"); SizeStatistics statistics = new SizeStatistics(type, 1024L, null, null); - Assert.assertEquals(Optional.of(1024L), statistics.getUnencodedByteArrayDataBytes()); - Assert.assertEquals(Collections.emptyList(), statistics.getRepetitionLevelHistogram()); - Assert.assertEquals(Collections.emptyList(), statistics.getDefinitionLevelHistogram()); + assertThat(statistics.getUnencodedByteArrayDataBytes()).contains(1024L); + assertThat(statistics.getRepetitionLevelHistogram()).isEmpty(); + assertThat(statistics.getDefinitionLevelHistogram()).isEmpty(); SizeStatistics copy = statistics.copy(); - Assert.assertEquals(Optional.of(1024L), copy.getUnencodedByteArrayDataBytes()); - Assert.assertEquals(Collections.emptyList(), copy.getRepetitionLevelHistogram()); - Assert.assertEquals(Collections.emptyList(), copy.getDefinitionLevelHistogram()); + assertThat(copy.getUnencodedByteArrayDataBytes()).contains(1024L); + assertThat(copy.getRepetitionLevelHistogram()).isEmpty(); + assertThat(copy.getDefinitionLevelHistogram()).isEmpty(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatistics.java b/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatistics.java index 92eaa7a302..c189b6721a 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatistics.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatistics.java @@ -31,11 +31,9 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT64; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT96; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.data.Offset.offset; import java.nio.ByteBuffer; import java.util.Locale; @@ -57,20 +55,20 @@ public class TestStatistics { @Test public void testNumNulls() { IntStatistics stats = new IntStatistics(); - assertTrue(stats.isNumNullsSet()); - assertEquals(stats.getNumNulls(), 0); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(0); stats.incrementNumNulls(); stats.incrementNumNulls(); stats.incrementNumNulls(); stats.incrementNumNulls(); - assertEquals(stats.getNumNulls(), 4); + assertThat(stats.getNumNulls()).isEqualTo(4); stats.incrementNumNulls(5); - assertEquals(stats.getNumNulls(), 9); + assertThat(stats.getNumNulls()).isEqualTo(9); stats.setNumNulls(22); - assertEquals(stats.getNumNulls(), 22); + assertThat(stats.getNumNulls()).isEqualTo(22); } @Test @@ -82,8 +80,8 @@ public void testIntMinMax() { for (int i : integerArray) { stats.updateStats(i); } - assertEquals(stats.getMax(), 66); - assertEquals(stats.getMin(), 0); + assertThat(stats.getMax()).isEqualTo(66); + assertThat(stats.getMin()).isEqualTo(0); // Test negative values integerArray = new int[] {-11, 3, -14, 54, -66, 8, 0, -23, 54}; @@ -92,36 +90,34 @@ public void testIntMinMax() { for (int i : integerArray) { statsNeg.updateStats(i); } - assertEquals(statsNeg.getMax(), 54); - assertEquals(statsNeg.getMin(), -66); + assertThat(statsNeg.getMax()).isEqualTo(54); + assertThat(statsNeg.getMin()).isEqualTo(-66); - assertTrue(statsNeg.compareMaxToValue(55) < 0); - assertTrue(statsNeg.compareMaxToValue(54) == 0); - assertTrue(statsNeg.compareMaxToValue(5) > 0); - assertTrue(statsNeg.compareMinToValue(0) < 0); - assertTrue(statsNeg.compareMinToValue(-66) == 0); - assertTrue(statsNeg.compareMinToValue(-67) > 0); + assertThat(statsNeg.compareMaxToValue(55)).isNegative(); + assertThat(statsNeg.compareMaxToValue(54)).isZero(); + assertThat(statsNeg.compareMaxToValue(5)).isPositive(); + assertThat(statsNeg.compareMinToValue(0)).isNegative(); + assertThat(statsNeg.compareMinToValue(-66)).isZero(); + assertThat(statsNeg.compareMinToValue(-67)).isPositive(); // Test converting to and from byte[] byte[] intMaxBytes = statsNeg.getMaxBytes(); byte[] intMinBytes = statsNeg.getMinBytes(); - assertEquals( - ByteBuffer.wrap(intMaxBytes) + assertThat(ByteBuffer.wrap(intMaxBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getInt(), - 54); - assertEquals( - ByteBuffer.wrap(intMinBytes) + .getInt()) + .isEqualTo(54); + assertThat(ByteBuffer.wrap(intMinBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getInt(), - -66); + .getInt()) + .isEqualTo(-66); IntStatistics statsFromBytes = new IntStatistics(); statsFromBytes.setMinMaxFromBytes(intMinBytes, intMaxBytes); - assertEquals(statsFromBytes.getMax(), 54); - assertEquals(statsFromBytes.getMin(), -66); + assertThat(statsFromBytes.getMax()).isEqualTo(54); + assertThat(statsFromBytes.getMin()).isEqualTo(-66); integerArray = new int[] {Integer.MAX_VALUE, Integer.MIN_VALUE}; IntStatistics minMaxValues = new IntStatistics(); @@ -129,32 +125,30 @@ public void testIntMinMax() { for (int i : integerArray) { minMaxValues.updateStats(i); } - assertEquals(minMaxValues.getMax(), Integer.MAX_VALUE); - assertEquals(minMaxValues.getMin(), Integer.MIN_VALUE); + assertThat(minMaxValues.getMax()).isEqualTo(Integer.MAX_VALUE); + assertThat(minMaxValues.getMin()).isEqualTo(Integer.MIN_VALUE); // Test converting to and from byte[] for large and small values byte[] intMaxBytesMinMax = minMaxValues.getMaxBytes(); byte[] intMinBytesMinMax = minMaxValues.getMinBytes(); - assertEquals( - ByteBuffer.wrap(intMaxBytesMinMax) + assertThat(ByteBuffer.wrap(intMaxBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getInt(), - Integer.MAX_VALUE); - assertEquals( - ByteBuffer.wrap(intMinBytesMinMax) + .getInt()) + .isEqualTo(Integer.MAX_VALUE); + assertThat(ByteBuffer.wrap(intMinBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getInt(), - Integer.MIN_VALUE); + .getInt()) + .isEqualTo(Integer.MIN_VALUE); IntStatistics statsFromBytesMinMax = new IntStatistics(); statsFromBytesMinMax.setMinMaxFromBytes(intMinBytesMinMax, intMaxBytesMinMax); - assertEquals(statsFromBytesMinMax.getMax(), Integer.MAX_VALUE); - assertEquals(statsFromBytesMinMax.getMin(), Integer.MIN_VALUE); + assertThat(statsFromBytesMinMax.getMax()).isEqualTo(Integer.MAX_VALUE); + assertThat(statsFromBytesMinMax.getMin()).isEqualTo(Integer.MIN_VALUE); // Test print formatting - assertEquals(stats.toString(), "min: 0, max: 66, num_nulls: 0"); + assertThat(stats).asString().isEqualTo("min: 0, max: 66, num_nulls: 0"); } @Test @@ -166,8 +160,8 @@ public void testLongMinMax() { for (long l : longArray) { stats.updateStats(l); } - assertEquals(stats.getMax(), 1000); - assertEquals(stats.getMin(), 0); + assertThat(stats.getMax()).isEqualTo(1000); + assertThat(stats.getMin()).isEqualTo(0); // Test negative values longArray = new long[] {-101, 993, -9914, 54, -9, 89, 0, -23, 90}; @@ -176,36 +170,34 @@ public void testLongMinMax() { for (long l : longArray) { statsNeg.updateStats(l); } - assertEquals(statsNeg.getMax(), 993); - assertEquals(statsNeg.getMin(), -9914); + assertThat(statsNeg.getMax()).isEqualTo(993); + assertThat(statsNeg.getMin()).isEqualTo(-9914); - assertTrue(statsNeg.compareMaxToValue(994) < 0); - assertTrue(statsNeg.compareMaxToValue(993) == 0); - assertTrue(statsNeg.compareMaxToValue(-1000) > 0); - assertTrue(statsNeg.compareMinToValue(10000) < 0); - assertTrue(statsNeg.compareMinToValue(-9914) == 0); - assertTrue(statsNeg.compareMinToValue(-9915) > 0); + assertThat(statsNeg.compareMaxToValue(994)).isNegative(); + assertThat(statsNeg.compareMaxToValue(993)).isZero(); + assertThat(statsNeg.compareMaxToValue(-1000)).isPositive(); + assertThat(statsNeg.compareMinToValue(10000)).isNegative(); + assertThat(statsNeg.compareMinToValue(-9914)).isZero(); + assertThat(statsNeg.compareMinToValue(-9915)).isPositive(); // Test converting to and from byte[] byte[] longMaxBytes = statsNeg.getMaxBytes(); byte[] longMinBytes = statsNeg.getMinBytes(); - assertEquals( - ByteBuffer.wrap(longMaxBytes) + assertThat(ByteBuffer.wrap(longMaxBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getLong(), - 993); - assertEquals( - ByteBuffer.wrap(longMinBytes) + .getLong()) + .isEqualTo(993); + assertThat(ByteBuffer.wrap(longMinBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getLong(), - -9914); + .getLong()) + .isEqualTo(-9914); LongStatistics statsFromBytes = new LongStatistics(); statsFromBytes.setMinMaxFromBytes(longMinBytes, longMaxBytes); - assertEquals(statsFromBytes.getMax(), 993); - assertEquals(statsFromBytes.getMin(), -9914); + assertThat(statsFromBytes.getMax()).isEqualTo(993); + assertThat(statsFromBytes.getMin()).isEqualTo(-9914); longArray = new long[] {Long.MAX_VALUE, Long.MIN_VALUE}; LongStatistics minMaxValues = new LongStatistics(); @@ -213,32 +205,30 @@ public void testLongMinMax() { for (long l : longArray) { minMaxValues.updateStats(l); } - assertEquals(minMaxValues.getMax(), Long.MAX_VALUE); - assertEquals(minMaxValues.getMin(), Long.MIN_VALUE); + assertThat(minMaxValues.getMax()).isEqualTo(Long.MAX_VALUE); + assertThat(minMaxValues.getMin()).isEqualTo(Long.MIN_VALUE); // Test converting to and from byte[] for large and small values byte[] longMaxBytesMinMax = minMaxValues.getMaxBytes(); byte[] longMinBytesMinMax = minMaxValues.getMinBytes(); - assertEquals( - ByteBuffer.wrap(longMaxBytesMinMax) + assertThat(ByteBuffer.wrap(longMaxBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getLong(), - Long.MAX_VALUE); - assertEquals( - ByteBuffer.wrap(longMinBytesMinMax) + .getLong()) + .isEqualTo(Long.MAX_VALUE); + assertThat(ByteBuffer.wrap(longMinBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getLong(), - Long.MIN_VALUE); + .getLong()) + .isEqualTo(Long.MIN_VALUE); LongStatistics statsFromBytesMinMax = new LongStatistics(); statsFromBytesMinMax.setMinMaxFromBytes(longMinBytesMinMax, longMaxBytesMinMax); - assertEquals(statsFromBytesMinMax.getMax(), Long.MAX_VALUE); - assertEquals(statsFromBytesMinMax.getMin(), Long.MIN_VALUE); + assertThat(statsFromBytesMinMax.getMax()).isEqualTo(Long.MAX_VALUE); + assertThat(statsFromBytesMinMax.getMin()).isEqualTo(Long.MIN_VALUE); // Test print formatting - assertEquals(stats.toString(), "min: 0, max: 1000, num_nulls: 0"); + assertThat(stats).asString().isEqualTo("min: 0, max: 1000, num_nulls: 0"); } @Test @@ -250,8 +240,8 @@ public void testFloatMinMax() { for (float f : floatArray) { stats.updateStats(f); } - assertEquals(stats.getMax(), 553.6f, 1e-10); - assertEquals(stats.getMin(), 0.0001f, 1e-10); + assertThat(stats.getMax()).isCloseTo(553.6f, offset(1e-10f)); + assertThat(stats.getMin()).isCloseTo(0.0001f, offset(1e-10f)); // Test negative values floatArray = new float[] {-1.5f, -44.5f, -412.99f, 0.65f, -5.6f, -100.6f, 0.0001f, -23.0f, -3.6f}; @@ -260,38 +250,34 @@ public void testFloatMinMax() { for (float f : floatArray) { statsNeg.updateStats(f); } - assertEquals(statsNeg.getMax(), 0.65f, 1e-10); - assertEquals(statsNeg.getMin(), -412.99f, 1e-10); + assertThat(statsNeg.getMax()).isCloseTo(0.65f, offset(1e-10f)); + assertThat(statsNeg.getMin()).isCloseTo(-412.99f, offset(1e-10f)); - assertTrue(statsNeg.compareMaxToValue(1) < 0); - assertTrue(statsNeg.compareMaxToValue(0.65F) == 0); - assertTrue(statsNeg.compareMaxToValue(0.649F) > 0); - assertTrue(statsNeg.compareMinToValue(-412.98F) < 0); - assertTrue(statsNeg.compareMinToValue(-412.99F) == 0); - assertTrue(statsNeg.compareMinToValue(-450) > 0); + assertThat(statsNeg.compareMaxToValue(1)).isNegative(); + assertThat(statsNeg.compareMaxToValue(0.65F)).isZero(); + assertThat(statsNeg.compareMaxToValue(0.649F)).isPositive(); + assertThat(statsNeg.compareMinToValue(-412.98F)).isNegative(); + assertThat(statsNeg.compareMinToValue(-412.99F)).isZero(); + assertThat(statsNeg.compareMinToValue(-450)).isPositive(); // Test converting to and from byte[] byte[] floatMaxBytes = statsNeg.getMaxBytes(); byte[] floatMinBytes = statsNeg.getMinBytes(); - assertEquals( - ByteBuffer.wrap(floatMaxBytes) + assertThat(ByteBuffer.wrap(floatMaxBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getFloat(), - 0.65f, - 1e-10); - assertEquals( - ByteBuffer.wrap(floatMinBytes) + .getFloat()) + .isCloseTo(0.65f, offset(1e-10f)); + assertThat(ByteBuffer.wrap(floatMinBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getFloat(), - -412.99f, - 1e-10); + .getFloat()) + .isCloseTo(-412.99f, offset(1e-10f)); FloatStatistics statsFromBytes = new FloatStatistics(); statsFromBytes.setMinMaxFromBytes(floatMinBytes, floatMaxBytes); - assertEquals(statsFromBytes.getMax(), 0.65f, 1e-10); - assertEquals(statsFromBytes.getMin(), -412.99f, 1e-10); + assertThat(statsFromBytes.getMax()).isCloseTo(0.65f, offset(1e-10f)); + assertThat(statsFromBytes.getMin()).isCloseTo(-412.99f, offset(1e-10f)); floatArray = new float[] {Float.MAX_VALUE, Float.MIN_VALUE}; FloatStatistics minMaxValues = new FloatStatistics(); @@ -299,34 +285,30 @@ public void testFloatMinMax() { for (float f : floatArray) { minMaxValues.updateStats(f); } - assertEquals(minMaxValues.getMax(), Float.MAX_VALUE, 1e-10); - assertEquals(minMaxValues.getMin(), Float.MIN_VALUE, 1e-10); + assertThat(minMaxValues.getMax()).isCloseTo(Float.MAX_VALUE, offset(1e-10f)); + assertThat(minMaxValues.getMin()).isCloseTo(Float.MIN_VALUE, offset(1e-10f)); // Test converting to and from byte[] for large and small values byte[] floatMaxBytesMinMax = minMaxValues.getMaxBytes(); byte[] floatMinBytesMinMax = minMaxValues.getMinBytes(); - assertEquals( - ByteBuffer.wrap(floatMaxBytesMinMax) + assertThat(ByteBuffer.wrap(floatMaxBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getFloat(), - Float.MAX_VALUE, - 1e-10); - assertEquals( - ByteBuffer.wrap(floatMinBytesMinMax) + .getFloat()) + .isCloseTo(Float.MAX_VALUE, offset(1e-10f)); + assertThat(ByteBuffer.wrap(floatMinBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getFloat(), - Float.MIN_VALUE, - 1e-10); + .getFloat()) + .isCloseTo(Float.MIN_VALUE, offset(1e-10f)); FloatStatistics statsFromBytesMinMax = new FloatStatistics(); statsFromBytesMinMax.setMinMaxFromBytes(floatMinBytesMinMax, floatMaxBytesMinMax); - assertEquals(statsFromBytesMinMax.getMax(), Float.MAX_VALUE, 1e-10); - assertEquals(statsFromBytesMinMax.getMin(), Float.MIN_VALUE, 1e-10); + assertThat(statsFromBytesMinMax.getMax()).isCloseTo(Float.MAX_VALUE, offset(1e-10f)); + assertThat(statsFromBytesMinMax.getMin()).isCloseTo(Float.MIN_VALUE, offset(1e-10f)); // Test print formatting - assertEquals("min: 1.0E-4, max: 553.6, num_nulls: 0", stats.toString()); + assertThat(stats).asString().isEqualTo("min: 1.0E-4, max: 553.6, num_nulls: 0"); } @Test @@ -338,8 +320,8 @@ public void testDoubleMinMax() { for (double d : doubleArray) { stats.updateStats(d); } - assertEquals(stats.getMax(), 944.5d, 1e-10); - assertEquals(stats.getMin(), 0.00001d, 1e-10); + assertThat(stats.getMax()).isCloseTo(944.5d, offset(1e-10)); + assertThat(stats.getMin()).isCloseTo(0.00001d, offset(1e-10)); // Test negative values doubleArray = new double[] {-81.5d, -944.5d, 2.002d, -334.5d, -5.6d, -0.001d, -0.00001d, 23.0d, -3.6d}; @@ -348,38 +330,34 @@ public void testDoubleMinMax() { for (double d : doubleArray) { statsNeg.updateStats(d); } - assertEquals(statsNeg.getMax(), 23.0d, 1e-10); - assertEquals(statsNeg.getMin(), -944.5d, 1e-10); + assertThat(statsNeg.getMax()).isCloseTo(23.0d, offset(1e-10)); + assertThat(statsNeg.getMin()).isCloseTo(-944.5d, offset(1e-10)); - assertTrue(statsNeg.compareMaxToValue(23.0001D) < 0); - assertTrue(statsNeg.compareMaxToValue(23D) == 0); - assertTrue(statsNeg.compareMaxToValue(0D) > 0); - assertTrue(statsNeg.compareMinToValue(-400D) < 0); - assertTrue(statsNeg.compareMinToValue(-944.5D) == 0); - assertTrue(statsNeg.compareMinToValue(-944.500001D) > 0); + assertThat(statsNeg.compareMaxToValue(23.0001D)).isNegative(); + assertThat(statsNeg.compareMaxToValue(23D)).isZero(); + assertThat(statsNeg.compareMaxToValue(0D)).isPositive(); + assertThat(statsNeg.compareMinToValue(-400D)).isNegative(); + assertThat(statsNeg.compareMinToValue(-944.5D)).isZero(); + assertThat(statsNeg.compareMinToValue(-944.500001D)).isPositive(); // Test converting to and from byte[] byte[] doubleMaxBytes = statsNeg.getMaxBytes(); byte[] doubleMinBytes = statsNeg.getMinBytes(); - assertEquals( - ByteBuffer.wrap(doubleMaxBytes) + assertThat(ByteBuffer.wrap(doubleMaxBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getDouble(), - 23.0d, - 1e-10); - assertEquals( - ByteBuffer.wrap(doubleMinBytes) + .getDouble()) + .isCloseTo(23.0d, offset(1e-10)); + assertThat(ByteBuffer.wrap(doubleMinBytes) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getDouble(), - -944.5d, - 1e-10); + .getDouble()) + .isCloseTo(-944.5d, offset(1e-10)); DoubleStatistics statsFromBytes = new DoubleStatistics(); statsFromBytes.setMinMaxFromBytes(doubleMinBytes, doubleMaxBytes); - assertEquals(statsFromBytes.getMax(), 23.0d, 1e-10); - assertEquals(statsFromBytes.getMin(), -944.5d, 1e-10); + assertThat(statsFromBytes.getMax()).isCloseTo(23.0d, offset(1e-10)); + assertThat(statsFromBytes.getMin()).isCloseTo(-944.5d, offset(1e-10)); doubleArray = new double[] {Double.MAX_VALUE, Double.MIN_VALUE}; DoubleStatistics minMaxValues = new DoubleStatistics(); @@ -387,34 +365,30 @@ public void testDoubleMinMax() { for (double d : doubleArray) { minMaxValues.updateStats(d); } - assertEquals(minMaxValues.getMax(), Double.MAX_VALUE, 1e-10); - assertEquals(minMaxValues.getMin(), Double.MIN_VALUE, 1e-10); + assertThat(minMaxValues.getMax()).isCloseTo(Double.MAX_VALUE, offset(1e-10)); + assertThat(minMaxValues.getMin()).isCloseTo(Double.MIN_VALUE, offset(1e-10)); // Test converting to and from byte[] for large and small values byte[] doubleMaxBytesMinMax = minMaxValues.getMaxBytes(); byte[] doubleMinBytesMinMax = minMaxValues.getMinBytes(); - assertEquals( - ByteBuffer.wrap(doubleMaxBytesMinMax) + assertThat(ByteBuffer.wrap(doubleMaxBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getDouble(), - Double.MAX_VALUE, - 1e-10); - assertEquals( - ByteBuffer.wrap(doubleMinBytesMinMax) + .getDouble()) + .isCloseTo(Double.MAX_VALUE, offset(1e-10)); + assertThat(ByteBuffer.wrap(doubleMinBytesMinMax) .order(java.nio.ByteOrder.LITTLE_ENDIAN) - .getDouble(), - Double.MIN_VALUE, - 1e-10); + .getDouble()) + .isCloseTo(Double.MIN_VALUE, offset(1e-10)); DoubleStatistics statsFromBytesMinMax = new DoubleStatistics(); statsFromBytesMinMax.setMinMaxFromBytes(doubleMinBytesMinMax, doubleMaxBytesMinMax); - assertEquals(statsFromBytesMinMax.getMax(), Double.MAX_VALUE, 1e-10); - assertEquals(statsFromBytesMinMax.getMin(), Double.MIN_VALUE, 1e-10); + assertThat(statsFromBytesMinMax.getMax()).isCloseTo(Double.MAX_VALUE, offset(1e-10)); + assertThat(statsFromBytesMinMax.getMin()).isCloseTo(Double.MIN_VALUE, offset(1e-10)); // Test print formatting - assertEquals("min: 1.0E-5, max: 944.5, num_nulls: 0", stats.toString()); + assertThat(stats).asString().isEqualTo("min: 1.0E-5, max: 944.5, num_nulls: 0"); } @Test @@ -430,8 +404,8 @@ public void testFloatingPointStringIndependentFromLocale() { try { // Set the locale to French where the decimal separator would be ',' instead of '.' Locale.setDefault(Locale.FRENCH); - assertEquals("min: 123.456, max: 123.456, num_nulls: 0", floatStats.toString()); - assertEquals("min: 12345.6789, max: 12345.6789, num_nulls: 0", doubleStats.toString()); + assertThat(floatStats).asString().isEqualTo("min: 123.456, max: 123.456, num_nulls: 0"); + assertThat(doubleStats).asString().isEqualTo("min: 12345.6789, max: 12345.6789, num_nulls: 0"); } finally { Locale.setDefault(defaultLocale); } @@ -446,8 +420,8 @@ public void testBooleanMinMax() { for (boolean i : booleanArray) { statsTrue.updateStats(i); } - assertTrue(statsTrue.getMax()); - assertTrue(statsTrue.getMin()); + assertThat(statsTrue.getMax()).isTrue(); + assertThat(statsTrue.getMin()).isTrue(); // Test all false booleanArray = new boolean[] {false, false, false}; @@ -456,8 +430,8 @@ public void testBooleanMinMax() { for (boolean i : booleanArray) { statsFalse.updateStats(i); } - assertFalse(statsFalse.getMax()); - assertFalse(statsFalse.getMin()); + assertThat(statsFalse.getMax()).isFalse(); + assertThat(statsFalse.getMin()).isFalse(); booleanArray = new boolean[] {false, true, false}; BooleanStatistics statsBoth = new BooleanStatistics(); @@ -465,24 +439,24 @@ public void testBooleanMinMax() { for (boolean i : booleanArray) { statsBoth.updateStats(i); } - assertTrue(statsBoth.getMax()); - assertFalse(statsBoth.getMin()); + assertThat(statsBoth.getMax()).isTrue(); + assertThat(statsBoth.getMin()).isFalse(); // Test converting to and from byte[] byte[] boolMaxBytes = statsBoth.getMaxBytes(); byte[] boolMinBytes = statsBoth.getMinBytes(); - assertEquals(boolMaxBytes[0] & 255, 1); - assertEquals(boolMinBytes[0] & 255, 0); + assertThat(boolMaxBytes[0] & 255).isEqualTo(1); + assertThat(boolMinBytes[0] & 255).isEqualTo(0); BooleanStatistics statsFromBytes = new BooleanStatistics(); statsFromBytes.setMinMaxFromBytes(boolMinBytes, boolMaxBytes); - assertTrue(statsFromBytes.getMax()); - assertFalse(statsFromBytes.getMin()); + assertThat(statsFromBytes.getMax()).isTrue(); + assertThat(statsFromBytes.getMin()).isFalse(); // Test print formatting - assertEquals(statsBoth.toString(), "min: false, max: true, num_nulls: 0"); + assertThat(statsBoth).asString().isEqualTo("min: false, max: true, num_nulls: 0"); } @Test @@ -496,8 +470,8 @@ public void testBinaryMinMax() { for (String s : stringArray) { stats.updateStats(Binary.fromString(s)); } - assertEquals(stats.genericGetMax(), Binary.fromString("world")); - assertEquals(stats.genericGetMin(), Binary.fromString("a")); + assertThat(stats.genericGetMax()).isEqualTo(Binary.fromString("world")); + assertThat(stats.genericGetMin()).isEqualTo(Binary.fromString("a")); // Test empty string stringArray = new String[] {"", "", "", "", ""}; @@ -506,24 +480,24 @@ public void testBinaryMinMax() { for (String s : stringArray) { statsEmpty.updateStats(Binary.fromString(s)); } - assertEquals(statsEmpty.genericGetMax(), Binary.fromString("")); - assertEquals(statsEmpty.genericGetMin(), Binary.fromString("")); + assertThat(statsEmpty.genericGetMax()).isEqualTo(Binary.fromString("")); + assertThat(statsEmpty.genericGetMin()).isEqualTo(Binary.fromString("")); // Test converting to and from byte[] byte[] stringMaxBytes = stats.getMaxBytes(); byte[] stringMinBytes = stats.getMinBytes(); - assertEquals(new String(stringMaxBytes), "world"); - assertEquals(new String(stringMinBytes), "a"); + assertThat(new String(stringMaxBytes)).isEqualTo("world"); + assertThat(new String(stringMinBytes)).isEqualTo("a"); BinaryStatistics statsFromBytes = (BinaryStatistics) Statistics.createStats(type); statsFromBytes.setMinMaxFromBytes(stringMinBytes, stringMaxBytes); - assertEquals(statsFromBytes.genericGetMax(), Binary.fromString("world")); - assertEquals(statsFromBytes.genericGetMin(), Binary.fromString("a")); + assertThat(statsFromBytes.genericGetMax()).isEqualTo(Binary.fromString("world")); + assertThat(statsFromBytes.genericGetMin()).isEqualTo(Binary.fromString("a")); // Test print formatting - assertEquals(stats.toString(), "min: a, max: world, num_nulls: 0"); + assertThat(stats).asString().isEqualTo("min: a, max: world, num_nulls: 0"); } @Test @@ -540,8 +514,8 @@ public void testBinaryMinMaxForReusedBackingByteArray() { bytes[0] = 15; stats.updateStats(value); - assertArrayEquals(new byte[] {20}, stats.getMaxBytes()); - assertArrayEquals(new byte[] {10}, stats.getMinBytes()); + assertThat(stats.getMaxBytes()).isEqualTo(new byte[] {20}); + assertThat(stats.getMinBytes()).isEqualTo(new byte[] {10}); } @Test @@ -569,8 +543,8 @@ private void testMergingIntStats() { intStats2.updateStats(s); } intStats.mergeStatistics(intStats2); - assertEquals(intStats.getMax(), 5); - assertEquals(intStats.getMin(), 0); + assertThat(intStats.getMax()).isEqualTo(5); + assertThat(intStats.getMin()).isEqualTo(0); integerArray = new int[] {-1, -100, 100}; IntStatistics intStats3 = new IntStatistics(); @@ -579,8 +553,8 @@ private void testMergingIntStats() { } intStats.mergeStatistics(intStats3); - assertEquals(intStats.getMax(), 100); - assertEquals(intStats.getMin(), -100); + assertThat(intStats.getMax()).isEqualTo(100); + assertThat(intStats.getMin()).isEqualTo(-100); } private void testMergingLongStats() { @@ -598,8 +572,8 @@ private void testMergingLongStats() { longStats2.updateStats(s); } longStats.mergeStatistics(longStats2); - assertEquals(longStats.getMax(), 5l); - assertEquals(longStats.getMin(), 0l); + assertThat(longStats.getMax()).isEqualTo(5l); + assertThat(longStats.getMin()).isEqualTo(0l); longArray = new long[] {-1l, -100l, 100l}; LongStatistics longStats3 = new LongStatistics(); @@ -608,8 +582,8 @@ private void testMergingLongStats() { } longStats.mergeStatistics(longStats3); - assertEquals(longStats.getMax(), 100l); - assertEquals(longStats.getMin(), -100l); + assertThat(longStats.getMax()).isEqualTo(100l); + assertThat(longStats.getMin()).isEqualTo(-100l); } private void testMergingFloatStats() { @@ -627,8 +601,8 @@ private void testMergingFloatStats() { floatStats2.updateStats(s); } floatStats.mergeStatistics(floatStats2); - assertEquals(floatStats.getMax(), 98.3f, 1e-10); - assertEquals(floatStats.getMin(), 0.0001f, 1e-10); + assertThat(floatStats.getMax()).isCloseTo(98.3f, offset(1e-10f)); + assertThat(floatStats.getMin()).isCloseTo(0.0001f, offset(1e-10f)); floatArray = new float[] {-1.91f, -100.9f, 100.54f}; FloatStatistics floatStats3 = new FloatStatistics(); @@ -637,8 +611,8 @@ private void testMergingFloatStats() { } floatStats.mergeStatistics(floatStats3); - assertEquals(floatStats.getMax(), 100.54f, 1e-10); - assertEquals(floatStats.getMin(), -100.9f, 1e-10); + assertThat(floatStats.getMax()).isCloseTo(100.54f, offset(1e-10f)); + assertThat(floatStats.getMin()).isCloseTo(-100.9f, offset(1e-10f)); } private void testMergingDoubleStats() { @@ -656,8 +630,8 @@ private void testMergingDoubleStats() { doubleStats2.updateStats(s); } doubleStats.mergeStatistics(doubleStats2); - assertEquals(doubleStats.getMax(), 98.3d, 1e-10); - assertEquals(doubleStats.getMin(), 0.0001d, 1e-10); + assertThat(doubleStats.getMax()).isCloseTo(98.3d, offset(1e-10)); + assertThat(doubleStats.getMin()).isCloseTo(0.0001d, offset(1e-10)); doubleArray = new double[] {-1.91d, -100.9d, 100.54d}; DoubleStatistics doubleStats3 = new DoubleStatistics(); @@ -666,8 +640,8 @@ private void testMergingDoubleStats() { } doubleStats.mergeStatistics(doubleStats3); - assertEquals(doubleStats.getMax(), 100.54d, 1e-10); - assertEquals(doubleStats.getMin(), -100.9d, 1e-10); + assertThat(doubleStats.getMax()).isCloseTo(100.54d, offset(1e-10)); + assertThat(doubleStats.getMin()).isCloseTo(-100.9d, offset(1e-10)); } private void testMergingBooleanStats() { @@ -685,8 +659,8 @@ private void testMergingBooleanStats() { booleanStats2.updateStats(s); } booleanStats.mergeStatistics(booleanStats2); - assertEquals(booleanStats.getMax(), true); - assertEquals(booleanStats.getMin(), false); + assertThat(booleanStats.getMax()).isTrue(); + assertThat(booleanStats.getMin()).isFalse(); booleanArray = new boolean[] {false, false, false, false}; BooleanStatistics booleanStats3 = new BooleanStatistics(); @@ -695,8 +669,8 @@ private void testMergingBooleanStats() { } booleanStats.mergeStatistics(booleanStats3); - assertEquals(booleanStats.getMax(), true); - assertEquals(booleanStats.getMin(), false); + assertThat(booleanStats.getMax()).isTrue(); + assertThat(booleanStats.getMin()).isFalse(); } private void testMergingStringStats() { @@ -714,8 +688,8 @@ private void testMergingStringStats() { stats2.updateStats(Binary.fromString(s)); } stats.mergeStatistics(stats2); - assertEquals(stats.getMax(), Binary.fromString("zzzz")); - assertEquals(stats.getMin(), Binary.fromString("a")); + assertThat(stats.getMax()).isEqualTo(Binary.fromString("zzzz")); + assertThat(stats.getMin()).isEqualTo(Binary.fromString("a")); stringArray = new String[] {"", "good", "testing"}; BinaryStatistics stats3 = new BinaryStatistics(); @@ -724,8 +698,8 @@ private void testMergingStringStats() { } stats.mergeStatistics(stats3); - assertEquals(stats.getMax(), Binary.fromString("zzzz")); - assertEquals(stats.getMin(), Binary.fromString("")); + assertThat(stats.getMax()).isEqualTo(Binary.fromString("zzzz")); + assertThat(stats.getMin()).isEqualTo(Binary.fromString("")); } @Test @@ -771,32 +745,32 @@ public void testBuilder() { private void testBuilder(PrimitiveType type, Object min, byte[] minBytes, Object max, byte[] maxBytes) { Statistics.Builder builder = Statistics.getBuilderForReading(type); Statistics stats = builder.build(); - assertTrue(stats.isEmpty()); - assertFalse(stats.isNumNullsSet()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isEmpty()).isTrue(); + assertThat(stats.isNumNullsSet()).isFalse(); + assertThat(stats.hasNonNullValue()).isFalse(); builder = Statistics.getBuilderForReading(type); stats = builder.withNumNulls(0).withMin(minBytes).build(); - assertFalse(stats.isEmpty()); - assertTrue(stats.isNumNullsSet()); - assertFalse(stats.hasNonNullValue()); - assertEquals(0, stats.getNumNulls()); + assertThat(stats.isEmpty()).isFalse(); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.hasNonNullValue()).isFalse(); + assertThat(stats.getNumNulls()).isEqualTo(0); builder = Statistics.getBuilderForReading(type); stats = builder.withNumNulls(11).withMax(maxBytes).build(); - assertFalse(stats.isEmpty()); - assertTrue(stats.isNumNullsSet()); - assertFalse(stats.hasNonNullValue()); - assertEquals(11, stats.getNumNulls()); + assertThat(stats.isEmpty()).isFalse(); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.hasNonNullValue()).isFalse(); + assertThat(stats.getNumNulls()).isEqualTo(11); builder = Statistics.getBuilderForReading(type); stats = builder.withNumNulls(42).withMin(minBytes).withMax(maxBytes).build(); - assertFalse(stats.isEmpty()); - assertTrue(stats.isNumNullsSet()); - assertTrue(stats.hasNonNullValue()); - assertEquals(42, stats.getNumNulls()); - assertEquals(min, stats.genericGetMin()); - assertEquals(max, stats.genericGetMax()); + assertThat(stats.isEmpty()).isFalse(); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.hasNonNullValue()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(42); + assertThat(stats.genericGetMin()).isEqualTo(min); + assertThat(stats.genericGetMax()).isEqualTo(max); } @Test @@ -807,48 +781,60 @@ public void testSpecBuilderForFloat() { .withMax(intToBytes(floatToIntBits(42.0f))) .withNumNulls(0) .build(); - assertTrue(stats.isNumNullsSet()); - assertEquals(0, stats.getNumNulls()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(0); + assertThat(stats.hasNonNullValue()).isFalse(); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(intToBytes(floatToIntBits(-42.0f))) .withMax(intToBytes(floatToIntBits(Float.NaN))) .withNumNulls(11) .build(); - assertTrue(stats.isNumNullsSet()); - assertEquals(11, stats.getNumNulls()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(11); + assertThat(stats.hasNonNullValue()).isFalse(); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(intToBytes(floatToIntBits(Float.NaN))) .withMax(intToBytes(floatToIntBits(Float.NaN))) .withNumNulls(42) .build(); - assertTrue(stats.isNumNullsSet()); - assertEquals(42, stats.getNumNulls()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(42); + assertThat(stats.hasNonNullValue()).isFalse(); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(intToBytes(floatToIntBits(0.0f))) .withMax(intToBytes(floatToIntBits(42.0f))) .build(); - assertEquals(0, Float.compare(-0.0f, (Float) stats.genericGetMin())); - assertEquals(0, Float.compare(42.0f, (Float) stats.genericGetMax())); + assertThat((Float) stats.genericGetMin()) + .usingComparator(Float::compare) + .isEqualByComparingTo(-0.0f); + assertThat((Float) stats.genericGetMax()) + .usingComparator(Float::compare) + .isEqualByComparingTo(42.0f); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(intToBytes(floatToIntBits(-42.0f))) .withMax(intToBytes(floatToIntBits(-0.0f))) .build(); - assertEquals(0, Float.compare(-42.0f, (Float) stats.genericGetMin())); - assertEquals(0, Float.compare(0.0f, (Float) stats.genericGetMax())); + assertThat((Float) stats.genericGetMin()) + .usingComparator(Float::compare) + .isEqualByComparingTo(-42.0f); + assertThat((Float) stats.genericGetMax()) + .usingComparator(Float::compare) + .isEqualByComparingTo(0.0f); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(intToBytes(floatToIntBits(0.0f))) .withMax(intToBytes(floatToIntBits(-0.0f))) .build(); - assertEquals(0, Float.compare(-0.0f, (Float) stats.genericGetMin())); - assertEquals(0, Float.compare(0.0f, (Float) stats.genericGetMax())); + assertThat((Float) stats.genericGetMin()) + .usingComparator(Float::compare) + .isEqualByComparingTo(-0.0f); + assertThat((Float) stats.genericGetMax()) + .usingComparator(Float::compare) + .isEqualByComparingTo(0.0f); } @Test @@ -859,48 +845,60 @@ public void testSpecBuilderForDouble() { .withMax(longToBytes(doubleToLongBits(42.0))) .withNumNulls(0) .build(); - assertTrue(stats.isNumNullsSet()); - assertEquals(0, stats.getNumNulls()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(0); + assertThat(stats.hasNonNullValue()).isFalse(); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(longToBytes(doubleToLongBits(-42.0))) .withMax(longToBytes(doubleToLongBits(Double.NaN))) .withNumNulls(11) .build(); - assertTrue(stats.isNumNullsSet()); - assertEquals(11, stats.getNumNulls()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(11); + assertThat(stats.hasNonNullValue()).isFalse(); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(longToBytes(doubleToLongBits(Double.NaN))) .withMax(longToBytes(doubleToLongBits(Double.NaN))) .withNumNulls(42) .build(); - assertTrue(stats.isNumNullsSet()); - assertEquals(42, stats.getNumNulls()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isNumNullsSet()).isTrue(); + assertThat(stats.getNumNulls()).isEqualTo(42); + assertThat(stats.hasNonNullValue()).isFalse(); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(longToBytes(doubleToLongBits(0.0))) .withMax(longToBytes(doubleToLongBits(42.0))) .build(); - assertEquals(0, Double.compare(-0.0, (Double) stats.genericGetMin())); - assertEquals(0, Double.compare(42.0, (Double) stats.genericGetMax())); + assertThat((Double) stats.genericGetMin()) + .usingComparator(Double::compare) + .isEqualByComparingTo(-0.0); + assertThat((Double) stats.genericGetMax()) + .usingComparator(Double::compare) + .isEqualByComparingTo(42.0); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(longToBytes(doubleToLongBits(-42.0))) .withMax(longToBytes(doubleToLongBits(-0.0))) .build(); - assertEquals(0, Double.compare(-42.0, (Double) stats.genericGetMin())); - assertEquals(0, Double.compare(0.0, (Double) stats.genericGetMax())); + assertThat((Double) stats.genericGetMin()) + .usingComparator(Double::compare) + .isEqualByComparingTo(-42.0); + assertThat((Double) stats.genericGetMax()) + .usingComparator(Double::compare) + .isEqualByComparingTo(0.0); builder = Statistics.getBuilderForReading(type); stats = builder.withMin(longToBytes(doubleToLongBits(0.0))) .withMax(longToBytes(doubleToLongBits(-0.0))) .build(); - assertEquals(0, Double.compare(-0.0, (Double) stats.genericGetMin())); - assertEquals(0, Double.compare(0.0, (Double) stats.genericGetMax())); + assertThat((Double) stats.genericGetMin()) + .usingComparator(Double::compare) + .isEqualByComparingTo(-0.0); + assertThat((Double) stats.genericGetMax()) + .usingComparator(Double::compare) + .isEqualByComparingTo(0.0); } @Test @@ -908,24 +906,38 @@ public void testNoopStatistics() { // Test basic max/min integerArray = new int[] {1, 3, 14, 54, 66, 8, 0, 23, 54}; Statistics stats = Statistics.noopStats(new PrimitiveType(REQUIRED, INT32, "int32")); - assertTrue(stats.isEmpty()); + assertThat(stats.isEmpty()).isTrue(); for (int i : integerArray) { stats.updateStats(i); } - assertEquals(stats.getNumNulls(), -1); - assertFalse(stats.hasNonNullValue()); - assertFalse(stats.isNumNullsSet()); - assertTrue(stats.isEmpty()); - - assertThrows(UnsupportedOperationException.class, stats::genericGetMax); - assertThrows(UnsupportedOperationException.class, stats::genericGetMin); - assertThrows(UnsupportedOperationException.class, stats::getMaxBytes); - assertThrows(UnsupportedOperationException.class, stats::getMinBytes); - assertThrows(UnsupportedOperationException.class, stats::maxAsString); - assertThrows(UnsupportedOperationException.class, stats::minAsString); - assertThrows(UnsupportedOperationException.class, () -> stats.isSmallerThan(0)); + assertThat(stats.getNumNulls()).isEqualTo(-1); + assertThat(stats.hasNonNullValue()).isFalse(); + assertThat(stats.isNumNullsSet()).isFalse(); + assertThat(stats.isEmpty()).isTrue(); + + assertThatThrownBy(stats::genericGetMax) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("genericGetMax is not supported by org.apache.parquet.column.statistics.NoopStatistics"); + assertThatThrownBy(stats::genericGetMin) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("genericGetMin is not supported by org.apache.parquet.column.statistics.NoopStatistics"); + assertThatThrownBy(stats::getMaxBytes) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("getMaxBytes is not supported by org.apache.parquet.column.statistics.NoopStatistics"); + assertThatThrownBy(stats::getMinBytes) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("getMinBytes is not supported by org.apache.parquet.column.statistics.NoopStatistics"); + assertThatThrownBy(stats::maxAsString) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("genericGetMax is not supported by org.apache.parquet.column.statistics.NoopStatistics"); + assertThatThrownBy(stats::minAsString) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("genericGetMin is not supported by org.apache.parquet.column.statistics.NoopStatistics"); + assertThatThrownBy(() -> stats.isSmallerThan(0)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage("isSmallerThan is not supported by org.apache.parquet.column.statistics.NoopStatistics"); } @Test @@ -936,6 +948,6 @@ public void testBinaryIsSmallerThanNoOverflowForLargeValues() { stats.updateStats(fakeLarge); // min.length() + max.length() = 2^31, must not overflow int to negative - assertFalse(stats.isSmallerThan(4096)); + assertThat(stats.isSmallerThan(4096)).isFalse(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatisticsNanCount.java b/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatisticsNanCount.java index a1c47ada1a..815f1004c2 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatisticsNanCount.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/statistics/TestStatisticsNanCount.java @@ -18,9 +18,8 @@ */ package org.apache.parquet.column.statistics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import org.apache.parquet.bytes.BytesUtils; import org.apache.parquet.io.api.Binary; @@ -73,10 +72,10 @@ public void testFloatNanCountMixedValues() { stats.updateStats(Float.NaN); stats.updateStats(3.0f); - assertTrue(stats.isNanCountSet()); - assertEquals(2, stats.getNanCount()); - assertEquals(1.0f, stats.getMin(), 0.0f); - assertEquals(3.0f, stats.getMax(), 0.0f); + assertThat(stats.isNanCountSet()).isTrue(); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(stats.getMin()).isCloseTo(1.0f, offset(0.0f)); + assertThat(stats.getMax()).isCloseTo(3.0f, offset(0.0f)); } @Test @@ -85,9 +84,9 @@ public void testFloatNanCountAllNaN() { stats.updateStats(Float.NaN); stats.updateStats(Float.NaN); - assertTrue(stats.isNanCountSet()); - assertEquals(2, stats.getNanCount()); - assertFalse(stats.hasNonNullValue()); + assertThat(stats.isNanCountSet()).isTrue(); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(stats.hasNonNullValue()).isFalse(); } @Test @@ -96,8 +95,8 @@ public void testFloatNanCountNoNaN() { stats.updateStats(1.0f); stats.updateStats(2.0f); - assertTrue(stats.isNanCountSet()); - assertEquals(0, stats.getNanCount()); + assertThat(stats.isNanCountSet()).isTrue(); + assertThat(stats.getNanCount()).isEqualTo(0); } @Test @@ -107,10 +106,10 @@ public void testDoubleNanCountMixedValues() { stats.updateStats(Double.NaN); stats.updateStats(2.0); - assertTrue(stats.isNanCountSet()); - assertEquals(1, stats.getNanCount()); - assertEquals(1.0, stats.getMin(), 0.0); - assertEquals(2.0, stats.getMax(), 0.0); + assertThat(stats.isNanCountSet()).isTrue(); + assertThat(stats.getNanCount()).isEqualTo(1); + assertThat(stats.getMin()).isCloseTo(1.0, offset(0.0)); + assertThat(stats.getMax()).isCloseTo(2.0, offset(0.0)); } @Test @@ -120,11 +119,11 @@ public void testFloat16NanCountMixedValues() { stats.updateStats(FLOAT16_NAN); stats.updateStats(FLOAT16_TWO); - assertTrue(stats.isNanCountSet()); - assertEquals(1, stats.getNanCount()); - assertTrue(stats.hasNonNullValue()); - assertEquals(FLOAT16_ONE, stats.genericGetMin()); - assertEquals(FLOAT16_TWO, stats.genericGetMax()); + assertThat(stats.isNanCountSet()).isTrue(); + assertThat(stats.getNanCount()).isEqualTo(1); + assertThat(stats.hasNonNullValue()).isTrue(); + assertThat(stats.genericGetMin()).isEqualTo(FLOAT16_ONE); + assertThat(stats.genericGetMax()).isEqualTo(FLOAT16_TWO); } @Test @@ -132,8 +131,8 @@ public void testFloat16NanCountNoNaN() { Float16Statistics stats = (Float16Statistics) Statistics.createStats(FLOAT16_TYPE); stats.updateStats(FLOAT16_ONE); - assertTrue(stats.isNanCountSet()); - assertEquals(0, stats.getNanCount()); + assertThat(stats.isNanCountSet()).isTrue(); + assertThat(stats.getNanCount()).isEqualTo(0); } @Test @@ -148,7 +147,7 @@ public void testMergeNanCounts() { stats2.updateStats(Float.NaN); stats1.mergeStatistics(stats2); - assertEquals(3, stats1.getNanCount()); + assertThat(stats1.getNanCount()).isEqualTo(3); } @Test @@ -159,9 +158,9 @@ public void testCopyPreservesNanCount() { stats.updateStats(Float.NaN); FloatStatistics copy = stats.copy(); - assertEquals(stats.getNanCount(), copy.getNanCount()); - assertTrue(copy.isNanCountSet()); - assertEquals(2, copy.getNanCount()); + assertThat(copy.getNanCount()).isEqualTo(stats.getNanCount()); + assertThat(copy.isNanCountSet()).isTrue(); + assertThat(copy.getNanCount()).isEqualTo(2); } @Test @@ -174,10 +173,10 @@ public void testFloatBuilderIEEE754KeepsNanMinMax() { .withNumNulls(0) .build(); - assertTrue(stats.hasNonNullValue()); - assertTrue(Float.isNaN(((FloatStatistics) stats).getMin())); - assertTrue(Float.isNaN(((FloatStatistics) stats).getMax())); - assertEquals(10, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isTrue(); + assertThat(((FloatStatistics) stats).getMin()).isNaN(); + assertThat(((FloatStatistics) stats).getMax()).isNaN(); + assertThat(stats.getNanCount()).isEqualTo(10); } @Test @@ -187,9 +186,9 @@ public void testFloatBuilderTypeDefinedDropsNanMinMax() { Statistics stats = builder.withMin(nanBytes).withMax(nanBytes).withNumNulls(0).build(); - assertFalse(stats.hasNonNullValue()); - assertFalse(Float.isNaN(((FloatStatistics) stats).getMin())); - assertFalse(Float.isNaN(((FloatStatistics) stats).getMax())); + assertThat(stats.hasNonNullValue()).isFalse(); + assertThat(((FloatStatistics) stats).getMin()).isNotNaN(); + assertThat(((FloatStatistics) stats).getMax()).isNotNaN(); } @Test @@ -202,10 +201,10 @@ public void testDoubleBuilderIEEE754KeepsNanMinMax() { .withNumNulls(0) .build(); - assertTrue(stats.hasNonNullValue()); - assertTrue(Double.isNaN(((DoubleStatistics) stats).getMin())); - assertTrue(Double.isNaN(((DoubleStatistics) stats).getMax())); - assertEquals(10, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isTrue(); + assertThat(((DoubleStatistics) stats).getMin()).isNaN(); + assertThat(((DoubleStatistics) stats).getMax()).isNaN(); + assertThat(stats.getNanCount()).isEqualTo(10); } @Test @@ -214,10 +213,10 @@ public void testFloatIEEE754NanOnlySetsHasNonNullValue() { stats.updateStats(Float.NaN); stats.updateStats(Float.NaN); - assertTrue(stats.hasNonNullValue()); - assertTrue(Float.isNaN(stats.getMin())); - assertTrue(Float.isNaN(stats.getMax())); - assertEquals(2, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isTrue(); + assertThat(stats.getMin()).isNaN(); + assertThat(stats.getMax()).isNaN(); + assertThat(stats.getNanCount()).isEqualTo(2); } @Test @@ -225,10 +224,10 @@ public void testDoubleIEEE754NanOnlySetsHasNonNullValue() { DoubleStatistics stats = (DoubleStatistics) Statistics.createStats(DOUBLE_IEEE754_TYPE); stats.updateStats(Double.NaN); - assertTrue(stats.hasNonNullValue()); - assertTrue(Double.isNaN(stats.getMin())); - assertTrue(Double.isNaN(stats.getMax())); - assertEquals(1, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isTrue(); + assertThat(stats.getMin()).isNaN(); + assertThat(stats.getMax()).isNaN(); + assertThat(stats.getNanCount()).isEqualTo(1); } @Test @@ -236,10 +235,10 @@ public void testFloat16IEEE754NanOnlySetsHasNonNullValue() { IEEE754Float16Statistics stats = (IEEE754Float16Statistics) Statistics.createStats(FLOAT16_IEEE754_TYPE); stats.updateStats(FLOAT16_NAN); - assertTrue(stats.hasNonNullValue()); - assertEquals(FLOAT16_NAN, stats.genericGetMin()); - assertEquals(FLOAT16_NAN, stats.genericGetMax()); - assertEquals(1, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isTrue(); + assertThat(stats.genericGetMin()).isEqualTo(FLOAT16_NAN); + assertThat(stats.genericGetMax()).isEqualTo(FLOAT16_NAN); + assertThat(stats.getNanCount()).isEqualTo(1); } @Test @@ -250,9 +249,9 @@ public void testFloatIEEE754AllNaNTracksNaNRange() { stats.updateStats(maxNaN); stats.updateStats(minNaN); - assertEquals(2, stats.getNanCount()); - assertEquals(0x7fc00001, Float.floatToRawIntBits(stats.getMin())); - assertEquals(0x7fffffff, Float.floatToRawIntBits(stats.getMax())); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(Float.floatToRawIntBits(stats.getMin())).isEqualTo(0x7fc00001); + assertThat(Float.floatToRawIntBits(stats.getMax())).isEqualTo(0x7fffffff); } @Test @@ -263,9 +262,9 @@ public void testDoubleIEEE754AllNaNTracksNaNRange() { stats.updateStats(maxNaN); stats.updateStats(minNaN); - assertEquals(2, stats.getNanCount()); - assertEquals(0x7ff0000000000001L, Double.doubleToRawLongBits(stats.getMin())); - assertEquals(0x7fffffffffffffffL, Double.doubleToRawLongBits(stats.getMax())); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(Double.doubleToRawLongBits(stats.getMin())).isEqualTo(0x7ff0000000000001L); + assertThat(Double.doubleToRawLongBits(stats.getMax())).isEqualTo(0x7fffffffffffffffL); } @Test @@ -274,11 +273,9 @@ public void testFloat16IEEE754AllNaNTracksNaNRange() { stats.updateStats(FLOAT16_NAN_LARGE); stats.updateStats(FLOAT16_NAN_SMALL); - assertEquals(2, stats.getNanCount()); - assertEquals( - FLOAT16_NAN_SMALL.get2BytesLittleEndian(), stats.genericGetMin().get2BytesLittleEndian()); - assertEquals( - FLOAT16_NAN_LARGE.get2BytesLittleEndian(), stats.genericGetMax().get2BytesLittleEndian()); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(stats.genericGetMin().get2BytesLittleEndian()).isEqualTo(FLOAT16_NAN_SMALL.get2BytesLittleEndian()); + assertThat(stats.genericGetMax().get2BytesLittleEndian()).isEqualTo(FLOAT16_NAN_LARGE.get2BytesLittleEndian()); } @Test @@ -289,9 +286,9 @@ public void testFloatIEEE754NonNaNReplacesAllNaNRange() { stats.updateStats(1.0f); stats.updateStats(2.0f); - assertEquals(2, stats.getNanCount()); - assertEquals(1.0f, stats.getMin(), 0.0f); - assertEquals(2.0f, stats.getMax(), 0.0f); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(stats.getMin()).isCloseTo(1.0f, offset(0.0f)); + assertThat(stats.getMax()).isCloseTo(2.0f, offset(0.0f)); } @Test @@ -302,9 +299,9 @@ public void testDoubleIEEE754NonNaNReplacesAllNaNRange() { stats.updateStats(1.0); stats.updateStats(2.0); - assertEquals(2, stats.getNanCount()); - assertEquals(1.0, stats.getMin(), 0.0); - assertEquals(2.0, stats.getMax(), 0.0); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(stats.getMin()).isCloseTo(1.0, offset(0.0)); + assertThat(stats.getMax()).isCloseTo(2.0, offset(0.0)); } @Test @@ -315,9 +312,9 @@ public void testFloat16IEEE754NonNaNReplacesAllNaNRange() { stats.updateStats(FLOAT16_ONE); stats.updateStats(FLOAT16_TWO); - assertEquals(2, stats.getNanCount()); - assertEquals(FLOAT16_ONE, stats.genericGetMin()); - assertEquals(FLOAT16_TWO, stats.genericGetMax()); + assertThat(stats.getNanCount()).isEqualTo(2); + assertThat(stats.genericGetMin()).isEqualTo(FLOAT16_ONE); + assertThat(stats.genericGetMax()).isEqualTo(FLOAT16_TWO); } @Test @@ -327,9 +324,9 @@ public void testFloatIEEE754NanExcludedFromMax() { stats.updateStats(Float.NaN); stats.updateStats(2.0f); - assertEquals(2.0f, stats.getMax(), 0.0f); - assertEquals(1.0f, stats.getMin(), 0.0f); - assertEquals(1, stats.getNanCount()); + assertThat(stats.getMax()).isCloseTo(2.0f, offset(0.0f)); + assertThat(stats.getMin()).isCloseTo(1.0f, offset(0.0f)); + assertThat(stats.getNanCount()).isEqualTo(1); } @Test @@ -339,9 +336,9 @@ public void testDoubleIEEE754NanExcludedFromMax() { stats.updateStats(Double.NaN); stats.updateStats(2.0); - assertEquals(2.0, stats.getMax(), 0.0); - assertEquals(1.0, stats.getMin(), 0.0); - assertEquals(1, stats.getNanCount()); + assertThat(stats.getMax()).isCloseTo(2.0, offset(0.0)); + assertThat(stats.getMin()).isCloseTo(1.0, offset(0.0)); + assertThat(stats.getNanCount()).isEqualTo(1); } @Test @@ -350,8 +347,8 @@ public void testFloatTypeDefinedNanOnlyDoesNotSetHasNonNullValue() { stats.updateStats(Float.NaN); stats.updateStats(Float.NaN); - assertFalse(stats.hasNonNullValue()); - assertEquals(2, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isFalse(); + assertThat(stats.getNanCount()).isEqualTo(2); } @Test @@ -359,8 +356,8 @@ public void testDoubleTypeDefinedNanOnlyDoesNotSetHasNonNullValue() { DoubleStatistics stats = (DoubleStatistics) Statistics.createStats(DOUBLE_TYPE); stats.updateStats(Double.NaN); - assertFalse(stats.hasNonNullValue()); - assertEquals(1, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isFalse(); + assertThat(stats.getNanCount()).isEqualTo(1); } @Test @@ -368,7 +365,7 @@ public void testFloat16TypeDefinedNanOnlyDoesNotSetHasNonNullValue() { Float16Statistics stats = (Float16Statistics) Statistics.createStats(FLOAT16_TYPE); stats.updateStats(FLOAT16_NAN); - assertFalse(stats.hasNonNullValue()); - assertEquals(1, stats.getNanCount()); + assertThat(stats.hasNonNullValue()).isFalse(); + assertThat(stats.getNanCount()).isEqualTo(1); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestBoundingBox.java b/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestBoundingBox.java index e02728614d..e82803e501 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestBoundingBox.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestBoundingBox.java @@ -18,7 +18,9 @@ */ package org.apache.parquet.column.statistics.geospatial; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; + import org.junit.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.CoordinateXYZM; @@ -37,11 +39,11 @@ public void testUpdate() { Point point2D = geometryFactory.createPoint(new Coordinate(10, 20)); boundingBox.update(point2D); - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(10.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(20.0, offset(0.0)); } @Test @@ -54,28 +56,28 @@ public void testEmptyGeometry() { boundingBox.update(emptyPoint); // Empty geometry should retain the initial state - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getXMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getXMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getYMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getYMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); // Test that after adding a non-empty geometry, values are updated correctly Point point = geometryFactory.createPoint(new Coordinate(10, 20)); boundingBox.update(point); - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(10.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(20.0, offset(0.0)); // Update with another empty geometry, should not change the bounds boundingBox.update(emptyPoint); - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(10.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(20.0, offset(0.0)); } @Test @@ -88,8 +90,8 @@ public void testNaNCoordinates() { boundingBox.update(nanPoint); // All values should be NaN after updating with all-NaN coordinates - Assert.assertTrue(boundingBox.isValid()); - Assert.assertTrue(boundingBox.isXYEmpty()); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.isXYEmpty()).isTrue(); // Reset the bounding box for the next test boundingBox = new BoundingBox(); @@ -99,8 +101,8 @@ public void testNaNCoordinates() { boundingBox.update(mixedPoint); // The valid X coordinate should be used, Y should remain at initial values - Assert.assertTrue(boundingBox.isValid()); - Assert.assertTrue(boundingBox.isXYEmpty()); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.isXYEmpty()).isTrue(); } @Test @@ -115,11 +117,11 @@ public void testNaNZAndMValues() { boundingBox.update(nanZPoint); // X and Y should be updated, but Z should remain NaN - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(10.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(20.0, offset(0.0)); // Add a point with valid Z value Coordinate coord2 = new Coordinate(15, 25, 30); // Using constructor with Z @@ -127,13 +129,13 @@ public void testNaNZAndMValues() { boundingBox.update(validZPoint); // X, Y, and Z values should now be updated - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(15.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(25.0, boundingBox.getYMax(), 0.0); - Assert.assertEquals(30.0, boundingBox.getZMin(), 0.0); - Assert.assertEquals(30.0, boundingBox.getZMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(15.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(25.0, offset(0.0)); + assertThat(boundingBox.getZMin()).isCloseTo(30.0, offset(0.0)); + assertThat(boundingBox.getZMax()).isCloseTo(30.0, offset(0.0)); // Reset the bounding box for M value tests boundingBox.reset(); @@ -144,15 +146,15 @@ public void testNaNZAndMValues() { boundingBox.update(nanMPoint); // X, Y, Z should be updated, but M should remain at initial values - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(10.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMax(), 0.0); - Assert.assertEquals(30.0, boundingBox.getZMin(), 0.0); - Assert.assertEquals(30.0, boundingBox.getZMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getMMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getMMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getZMin()).isCloseTo(30.0, offset(0.0)); + assertThat(boundingBox.getZMax()).isCloseTo(30.0, offset(0.0)); + assertThat(boundingBox.getMMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getMMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); // Add a point with valid M value CoordinateXYZM coordValidM = new CoordinateXYZM(15, 25, 35, 40); @@ -160,15 +162,15 @@ public void testNaNZAndMValues() { boundingBox.update(validMPoint); // All values including M should now be updated - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(15.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(25.0, boundingBox.getYMax(), 0.0); - Assert.assertEquals(30.0, boundingBox.getZMin(), 0.0); - Assert.assertEquals(35.0, boundingBox.getZMax(), 0.0); - Assert.assertEquals(40.0, boundingBox.getMMin(), 0.0); - Assert.assertEquals(40.0, boundingBox.getMMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(15.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(25.0, offset(0.0)); + assertThat(boundingBox.getZMin()).isCloseTo(30.0, offset(0.0)); + assertThat(boundingBox.getZMax()).isCloseTo(35.0, offset(0.0)); + assertThat(boundingBox.getMMin()).isCloseTo(40.0, offset(0.0)); + assertThat(boundingBox.getMMax()).isCloseTo(40.0, offset(0.0)); } @Test @@ -181,25 +183,25 @@ public void testAbort() { boundingBox.update(validPoint); // Check initial values - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(10.0, boundingBox.getXMin(), 0.0); - Assert.assertEquals(10.0, boundingBox.getXMax(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMin(), 0.0); - Assert.assertEquals(20.0, boundingBox.getYMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(20.0, offset(0.0)); // Abort the update boundingBox.abort(); // Check that values are reset to initial state - Assert.assertFalse(boundingBox.isValid()); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getXMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getXMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getYMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getYMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getZMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getZMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getMMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getMMax(), 0.0); + assertThat(boundingBox.isValid()).isFalse(); + assertThat(boundingBox.getXMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getZMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getZMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getMMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getMMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); } @Test @@ -207,15 +209,15 @@ public void testEmptyBoundingBox() { BoundingBox boundingBox = new BoundingBox(); // Assert all initial values are Infinity - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getXMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getXMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getYMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getYMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getZMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getZMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getMMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getMMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getZMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getZMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getMMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getMMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); } @Test @@ -225,15 +227,15 @@ public void testMergeBoundingBoxes() { boundingBox1.merge(boundingBox2); - Assert.assertTrue(boundingBox1.isValid()); - Assert.assertEquals(0.0, boundingBox1.getXMin(), 0.0); - Assert.assertEquals(15.0, boundingBox1.getXMax(), 0.0); - Assert.assertEquals(0.0, boundingBox1.getYMin(), 0.0); - Assert.assertEquals(30.0, boundingBox1.getYMax(), 0.0); - Assert.assertTrue(Double.isNaN(boundingBox1.getZMin())); - Assert.assertTrue(Double.isNaN(boundingBox1.getZMax())); - Assert.assertTrue(Double.isNaN(boundingBox1.getMMin())); - Assert.assertTrue(Double.isNaN(boundingBox1.getMMax())); + assertThat(boundingBox1.isValid()).isTrue(); + assertThat(boundingBox1.getXMin()).isCloseTo(0.0, offset(0.0)); + assertThat(boundingBox1.getXMax()).isCloseTo(15.0, offset(0.0)); + assertThat(boundingBox1.getYMin()).isCloseTo(0.0, offset(0.0)); + assertThat(boundingBox1.getYMax()).isCloseTo(30.0, offset(0.0)); + assertThat(boundingBox1.getZMin()).isNaN(); + assertThat(boundingBox1.getZMax()).isNaN(); + assertThat(boundingBox1.getMMin()).isNaN(); + assertThat(boundingBox1.getMMax()).isNaN(); } @Test @@ -243,15 +245,15 @@ public void testMergeWithEmptyBoundingBox() { boundingBox1.merge(emptyBoundingBox); - Assert.assertTrue(boundingBox1.isValid()); - Assert.assertEquals(0.0, boundingBox1.getXMin(), 0.0); - Assert.assertEquals(10.0, boundingBox1.getXMax(), 0.0); - Assert.assertEquals(0.0, boundingBox1.getYMin(), 0.0); - Assert.assertEquals(20.0, boundingBox1.getYMax(), 0.0); - Assert.assertTrue(Double.isNaN(boundingBox1.getZMin())); - Assert.assertTrue(Double.isNaN(boundingBox1.getZMax())); - Assert.assertTrue(Double.isNaN(boundingBox1.getMMin())); - Assert.assertTrue(Double.isNaN(boundingBox1.getMMax())); + assertThat(boundingBox1.isValid()).isTrue(); + assertThat(boundingBox1.getXMin()).isCloseTo(0.0, offset(0.0)); + assertThat(boundingBox1.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(boundingBox1.getYMin()).isCloseTo(0.0, offset(0.0)); + assertThat(boundingBox1.getYMax()).isCloseTo(20.0, offset(0.0)); + assertThat(boundingBox1.getZMin()).isNaN(); + assertThat(boundingBox1.getZMax()).isNaN(); + assertThat(boundingBox1.getMMin()).isNaN(); + assertThat(boundingBox1.getMMax()).isNaN(); } @Test @@ -260,15 +262,15 @@ public void testUpdateWithNullGeometry() { boundingBox.update(null); // Check that the bounding box remains in its initial state - Assert.assertTrue(boundingBox.isValid()); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getXMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getXMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getYMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getYMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getZMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getZMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, boundingBox.getMMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, boundingBox.getMMax(), 0.0); + assertThat(boundingBox.isValid()).isTrue(); + assertThat(boundingBox.getXMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getXMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getYMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getZMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getZMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getMMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(boundingBox.getMMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); } @Test @@ -280,7 +282,7 @@ public void testMergeWithNaNValues() { box1.merge(box2); // Check that box1 is invalid after the merge - Assert.assertFalse("Box1 should be invalid after the merge", box1.isValid()); + assertThat(box1.isValid()).as("Box1 should be invalid after the merge").isFalse(); } @Test @@ -290,18 +292,18 @@ public void testUpdateWithAllNaNCoordinatesAfterValid() { // First add a valid point box.update(gf.createPoint(new Coordinate(10, 20))); - Assert.assertTrue(box.isValid()); - Assert.assertEquals(10.0, box.getXMin(), 0.0); - Assert.assertEquals(10.0, box.getXMax(), 0.0); - Assert.assertEquals(20.0, box.getYMin(), 0.0); - Assert.assertEquals(20.0, box.getYMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(20.0, offset(0.0)); // Then update with all NaN coordinates - should not change valid values Point nanPoint = gf.createPoint(new Coordinate(Double.NaN, Double.NaN)); box.update(nanPoint); - Assert.assertFalse("Box should be empty after the merge", box.isXYEmpty()); - Assert.assertTrue("Box should be valid after the merge", box.isValid()); + assertThat(box.isXYEmpty()).as("Box should be empty after the merge").isFalse(); + assertThat(box.isValid()).as("Box should be valid after the merge").isTrue(); } @Test @@ -314,24 +316,24 @@ public void testUpdate3DPoint() { Point point3D = gf.createPoint(coord); box.update(point3D); - Assert.assertTrue(box.isValid()); - Assert.assertEquals(10.0, box.getXMin(), 0.0); - Assert.assertEquals(10.0, box.getXMax(), 0.0); - Assert.assertEquals(20.0, box.getYMin(), 0.0); - Assert.assertEquals(20.0, box.getYMax(), 0.0); - Assert.assertEquals(30.0, box.getZMin(), 0.0); - Assert.assertEquals(30.0, box.getZMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(20.0, offset(0.0)); + assertThat(box.getZMin()).isCloseTo(30.0, offset(0.0)); + assertThat(box.getZMax()).isCloseTo(30.0, offset(0.0)); // Add another 3D point with different Z box.update(gf.createPoint(new Coordinate(15, 25, 10))); - Assert.assertTrue(box.isValid()); - Assert.assertEquals(10.0, box.getXMin(), 0.0); - Assert.assertEquals(15.0, box.getXMax(), 0.0); - Assert.assertEquals(20.0, box.getYMin(), 0.0); - Assert.assertEquals(25.0, box.getYMax(), 0.0); - Assert.assertEquals(10.0, box.getZMin(), 0.0); - Assert.assertEquals(30.0, box.getZMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(15.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(25.0, offset(0.0)); + assertThat(box.getZMin()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getZMax()).isCloseTo(30.0, offset(0.0)); } @Test @@ -344,25 +346,25 @@ public void testUpdateWithMeasureValue() { Point pointWithM = gf.createPoint(coord); box.update(pointWithM); - Assert.assertTrue(box.isValid()); - Assert.assertEquals(10.0, box.getXMin(), 0.0); - Assert.assertEquals(10.0, box.getXMax(), 0.0); - Assert.assertEquals(20.0, box.getYMin(), 0.0); - Assert.assertEquals(20.0, box.getYMax(), 0.0); - Assert.assertEquals(5.0, box.getMMin(), 0.0); - Assert.assertEquals(5.0, box.getMMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(20.0, offset(0.0)); + assertThat(box.getMMin()).isCloseTo(5.0, offset(0.0)); + assertThat(box.getMMax()).isCloseTo(5.0, offset(0.0)); // Add another point with different M value CoordinateXYZM coord2 = new CoordinateXYZM(15, 25, Double.NaN, 10.0); box.update(gf.createPoint(coord2)); - Assert.assertTrue(box.isValid()); - Assert.assertEquals(10.0, box.getXMin(), 0.0); - Assert.assertEquals(15.0, box.getXMax(), 0.0); - Assert.assertEquals(20.0, box.getYMin(), 0.0); - Assert.assertEquals(25.0, box.getYMax(), 0.0); - Assert.assertEquals(5.0, box.getMMin(), 0.0); - Assert.assertEquals(10.0, box.getMMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(15.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(20.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(25.0, offset(0.0)); + assertThat(box.getMMin()).isCloseTo(5.0, offset(0.0)); + assertThat(box.getMMax()).isCloseTo(10.0, offset(0.0)); } @Test @@ -372,30 +374,30 @@ public void testResetAfterUpdate() { // Update with a valid point box.update(gf.createPoint(new Coordinate(10, 20))); - Assert.assertTrue(box.isValid()); - Assert.assertEquals(10.0, box.getXMin(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(10.0, offset(0.0)); // Reset the box box.reset(); // All values should be reset to their initial state - Assert.assertTrue(box.isValid()); - Assert.assertEquals(Double.POSITIVE_INFINITY, box.getXMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, box.getXMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, box.getYMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, box.getYMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, box.getZMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, box.getZMax(), 0.0); - Assert.assertEquals(Double.POSITIVE_INFINITY, box.getMMin(), 0.0); - Assert.assertEquals(Double.NEGATIVE_INFINITY, box.getMMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(box.getZMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(box.getZMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); + assertThat(box.getMMin()).isCloseTo(Double.POSITIVE_INFINITY, offset(0.0)); + assertThat(box.getMMax()).isCloseTo(Double.NEGATIVE_INFINITY, offset(0.0)); // Update after reset should work correctly box.update(gf.createPoint(new Coordinate(30, 40))); - Assert.assertTrue(box.isValid()); - Assert.assertEquals(30.0, box.getXMin(), 0.0); - Assert.assertEquals(30.0, box.getXMax(), 0.0); - Assert.assertEquals(40.0, box.getYMin(), 0.0); - Assert.assertEquals(40.0, box.getYMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(30.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(30.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(40.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(40.0, offset(0.0)); } @Test @@ -407,20 +409,20 @@ public void testCopy() { BoundingBox copy = original.copy(); // Verify all values are copied correctly - Assert.assertTrue(original.isValid()); - Assert.assertEquals(original.getXMin(), copy.getXMin(), 0.0); - Assert.assertEquals(original.getXMax(), copy.getXMax(), 0.0); - Assert.assertEquals(original.getYMin(), copy.getYMin(), 0.0); - Assert.assertEquals(original.getYMax(), copy.getYMax(), 0.0); - Assert.assertEquals(original.getZMin(), copy.getZMin(), 0.0); - Assert.assertEquals(original.getZMax(), copy.getZMax(), 0.0); - Assert.assertEquals(original.getMMin(), copy.getMMin(), 0.0); - Assert.assertEquals(original.getMMax(), copy.getMMax(), 0.0); + assertThat(original.isValid()).isTrue(); + assertThat(copy.getXMin()).isCloseTo(original.getXMin(), offset(0.0)); + assertThat(copy.getXMax()).isCloseTo(original.getXMax(), offset(0.0)); + assertThat(copy.getYMin()).isCloseTo(original.getYMin(), offset(0.0)); + assertThat(copy.getYMax()).isCloseTo(original.getYMax(), offset(0.0)); + assertThat(copy.getZMin()).isCloseTo(original.getZMin(), offset(0.0)); + assertThat(copy.getZMax()).isCloseTo(original.getZMax(), offset(0.0)); + assertThat(copy.getMMin()).isCloseTo(original.getMMin(), offset(0.0)); + assertThat(copy.getMMax()).isCloseTo(original.getMMax(), offset(0.0)); // Modify the copy and verify original is unchanged copy.reset(); - Assert.assertTrue(original.isValid()); - Assert.assertEquals(1.0, original.getXMin(), 0.0); + assertThat(original.isValid()).isTrue(); + assertThat(original.getXMin()).isCloseTo(1.0, offset(0.0)); } @Test @@ -434,25 +436,25 @@ public void testMergeWithAllNaNBox() { // Merge should keep existing values box1.merge(box2); - Assert.assertTrue(box1.isValid()); - Assert.assertEquals(1.0, box1.getXMin(), 0.0); - Assert.assertEquals(2.0, box1.getXMax(), 0.0); - Assert.assertEquals(3.0, box1.getYMin(), 0.0); - Assert.assertEquals(4.0, box1.getYMax(), 0.0); - Assert.assertEquals(5.0, box1.getZMin(), 0.0); - Assert.assertEquals(6.0, box1.getZMax(), 0.0); - Assert.assertEquals(7.0, box1.getMMin(), 0.0); - Assert.assertEquals(8.0, box1.getMMax(), 0.0); + assertThat(box1.isValid()).isTrue(); + assertThat(box1.getXMin()).isCloseTo(1.0, offset(0.0)); + assertThat(box1.getXMax()).isCloseTo(2.0, offset(0.0)); + assertThat(box1.getYMin()).isCloseTo(3.0, offset(0.0)); + assertThat(box1.getYMax()).isCloseTo(4.0, offset(0.0)); + assertThat(box1.getZMin()).isCloseTo(5.0, offset(0.0)); + assertThat(box1.getZMax()).isCloseTo(6.0, offset(0.0)); + assertThat(box1.getMMin()).isCloseTo(7.0, offset(0.0)); + assertThat(box1.getMMax()).isCloseTo(8.0, offset(0.0)); // Test the reverse - NaN box merging with valid box BoundingBox box3 = new BoundingBox(); box3.merge(box1); - Assert.assertTrue(box1.isValid()); - Assert.assertEquals(1.0, box3.getXMin(), 0.0); - Assert.assertEquals(2.0, box3.getXMax(), 0.0); - Assert.assertEquals(3.0, box3.getYMin(), 0.0); - Assert.assertEquals(4.0, box3.getYMax(), 0.0); + assertThat(box1.isValid()).isTrue(); + assertThat(box3.getXMin()).isCloseTo(1.0, offset(0.0)); + assertThat(box3.getXMax()).isCloseTo(2.0, offset(0.0)); + assertThat(box3.getYMin()).isCloseTo(3.0, offset(0.0)); + assertThat(box3.getYMax()).isCloseTo(4.0, offset(0.0)); } @Test @@ -467,11 +469,11 @@ public void testLineStringWithNaNCoordinates() { box.update(gf.createLineString(coords)); // The bounding box should include the valid coordinates and ignore NaN - Assert.assertTrue(box.isValid()); - Assert.assertEquals(0.0, box.getXMin(), 0.0); - Assert.assertEquals(2.0, box.getXMax(), 0.0); - Assert.assertEquals(1.0, box.getYMin(), 0.0); - Assert.assertEquals(3.0, box.getYMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(0.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(2.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(1.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(3.0, offset(0.0)); // Test with only one valid coordinate BoundingBox box2 = new BoundingBox(); @@ -481,11 +483,11 @@ public void testLineStringWithNaNCoordinates() { box2.update(gf.createLineString(coords2)); - Assert.assertTrue(box2.isValid()); - Assert.assertEquals(5.0, box2.getXMin(), 0.0); - Assert.assertEquals(5.0, box2.getXMax(), 0.0); - Assert.assertEquals(6.0, box2.getYMin(), 0.0); - Assert.assertEquals(6.0, box2.getYMax(), 0.0); + assertThat(box2.isValid()).isTrue(); + assertThat(box2.getXMin()).isCloseTo(5.0, offset(0.0)); + assertThat(box2.getXMax()).isCloseTo(5.0, offset(0.0)); + assertThat(box2.getYMin()).isCloseTo(6.0, offset(0.0)); + assertThat(box2.getYMax()).isCloseTo(6.0, offset(0.0)); // Test with all NaN coordinates BoundingBox box3 = new BoundingBox(); @@ -495,8 +497,8 @@ public void testLineStringWithNaNCoordinates() { box3.update(gf.createLineString(coords3)); // The bounding box should remain empty - Assert.assertTrue(box3.isValid()); - Assert.assertTrue(box3.isXYEmpty()); + assertThat(box3.isValid()).isTrue(); + assertThat(box3.isXYEmpty()).isTrue(); } @Test @@ -512,11 +514,11 @@ public void testLineStringWithPartialNaNCoordinates() { box.update(gf.createLineString(coords)); // The bounding box should include all valid coordinates - Assert.assertTrue(box.isValid()); - Assert.assertEquals(0.0, box.getXMin(), 0.0); - Assert.assertEquals(2.0, box.getXMax(), 0.0); - Assert.assertEquals(1.0, box.getYMin(), 0.0); - Assert.assertEquals(3.0, box.getYMax(), 0.0); + assertThat(box.isValid()).isTrue(); + assertThat(box.getXMin()).isCloseTo(0.0, offset(0.0)); + assertThat(box.getXMax()).isCloseTo(2.0, offset(0.0)); + assertThat(box.getYMin()).isCloseTo(1.0, offset(0.0)); + assertThat(box.getYMax()).isCloseTo(3.0, offset(0.0)); // Test with mixed NaN values in different components BoundingBox box2 = new BoundingBox(); @@ -524,8 +526,8 @@ public void testLineStringWithPartialNaNCoordinates() { new Coordinate[] {new Coordinate(Double.NaN, 5), new Coordinate(6, Double.NaN), new Coordinate(7, 8)}; box2.update(gf.createLineString(coords2)); - Assert.assertTrue(box2.isValid()); - Assert.assertTrue(box2.isXYEmpty()); + assertThat(box2.isValid()).isTrue(); + assertThat(box2.isXYEmpty()).isTrue(); } /** @@ -578,12 +580,12 @@ public void testMergingRowGroupBoundingBoxes() { rowGroup1.update(gf.createPoint(new Coordinate(2, Double.NaN))); // Verify Row Group 1 - Assert.assertTrue(rowGroup1.isValid()); - Assert.assertEquals(1.0, rowGroup1.getXMin(), 0.0); - Assert.assertEquals(2.0, rowGroup1.getXMax(), 0.0); - Assert.assertEquals(100.0, rowGroup1.getYMin(), 0.0); - Assert.assertEquals(100.0, rowGroup1.getYMax(), 0.0); - Assert.assertTrue(rowGroup1.isValid()); + assertThat(rowGroup1.isValid()).isTrue(); + assertThat(rowGroup1.getXMin()).isCloseTo(1.0, offset(0.0)); + assertThat(rowGroup1.getXMax()).isCloseTo(2.0, offset(0.0)); + assertThat(rowGroup1.getYMin()).isCloseTo(100.0, offset(0.0)); + assertThat(rowGroup1.getYMax()).isCloseTo(100.0, offset(0.0)); + assertThat(rowGroup1.isValid()).isTrue(); // Row Group 2: [3, 3, 300, 300] BoundingBox rowGroup2 = new BoundingBox(); @@ -593,12 +595,12 @@ public void testMergingRowGroupBoundingBoxes() { rowGroup2.update(gf.createPoint(nanCoord)); // Verify Row Group 2 - Assert.assertTrue(rowGroup2.isValid()); - Assert.assertEquals(3.0, rowGroup2.getXMin(), 0.0); - Assert.assertEquals(3.0, rowGroup2.getXMax(), 0.0); - Assert.assertEquals(300.0, rowGroup2.getYMin(), 0.0); - Assert.assertEquals(300.0, rowGroup2.getYMax(), 0.0); - Assert.assertTrue(rowGroup2.isValid()); + assertThat(rowGroup2.isValid()).isTrue(); + assertThat(rowGroup2.getXMin()).isCloseTo(3.0, offset(0.0)); + assertThat(rowGroup2.getXMax()).isCloseTo(3.0, offset(0.0)); + assertThat(rowGroup2.getYMin()).isCloseTo(300.0, offset(0.0)); + assertThat(rowGroup2.getYMax()).isCloseTo(300.0, offset(0.0)); + assertThat(rowGroup2.isValid()).isTrue(); // Row Group 3: No defined bbox due to NaN Y-coordinates BoundingBox rowGroup3 = new BoundingBox(); @@ -606,7 +608,7 @@ public void testMergingRowGroupBoundingBoxes() { rowGroup3.update(gf.createPoint(new Coordinate(6, Double.NaN))); // Verify Row Group 3 - Assert.assertTrue(rowGroup3.isXYEmpty()); + assertThat(rowGroup3.isXYEmpty()).isTrue(); // Row Group 4: [7, 8, 700, 800] BoundingBox rowGroup4 = new BoundingBox(); @@ -614,12 +616,12 @@ public void testMergingRowGroupBoundingBoxes() { rowGroup4.update(gf.createPoint(new Coordinate(8, 800))); // Verify Row Group 4 - Assert.assertTrue(rowGroup4.isValid()); - Assert.assertEquals(7.0, rowGroup4.getXMin(), 0.0); - Assert.assertEquals(8.0, rowGroup4.getXMax(), 0.0); - Assert.assertEquals(700.0, rowGroup4.getYMin(), 0.0); - Assert.assertEquals(800.0, rowGroup4.getYMax(), 0.0); - Assert.assertTrue(rowGroup4.isValid()); + assertThat(rowGroup4.isValid()).isTrue(); + assertThat(rowGroup4.getXMin()).isCloseTo(7.0, offset(0.0)); + assertThat(rowGroup4.getXMax()).isCloseTo(8.0, offset(0.0)); + assertThat(rowGroup4.getYMin()).isCloseTo(700.0, offset(0.0)); + assertThat(rowGroup4.getYMax()).isCloseTo(800.0, offset(0.0)); + assertThat(rowGroup4.isValid()).isTrue(); // Row Group 5: No defined bbox due to all NaN coordinates BoundingBox rowGroup5 = new BoundingBox(); @@ -627,7 +629,7 @@ public void testMergingRowGroupBoundingBoxes() { rowGroup5.update(gf.createPoint(nanCoord)); // Verify Row Group 5 - Assert.assertTrue(rowGroup5.isXYEmpty()); + assertThat(rowGroup5.isXYEmpty()).isTrue(); // Row Group 6: Test mixing an empty geometry with a valid point [9, 9, 900, 900] BoundingBox rowGroup6 = new BoundingBox(); @@ -642,11 +644,11 @@ public void testMergingRowGroupBoundingBoxes() { rowGroup6.update(validPoint); // This should set the bounds // Verify Row Group 6 - Assert.assertTrue(rowGroup6.isValid()); - Assert.assertEquals(9.0, rowGroup6.getXMin(), 0.0); - Assert.assertEquals(9.0, rowGroup6.getXMax(), 0.0); - Assert.assertEquals(900.0, rowGroup6.getYMin(), 0.0); - Assert.assertEquals(900.0, rowGroup6.getYMax(), 0.0); + assertThat(rowGroup6.isValid()).isTrue(); + assertThat(rowGroup6.getXMin()).isCloseTo(9.0, offset(0.0)); + assertThat(rowGroup6.getXMax()).isCloseTo(9.0, offset(0.0)); + assertThat(rowGroup6.getYMin()).isCloseTo(900.0, offset(0.0)); + assertThat(rowGroup6.getYMax()).isCloseTo(900.0, offset(0.0)); // Merge row group boxes into file-level box fileBBox.merge(rowGroup1); @@ -658,12 +660,12 @@ public void testMergingRowGroupBoundingBoxes() { // Verify file-level bounding box // Note: Now includes point (9, 900) from rowGroup6 - Assert.assertTrue(fileBBox.isValid()); - Assert.assertEquals(1.0, fileBBox.getXMin(), 0.0); - Assert.assertEquals(9.0, fileBBox.getXMax(), 0.0); - Assert.assertEquals(100.0, fileBBox.getYMin(), 0.0); - Assert.assertEquals(900.0, fileBBox.getYMax(), 0.0); - Assert.assertTrue(fileBBox.isValid()); + assertThat(fileBBox.isValid()).isTrue(); + assertThat(fileBBox.getXMin()).isCloseTo(1.0, offset(0.0)); + assertThat(fileBBox.getXMax()).isCloseTo(9.0, offset(0.0)); + assertThat(fileBBox.getYMin()).isCloseTo(100.0, offset(0.0)); + assertThat(fileBBox.getYMax()).isCloseTo(900.0, offset(0.0)); + assertThat(fileBBox.isValid()).isTrue(); // Test merging in reverse order to ensure commutativity BoundingBox reverseMergeBox = new BoundingBox(); @@ -674,108 +676,112 @@ public void testMergingRowGroupBoundingBoxes() { reverseMergeBox.merge(rowGroup2); reverseMergeBox.merge(rowGroup1); - Assert.assertTrue(reverseMergeBox.isValid()); - Assert.assertEquals(1.0, reverseMergeBox.getXMin(), 0.0); - Assert.assertEquals(9.0, reverseMergeBox.getXMax(), 0.0); - Assert.assertEquals(100.0, reverseMergeBox.getYMin(), 0.0); - Assert.assertEquals(900.0, reverseMergeBox.getYMax(), 0.0); - Assert.assertTrue(reverseMergeBox.isValid()); + assertThat(reverseMergeBox.isValid()).isTrue(); + assertThat(reverseMergeBox.getXMin()).isCloseTo(1.0, offset(0.0)); + assertThat(reverseMergeBox.getXMax()).isCloseTo(9.0, offset(0.0)); + assertThat(reverseMergeBox.getYMin()).isCloseTo(100.0, offset(0.0)); + assertThat(reverseMergeBox.getYMax()).isCloseTo(900.0, offset(0.0)); + assertThat(reverseMergeBox.isValid()).isTrue(); } @Test public void testIsXValidAndIsYValid() { // Test with valid X and Y BoundingBox validBox = new BoundingBox(1, 2, 3, 4, 5, 6, 7, 8); - Assert.assertTrue(validBox.isXValid()); - Assert.assertTrue(validBox.isYValid()); - Assert.assertTrue(validBox.isXYValid()); - Assert.assertTrue(validBox.isZValid()); - Assert.assertTrue(validBox.isMValid()); + assertThat(validBox.isXValid()).isTrue(); + assertThat(validBox.isYValid()).isTrue(); + assertThat(validBox.isXYValid()).isTrue(); + assertThat(validBox.isZValid()).isTrue(); + assertThat(validBox.isMValid()).isTrue(); // Test with invalid X (NaN) BoundingBox invalidXBox = new BoundingBox(Double.NaN, 2, 3, 4, 5, 6, 7, 8); - Assert.assertFalse(invalidXBox.isXValid()); - Assert.assertTrue(invalidXBox.isYValid()); - Assert.assertFalse(invalidXBox.isXYValid()); - Assert.assertTrue(invalidXBox.isZValid()); - Assert.assertTrue(invalidXBox.isMValid()); + assertThat(invalidXBox.isXValid()).isFalse(); + assertThat(invalidXBox.isYValid()).isTrue(); + assertThat(invalidXBox.isXYValid()).isFalse(); + assertThat(invalidXBox.isZValid()).isTrue(); + assertThat(invalidXBox.isMValid()).isTrue(); // Test with invalid Y (NaN) BoundingBox invalidYBox = new BoundingBox(1, 2, Double.NaN, 4, 5, 6, 7, 8); - Assert.assertTrue(invalidYBox.isXValid()); - Assert.assertFalse(invalidYBox.isYValid()); - Assert.assertFalse(invalidXBox.isXYValid()); - Assert.assertTrue(invalidXBox.isZValid()); - Assert.assertTrue(invalidXBox.isMValid()); + assertThat(invalidYBox.isXValid()).isTrue(); + assertThat(invalidYBox.isYValid()).isFalse(); + assertThat(invalidXBox.isXYValid()).isFalse(); + assertThat(invalidXBox.isZValid()).isTrue(); + assertThat(invalidXBox.isMValid()).isTrue(); // Test with both X and Y invalid BoundingBox invalidXYBox = new BoundingBox(Double.NaN, Double.NaN, Double.NaN, Double.NaN, 5, 6, 7, 8); - Assert.assertFalse(invalidXYBox.isXValid()); - Assert.assertFalse(invalidXYBox.isYValid()); - Assert.assertFalse(invalidXYBox.isXYValid()); - Assert.assertTrue(invalidXBox.isZValid()); - Assert.assertTrue(invalidXBox.isMValid()); + assertThat(invalidXYBox.isXValid()).isFalse(); + assertThat(invalidXYBox.isYValid()).isFalse(); + assertThat(invalidXYBox.isXYValid()).isFalse(); + assertThat(invalidXBox.isZValid()).isTrue(); + assertThat(invalidXBox.isMValid()).isTrue(); } @Test public void testIsXEmptyAndIsYEmpty() { // Empty bounding box (initial state) BoundingBox emptyBox = new BoundingBox(); - Assert.assertTrue(emptyBox.isXEmpty()); - Assert.assertTrue(emptyBox.isYEmpty()); - Assert.assertTrue(emptyBox.isXYEmpty()); + assertThat(emptyBox.isXEmpty()).isTrue(); + assertThat(emptyBox.isYEmpty()).isTrue(); + assertThat(emptyBox.isXYEmpty()).isTrue(); // Non-empty box BoundingBox nonEmptyBox = new BoundingBox(1, 2, 3, 4, 5, 6, 7, 8); - Assert.assertFalse(nonEmptyBox.isXEmpty()); - Assert.assertFalse(nonEmptyBox.isYEmpty()); - Assert.assertFalse(nonEmptyBox.isXYEmpty()); + assertThat(nonEmptyBox.isXEmpty()).isFalse(); + assertThat(nonEmptyBox.isYEmpty()).isFalse(); + assertThat(nonEmptyBox.isXYEmpty()).isFalse(); // Box with empty X dimension only GeometryFactory gf = new GeometryFactory(); BoundingBox emptyXBox = new BoundingBox(); // Only update Y dimension emptyXBox.update(gf.createPoint(new Coordinate(Double.NaN, 5))); - Assert.assertTrue(emptyXBox.isXEmpty()); - Assert.assertFalse(emptyXBox.isYEmpty()); - Assert.assertTrue(emptyXBox.isXYEmpty()); + assertThat(emptyXBox.isXEmpty()).isTrue(); + assertThat(emptyXBox.isYEmpty()).isFalse(); + assertThat(emptyXBox.isXYEmpty()).isTrue(); // Box with empty Y dimension only BoundingBox emptyYBox = new BoundingBox(); // Only update X dimension emptyYBox.update(gf.createPoint(new Coordinate(10, Double.NaN))); - Assert.assertFalse(emptyYBox.isXEmpty()); - Assert.assertTrue(emptyYBox.isYEmpty()); - Assert.assertTrue(emptyYBox.isXYEmpty()); + assertThat(emptyYBox.isXEmpty()).isFalse(); + assertThat(emptyYBox.isYEmpty()).isTrue(); + assertThat(emptyYBox.isXYEmpty()).isTrue(); } @Test public void testIsXWraparound() { // Normal bounding box (no wraparound) BoundingBox normalBox = new BoundingBox(1, 2, 3, 4, 5, 6, 7, 8); - Assert.assertFalse(normalBox.isXWraparound()); + assertThat(normalBox.isXWraparound()).isFalse(); // Wraparound box (xMin > xMax) BoundingBox wraparoundBox = new BoundingBox(170, 20, 10, 20, 0, 0, 0, 0); - Assert.assertTrue(wraparoundBox.isXWraparound()); + assertThat(wraparoundBox.isXWraparound()).isTrue(); // Edge case: equal bounds BoundingBox equalBoundsBox = new BoundingBox(10, 10, 20, 20, 0, 0, 0, 0); - Assert.assertFalse(equalBoundsBox.isXWraparound()); + assertThat(equalBoundsBox.isXWraparound()).isFalse(); // Test static method directly - Assert.assertTrue(BoundingBox.isWraparound(180, -180)); - Assert.assertFalse(BoundingBox.isWraparound(-180, 180)); + assertThat(BoundingBox.isWraparound(180, -180)).isTrue(); + assertThat(BoundingBox.isWraparound(-180, 180)).isFalse(); // Test with infinity values - Assert.assertFalse(BoundingBox.isWraparound(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)); - Assert.assertFalse(BoundingBox.isWraparound(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)); - Assert.assertFalse(BoundingBox.isWraparound(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)); - Assert.assertFalse(BoundingBox.isWraparound(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); + assertThat(BoundingBox.isWraparound(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY)) + .isFalse(); + assertThat(BoundingBox.isWraparound(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)) + .isFalse(); + assertThat(BoundingBox.isWraparound(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)) + .isFalse(); + assertThat(BoundingBox.isWraparound(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)) + .isFalse(); // Check edge cases - Assert.assertFalse(BoundingBox.isWraparound(0.0, Double.POSITIVE_INFINITY)); - Assert.assertFalse(BoundingBox.isWraparound(Double.NEGATIVE_INFINITY, 0.0)); + assertThat(BoundingBox.isWraparound(0.0, Double.POSITIVE_INFINITY)).isFalse(); + assertThat(BoundingBox.isWraparound(Double.NEGATIVE_INFINITY, 0.0)).isFalse(); } @Test @@ -785,9 +791,9 @@ public void testWraparoundHandlingInMerge() { BoundingBox box2 = new BoundingBox(15, 25, 15, 25, 0, 0, 0, 0); box1.merge(box2); - Assert.assertTrue(box1.isValid()); - Assert.assertEquals(10.0, box1.getXMin(), 0.0); - Assert.assertEquals(25.0, box1.getXMax(), 0.0); + assertThat(box1.isValid()).isTrue(); + assertThat(box1.getXMin()).isCloseTo(10.0, offset(0.0)); + assertThat(box1.getXMax()).isCloseTo(25.0, offset(0.0)); // Test with one wraparound box BoundingBox normalBox = new BoundingBox(0, 10, 0, 10, 0, 0, 0, 0); @@ -795,11 +801,11 @@ public void testWraparoundHandlingInMerge() { normalBox.merge(wraparoundBox); - Assert.assertFalse(normalBox.isValid()); - Assert.assertTrue(Double.isNaN(normalBox.getXMin())); - Assert.assertTrue(Double.isNaN(normalBox.getXMax())); - Assert.assertEquals(0.0, normalBox.getYMin(), 0.0); - Assert.assertEquals(15.0, normalBox.getYMax(), 0.0); + assertThat(normalBox.isValid()).isFalse(); + assertThat(normalBox.getXMin()).isNaN(); + assertThat(normalBox.getXMax()).isNaN(); + assertThat(normalBox.getYMin()).isCloseTo(0.0, offset(0.0)); + assertThat(normalBox.getYMax()).isCloseTo(15.0, offset(0.0)); } @Test @@ -815,12 +821,12 @@ public void testWraparoundBoxMergingNormalBox() { // After merging, X dimension should be marked as invalid (NaN) // because we don't support merging wraparound bounds - Assert.assertFalse(wraparoundBox.isValid()); - Assert.assertTrue(Double.isNaN(wraparoundBox.getXMin())); - Assert.assertTrue(Double.isNaN(wraparoundBox.getXMax())); + assertThat(wraparoundBox.isValid()).isFalse(); + assertThat(wraparoundBox.getXMin()).isNaN(); + assertThat(wraparoundBox.getXMax()).isNaN(); // Y dimension should be properly merged - Assert.assertEquals(0.0, wraparoundBox.getYMin(), 0.0); - Assert.assertEquals(15.0, wraparoundBox.getYMax(), 0.0); + assertThat(wraparoundBox.getYMin()).isCloseTo(0.0, offset(0.0)); + assertThat(wraparoundBox.getYMax()).isCloseTo(15.0, offset(0.0)); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialStatistics.java b/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialStatistics.java index 7c91ffbecb..82536e3e85 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialStatistics.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialStatistics.java @@ -19,11 +19,12 @@ package org.apache.parquet.column.statistics.geospatial; +import static org.assertj.core.api.Assertions.assertThat; + import org.apache.parquet.io.api.Binary; import org.apache.parquet.schema.LogicalTypeAnnotation; import org.apache.parquet.schema.PrimitiveType; import org.apache.parquet.schema.Types; -import org.junit.Assert; import org.junit.Test; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKBWriter; @@ -43,9 +44,9 @@ public void testAddGeospatialData() throws ParseException { builder.update(Binary.fromConstantByteArray(wkbWriter.write(wktReader.read("POINT (1 1)")))); builder.update(Binary.fromConstantByteArray(wkbWriter.write(wktReader.read("POINT (2 2)")))); GeospatialStatistics statistics = builder.build(); - Assert.assertTrue(statistics.isValid()); - Assert.assertNotNull(statistics.getBoundingBox()); - Assert.assertNotNull(statistics.getGeospatialTypes()); + assertThat(statistics.isValid()).isTrue(); + assertThat(statistics.getBoundingBox()).isNotNull(); + assertThat(statistics.getGeospatialTypes()).isNotNull(); } @Test @@ -66,13 +67,13 @@ public void testMergeGeospatialStatistics() throws ParseException { GeospatialStatistics statistics2 = builder2.build(); statistics1.merge(statistics2); - Assert.assertTrue(statistics1.isValid()); - Assert.assertNotNull(statistics1.getBoundingBox()); - Assert.assertNotNull(statistics1.getGeospatialTypes()); + assertThat(statistics1.isValid()).isTrue(); + assertThat(statistics1.getBoundingBox()).isNotNull(); + assertThat(statistics1.getGeospatialTypes()).isNotNull(); } @Test - public void testMergeNullGeospatialStatistics() { + public void testMergeNullGeospatialStatistics() throws ParseException { // Create a valid stats object PrimitiveType type = Types.optional(PrimitiveType.PrimitiveTypeName.BINARY) .as(LogicalTypeAnnotation.geometryType(null)) @@ -82,42 +83,38 @@ public void testMergeNullGeospatialStatistics() { WKBWriter wkbWriter = new WKBWriter(); GeospatialStatistics.Builder validBuilder = GeospatialStatistics.newBuilder(type); - try { - validBuilder.update(Binary.fromConstantByteArray(wkbWriter.write(wktReader.read("POINT (1 1)")))); - } catch (ParseException e) { - Assert.fail("Failed to parse valid WKT: " + e.getMessage()); - } + validBuilder.update(Binary.fromConstantByteArray(wkbWriter.write(wktReader.read("POINT (1 1)")))); GeospatialStatistics validStats = validBuilder.build(); - Assert.assertTrue(validStats.isValid()); + assertThat(validStats.isValid()).isTrue(); // Create stats with null components GeospatialStatistics nullStats = new GeospatialStatistics(null, null); - Assert.assertFalse(nullStats.isValid()); + assertThat(nullStats.isValid()).isFalse(); // Test merging valid with null GeospatialStatistics validCopy = validStats.copy(); validCopy.merge(nullStats); - Assert.assertFalse(validCopy.isValid()); - Assert.assertNotNull(validCopy.getBoundingBox()); - Assert.assertNotNull(validCopy.getGeospatialTypes()); + assertThat(validCopy.isValid()).isFalse(); + assertThat(validCopy.getBoundingBox()).isNotNull(); + assertThat(validCopy.getGeospatialTypes()).isNotNull(); // Test merging null with valid nullStats = new GeospatialStatistics(null, null); nullStats.merge(validStats); - Assert.assertFalse(nullStats.isValid()); - Assert.assertNull(nullStats.getBoundingBox()); - Assert.assertNull(nullStats.getGeospatialTypes()); + assertThat(nullStats.isValid()).isFalse(); + assertThat(nullStats.getBoundingBox()).isNull(); + assertThat(nullStats.getGeospatialTypes()).isNull(); // Create stats with null bounding box only GeospatialStatistics nullBboxStats = new GeospatialStatistics(null, new GeospatialTypes()); - Assert.assertTrue(nullBboxStats.isValid()); + assertThat(nullBboxStats.isValid()).isTrue(); // Test merging valid with null bounding box validCopy = validStats.copy(); validCopy.merge(nullBboxStats); - Assert.assertTrue(validCopy.isValid()); - Assert.assertNotNull(validCopy.getBoundingBox()); - Assert.assertNotNull(validCopy.getGeospatialTypes()); + assertThat(validCopy.isValid()).isTrue(); + assertThat(validCopy.getBoundingBox()).isNotNull(); + assertThat(validCopy.getGeospatialTypes()).isNotNull(); } @Test @@ -129,13 +126,13 @@ public void testCopyGeospatialStatistics() { builder.update(Binary.fromString("POINT (1 1)")); GeospatialStatistics statistics = builder.build(); GeospatialStatistics copy = statistics.copy(); - Assert.assertTrue(copy.isValid()); - Assert.assertNotNull(copy.getBoundingBox()); - Assert.assertNotNull(copy.getGeospatialTypes()); + assertThat(copy.isValid()).isTrue(); + assertThat(copy.getBoundingBox()).isNotNull(); + assertThat(copy.getGeospatialTypes()).isNotNull(); } @Test - public void testInvalidGeometryMakesStatisticsInvalid() { + public void testInvalidGeometryMakesStatisticsInvalid() throws ParseException { PrimitiveType type = Types.optional(PrimitiveType.PrimitiveTypeName.BINARY) .as(LogicalTypeAnnotation.geometryType(null)) .named("a"); @@ -144,15 +141,11 @@ public void testInvalidGeometryMakesStatisticsInvalid() { // First add a valid geometry WKTReader wktReader = new WKTReader(); WKBWriter wkbWriter = new WKBWriter(); - try { - builder.update(Binary.fromConstantByteArray(wkbWriter.write(wktReader.read("POINT (1 1)")))); - } catch (ParseException e) { - Assert.fail("Failed to parse valid WKT: " + e.getMessage()); - } + builder.update(Binary.fromConstantByteArray(wkbWriter.write(wktReader.read("POINT (1 1)")))); // Valid at this point GeospatialStatistics validStats = builder.build(); - Assert.assertTrue(validStats.isValid()); + assertThat(validStats.isValid()).isTrue(); // Now add invalid data - corrupt WKB bytes byte[] invalidBytes = new byte[] {0x01, 0x02, 0x03}; // Invalid WKB format @@ -160,13 +153,13 @@ public void testInvalidGeometryMakesStatisticsInvalid() { // After adding invalid data, omit it from stats GeospatialStatistics invalidStats = builder.build(); - Assert.assertTrue(invalidStats.isValid()); + assertThat(invalidStats.isValid()).isTrue(); } @Test public void testNoopBuilder() { GeospatialStatistics.Builder builder = GeospatialStatistics.noopBuilder(); GeospatialStatistics statistics = builder.build(); - Assert.assertFalse(statistics.isValid()); + assertThat(statistics.isValid()).isFalse(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialTypes.java b/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialTypes.java index 832aac06ee..903a24c1f1 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialTypes.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/statistics/geospatial/TestGeospatialTypes.java @@ -18,9 +18,10 @@ */ package org.apache.parquet.column.statistics.geospatial; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.HashSet; import java.util.Set; -import org.junit.Assert; import org.junit.Test; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.CoordinateXYZM; @@ -44,16 +45,13 @@ public void testUpdateWithDifferentGeometryTypes() { // Test with Point (type code 1) Point point = gf.createPoint(new Coordinate(1, 1)); geospatialTypes.update(point); - Assert.assertTrue(geospatialTypes.getTypes().contains(1)); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactly(1); // Test with LineString (type code 2) Coordinate[] lineCoords = new Coordinate[] {new Coordinate(1, 1), new Coordinate(2, 2)}; LineString line = gf.createLineString(lineCoords); geospatialTypes.update(line); - Assert.assertTrue(geospatialTypes.getTypes().contains(1)); - Assert.assertTrue(geospatialTypes.getTypes().contains(2)); - Assert.assertEquals(2, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactlyInAnyOrder(1, 2); // Test with Polygon (type code 3) Coordinate[] polygonCoords = new Coordinate[] { @@ -64,10 +62,7 @@ public void testUpdateWithDifferentGeometryTypes() { LinearRing shell = gf.createLinearRing(polygonCoords); Polygon polygon = gf.createPolygon(shell); geospatialTypes.update(polygon); - Assert.assertTrue(geospatialTypes.getTypes().contains(1)); - Assert.assertTrue(geospatialTypes.getTypes().contains(2)); - Assert.assertTrue(geospatialTypes.getTypes().contains(3)); - Assert.assertEquals(3, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactlyInAnyOrder(1, 2, 3); } @Test @@ -79,8 +74,7 @@ public void testUpdateWithComplexGeometries() { Point[] points = new Point[] {gf.createPoint(new Coordinate(1, 1)), gf.createPoint(new Coordinate(2, 2))}; MultiPoint multiPoint = gf.createMultiPoint(points); geospatialTypes.update(multiPoint); - Assert.assertTrue(geospatialTypes.getTypes().contains(4)); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactly(4); // MultiLineString (type code 5) LineString[] lines = new LineString[] { @@ -89,9 +83,7 @@ public void testUpdateWithComplexGeometries() { }; MultiLineString multiLine = gf.createMultiLineString(lines); geospatialTypes.update(multiLine); - Assert.assertTrue(geospatialTypes.getTypes().contains(4)); - Assert.assertTrue(geospatialTypes.getTypes().contains(5)); - Assert.assertEquals(2, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactlyInAnyOrder(4, 5); // MultiPolygon (type code 6) Polygon[] polygons = new Polygon[] { @@ -103,20 +95,13 @@ public void testUpdateWithComplexGeometries() { }; MultiPolygon multiPolygon = gf.createMultiPolygon(polygons); geospatialTypes.update(multiPolygon); - Assert.assertTrue(geospatialTypes.getTypes().contains(4)); - Assert.assertTrue(geospatialTypes.getTypes().contains(5)); - Assert.assertTrue(geospatialTypes.getTypes().contains(6)); - Assert.assertEquals(3, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactlyInAnyOrder(4, 5, 6); // GeometryCollection (type code 7) GeometryCollection collection = gf.createGeometryCollection( new org.locationtech.jts.geom.Geometry[] {multiPoint, multiLine, multiPolygon}); geospatialTypes.update(collection); - Assert.assertTrue(geospatialTypes.getTypes().contains(4)); - Assert.assertTrue(geospatialTypes.getTypes().contains(5)); - Assert.assertTrue(geospatialTypes.getTypes().contains(6)); - Assert.assertTrue(geospatialTypes.getTypes().contains(7)); - Assert.assertEquals(4, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactlyInAnyOrder(4, 5, 6, 7); } @Test @@ -127,8 +112,7 @@ public void testUpdateWithZCoordinates() { // Create a 3D point (XYZ) - should be type code 1001 Point pointXYZ = gf.createPoint(new Coordinate(1, 1, 1)); geospatialTypes.update(pointXYZ); - Assert.assertTrue(geospatialTypes.getTypes().contains(1001)); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactly(1001); } @Test @@ -140,8 +124,7 @@ public void testUpdateWithMCoordinates() { CoordinateXYZM coord = new CoordinateXYZM(1, 1, Double.NaN, 10); Point pointXYM = gf.createPoint(coord); geospatialTypes.update(pointXYM); - Assert.assertTrue(geospatialTypes.getTypes().contains(2001)); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactly(2001); } @Test @@ -153,8 +136,7 @@ public void testUpdateWithZMCoordinates() { CoordinateXYZM coord = new CoordinateXYZM(1, 1, 1, 10); Point pointXYZM = gf.createPoint(coord); geospatialTypes.update(pointXYZM); - Assert.assertTrue(geospatialTypes.getTypes().contains(3001)); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactly(3001); } @Test @@ -174,9 +156,7 @@ public void testMergeGeospatialTypes() { types1.merge(types2); // Check merged result - Assert.assertTrue(types1.getTypes().contains(1)); // Point - Assert.assertTrue(types1.getTypes().contains(2)); // LineString - Assert.assertEquals(2, types1.getTypes().size()); + assertThat(types1.getTypes()).containsExactlyInAnyOrder(1, 2); // Create third set of types with Z dimension GeospatialTypes types3 = new GeospatialTypes(); @@ -186,10 +166,7 @@ public void testMergeGeospatialTypes() { types1.merge(types3); // Check merged result - Assert.assertTrue(types1.getTypes().contains(1)); // Point XY - Assert.assertTrue(types1.getTypes().contains(2)); // LineString XY - Assert.assertTrue(types1.getTypes().contains(1001)); // Point XYZ - Assert.assertEquals(3, types1.getTypes().size()); + assertThat(types1.getTypes()).containsExactlyInAnyOrder(1, 2, 1001); } @Test @@ -199,21 +176,19 @@ public void testMergeWithEmptyGeospatialTypes() { // Create set with types GeospatialTypes types1 = new GeospatialTypes(); types1.update(gf.createPoint(new Coordinate(1, 1))); // Type 1 - Assert.assertEquals(1, types1.getTypes().size()); + assertThat(types1.getTypes()).containsExactly(1); // Create empty set GeospatialTypes emptyTypes = new GeospatialTypes(); - Assert.assertEquals(0, emptyTypes.getTypes().size()); + assertThat(emptyTypes.getTypes()).isEmpty(); // Merge empty into non-empty types1.merge(emptyTypes); - Assert.assertEquals(1, types1.getTypes().size()); - Assert.assertTrue(types1.getTypes().contains(1)); + assertThat(types1.getTypes()).containsExactly(1); // Merge non-empty into empty emptyTypes.merge(types1); - Assert.assertEquals(1, emptyTypes.getTypes().size()); - Assert.assertTrue(emptyTypes.getTypes().contains(1)); + assertThat(emptyTypes.getTypes()).containsExactly(1); } @Test @@ -222,18 +197,18 @@ public void testUpdateWithNullOrEmptyGeometry() { // Update with null geometry geospatialTypes.update(null); - Assert.assertEquals(0, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).isEmpty(); // Update with empty point GeometryFactory gf = new GeometryFactory(); Point emptyPoint = gf.createPoint((Coordinate) null); geospatialTypes.update(emptyPoint); - Assert.assertEquals(0, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).isEmpty(); // Update with empty linestring LineString emptyLine = gf.createLineString((Coordinate[]) null); geospatialTypes.update(emptyLine); - Assert.assertEquals(0, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).isEmpty(); } @Test @@ -244,16 +219,15 @@ public void testReset() { // Add some types geospatialTypes.update(gf.createPoint(new Coordinate(1, 1))); geospatialTypes.update(gf.createLineString(new Coordinate[] {new Coordinate(1, 1), new Coordinate(2, 2)})); - Assert.assertEquals(2, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).containsExactlyInAnyOrder(1, 2); // Reset the types geospatialTypes.reset(); - Assert.assertEquals(0, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.getTypes()).isEmpty(); // Add new types after reset geospatialTypes.update(gf.createPoint(new Coordinate(3, 3, 3))); // XYZ point (1001) - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(1001)); + assertThat(geospatialTypes.getTypes()).containsExactly(1001); } @Test @@ -263,18 +237,18 @@ public void testAbort() { // Add some types geospatialTypes.update(gf.createPoint(new Coordinate(1, 1))); - Assert.assertTrue(geospatialTypes.isValid()); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.isValid()).isTrue(); + assertThat(geospatialTypes.getTypes()).containsExactly(1); // Abort the set geospatialTypes.abort(); - Assert.assertFalse(geospatialTypes.isValid()); - Assert.assertEquals(0, geospatialTypes.getTypes().size()); + assertThat(geospatialTypes.isValid()).isFalse(); + assertThat(geospatialTypes.getTypes()).isEmpty(); // Update after abort shouldn't add anything geospatialTypes.update(gf.createPoint(new Coordinate(2, 2))); - Assert.assertEquals(0, geospatialTypes.getTypes().size()); - Assert.assertFalse(geospatialTypes.isValid()); + assertThat(geospatialTypes.getTypes()).isEmpty(); + assertThat(geospatialTypes.isValid()).isFalse(); } @Test @@ -290,17 +264,13 @@ public void testCopy() { GeospatialTypes copy = original.copy(); // Verify the copy has the same types - Assert.assertEquals(original.getTypes().size(), copy.getTypes().size()); - for (Integer typeId : original.getTypes()) { - Assert.assertTrue(copy.getTypes().contains(typeId)); - } + assertThat(copy.getTypes()).hasSameSizeAs(original.getTypes()).containsExactlyInAnyOrder(1, 2); // Modify copy and verify it doesn't affect the original copy.update(gf.createPoint(new Coordinate(3, 3, 3))); // Add XYZ point (1001) - Assert.assertEquals(2, original.getTypes().size()); - Assert.assertEquals(3, copy.getTypes().size()); - Assert.assertTrue(copy.getTypes().contains(1001)); - Assert.assertFalse(original.getTypes().contains(1001)); + assertThat(original.getTypes()).containsExactlyInAnyOrder(1, 2); + assertThat(copy.getTypes()).containsExactlyInAnyOrder(1, 2, 1001); + assertThat(original.getTypes()).doesNotContain(1001); } @Test @@ -310,13 +280,13 @@ public void testMergeWithNullGeospatialTypes() { // Add a type types.update(gf.createPoint(new Coordinate(1, 1))); - Assert.assertEquals(1, types.getTypes().size()); - Assert.assertTrue(types.isValid()); + assertThat(types.getTypes()).containsExactly(1); + assertThat(types.isValid()).isTrue(); // Merge with null types.merge(null); - Assert.assertEquals(0, types.getTypes().size()); - Assert.assertFalse(types.isValid()); + assertThat(types.getTypes()).isEmpty(); + assertThat(types.isValid()).isFalse(); } @Test @@ -326,18 +296,18 @@ public void testMergeWithInvalidGeospatialTypes() { // Create valid types GeospatialTypes validTypes = new GeospatialTypes(); validTypes.update(gf.createPoint(new Coordinate(1, 1))); - Assert.assertTrue(validTypes.isValid()); - Assert.assertEquals(1, validTypes.getTypes().size()); + assertThat(validTypes.isValid()).isTrue(); + assertThat(validTypes.getTypes()).containsExactly(1); // Create invalid types GeospatialTypes invalidTypes = new GeospatialTypes(); invalidTypes.abort(); // Mark as invalid - Assert.assertFalse(invalidTypes.isValid()); + assertThat(invalidTypes.isValid()).isFalse(); // Merge invalid into valid validTypes.merge(invalidTypes); - Assert.assertFalse(validTypes.isValid()); - Assert.assertEquals(0, validTypes.getTypes().size()); + assertThat(validTypes.isValid()).isFalse(); + assertThat(validTypes.getTypes()).isEmpty(); // Create new valid types GeospatialTypes newValidTypes = new GeospatialTypes(); @@ -345,8 +315,8 @@ public void testMergeWithInvalidGeospatialTypes() { // Merge valid into invalid invalidTypes.merge(newValidTypes); - Assert.assertFalse(invalidTypes.isValid()); - Assert.assertEquals(0, invalidTypes.getTypes().size()); + assertThat(invalidTypes.isValid()).isFalse(); + assertThat(invalidTypes.getTypes()).isEmpty(); } @Test @@ -361,11 +331,8 @@ public void testConstructorWithTypes() { GeospatialTypes types = new GeospatialTypes(typeSet); // Verify types were properly set - Assert.assertEquals(3, types.getTypes().size()); - Assert.assertTrue(types.getTypes().contains(1)); - Assert.assertTrue(types.getTypes().contains(1001)); - Assert.assertTrue(types.getTypes().contains(2)); - Assert.assertTrue(types.isValid()); + assertThat(types.getTypes()).containsExactlyInAnyOrder(1, 1001, 2); + assertThat(types.isValid()).isTrue(); } @Test @@ -375,30 +342,21 @@ public void testUpdateWithMixedDimensionGeometries() { // Add Point XY types.update(gf.createPoint(new Coordinate(1, 1))); - Assert.assertTrue(types.getTypes().contains(1)); + assertThat(types.getTypes()).containsExactly(1); // Add Point XYZ types.update(gf.createPoint(new Coordinate(2, 2, 2))); - Assert.assertTrue(types.getTypes().contains(1)); - Assert.assertTrue(types.getTypes().contains(1001)); - Assert.assertEquals(2, types.getTypes().size()); + assertThat(types.getTypes()).containsExactlyInAnyOrder(1, 1001); // Add Point XYM CoordinateXYZM coordXYM = new CoordinateXYZM(3, 3, Double.NaN, 10); types.update(gf.createPoint(coordXYM)); - Assert.assertTrue(types.getTypes().contains(1)); - Assert.assertTrue(types.getTypes().contains(1001)); - Assert.assertTrue(types.getTypes().contains(2001)); - Assert.assertEquals(3, types.getTypes().size()); + assertThat(types.getTypes()).containsExactlyInAnyOrder(1, 1001, 2001); // Add Point XYZM CoordinateXYZM coordXYZM = new CoordinateXYZM(4, 4, 4, 10); types.update(gf.createPoint(coordXYZM)); - Assert.assertTrue(types.getTypes().contains(1)); - Assert.assertTrue(types.getTypes().contains(1001)); - Assert.assertTrue(types.getTypes().contains(2001)); - Assert.assertTrue(types.getTypes().contains(3001)); - Assert.assertEquals(4, types.getTypes().size()); + assertThat(types.getTypes()).containsExactlyInAnyOrder(1, 1001, 2001, 3001); } @Test @@ -412,21 +370,18 @@ public void testRowGroupTypeMerging() { GeospatialTypes rowGroup1 = new GeospatialTypes(); rowGroup1.update(gf.createPoint(new Coordinate(1, 1))); // Point XY (1) rowGroup1.update(gf.createPoint(new Coordinate(2, 2, 2))); // Point XYZ (1001) - Assert.assertEquals(2, rowGroup1.getTypes().size()); - Assert.assertTrue(rowGroup1.getTypes().contains(1)); - Assert.assertTrue(rowGroup1.getTypes().contains(1001)); + assertThat(rowGroup1.getTypes()).containsExactlyInAnyOrder(1, 1001); // Row Group 2: LineStrings XY GeospatialTypes rowGroup2 = new GeospatialTypes(); LineString lineXY = gf.createLineString(new Coordinate[] {new Coordinate(1, 1), new Coordinate(2, 2)}); rowGroup2.update(lineXY); // LineString XY (2) - Assert.assertEquals(1, rowGroup2.getTypes().size()); - Assert.assertTrue(rowGroup2.getTypes().contains(2)); + assertThat(rowGroup2.getTypes()).containsExactly(2); // Row Group 3: Invalid types (aborted) GeospatialTypes rowGroup3 = new GeospatialTypes(); rowGroup3.abort(); - Assert.assertFalse(rowGroup3.isValid()); + assertThat(rowGroup3.isValid()).isFalse(); // Merge row groups into file-level types fileTypes.merge(rowGroup1); @@ -434,8 +389,8 @@ public void testRowGroupTypeMerging() { fileTypes.merge(rowGroup3); // This should invalidate fileTypes // Verify file level types after merge - Assert.assertFalse(fileTypes.isValid()); - Assert.assertEquals(0, fileTypes.getTypes().size()); + assertThat(fileTypes.isValid()).isFalse(); + assertThat(fileTypes.getTypes()).isEmpty(); // Test with different merge order - abort last fileTypes = new GeospatialTypes(); @@ -444,8 +399,8 @@ public void testRowGroupTypeMerging() { fileTypes.merge(rowGroup2); // This shouldn't change anything since fileTypes is already invalid // Verify file level types after second merge sequence - Assert.assertFalse(fileTypes.isValid()); - Assert.assertEquals(0, fileTypes.getTypes().size()); + assertThat(fileTypes.isValid()).isFalse(); + assertThat(fileTypes.getTypes()).isEmpty(); // Test without the invalid row group fileTypes = new GeospatialTypes(); @@ -453,11 +408,8 @@ public void testRowGroupTypeMerging() { fileTypes.merge(rowGroup2); // Verify file level types - should have 3 types: Point XY, Point XYZ, LineString XY - Assert.assertTrue(fileTypes.isValid()); - Assert.assertEquals(3, fileTypes.getTypes().size()); - Assert.assertTrue(fileTypes.getTypes().contains(1)); - Assert.assertTrue(fileTypes.getTypes().contains(1001)); - Assert.assertTrue(fileTypes.getTypes().contains(2)); + assertThat(fileTypes.isValid()).isTrue(); + assertThat(fileTypes.getTypes()).containsExactlyInAnyOrder(1, 1001, 2); } @Test @@ -468,16 +420,14 @@ public void testGeometryTypeCodeAssignment() { // Test Point (type code 1) Point point = gf.createPoint(new Coordinate(1, 1)); geospatialTypes.update(point); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(1)); + assertThat(geospatialTypes.getTypes()).containsExactly(1); geospatialTypes.reset(); // Test LineString (type code 2) LineString line = gf.createLineString(new Coordinate[] {new Coordinate(1, 1), new Coordinate(2, 2)}); geospatialTypes.update(line); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(2)); + assertThat(geospatialTypes.getTypes()).containsExactly(2); geospatialTypes.reset(); @@ -489,8 +439,7 @@ public void testGeometryTypeCodeAssignment() { }); Polygon polygon = gf.createPolygon(shell); geospatialTypes.update(polygon); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(3)); + assertThat(geospatialTypes.getTypes()).containsExactly(3); geospatialTypes.reset(); @@ -498,8 +447,7 @@ public void testGeometryTypeCodeAssignment() { MultiPoint multiPoint = gf.createMultiPoint( new Point[] {gf.createPoint(new Coordinate(1, 1)), gf.createPoint(new Coordinate(2, 2))}); geospatialTypes.update(multiPoint); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(4)); + assertThat(geospatialTypes.getTypes()).containsExactly(4); geospatialTypes.reset(); @@ -509,16 +457,14 @@ public void testGeometryTypeCodeAssignment() { gf.createLineString(new Coordinate[] {new Coordinate(3, 3), new Coordinate(4, 4)}) }); geospatialTypes.update(multiLine); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(5)); + assertThat(geospatialTypes.getTypes()).containsExactly(5); geospatialTypes.reset(); // Test MultiPolygon (type code 6) MultiPolygon multiPolygon = gf.createMultiPolygon(new Polygon[] {gf.createPolygon(shell)}); geospatialTypes.update(multiPolygon); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(6)); + assertThat(geospatialTypes.getTypes()).containsExactly(6); geospatialTypes.reset(); @@ -526,8 +472,7 @@ public void testGeometryTypeCodeAssignment() { GeometryCollection collection = gf.createGeometryCollection(new org.locationtech.jts.geom.Geometry[] {point, line}); geospatialTypes.update(collection); - Assert.assertEquals(1, geospatialTypes.getTypes().size()); - Assert.assertTrue(geospatialTypes.getTypes().contains(7)); + assertThat(geospatialTypes.getTypes()).containsExactly(7); } @Test @@ -537,23 +482,23 @@ public void testGeometryTypeDimensionCodes() { // Test XY (standard 2D, no prefix = 0) GeospatialTypes types2D = new GeospatialTypes(); types2D.update(gf.createPoint(new Coordinate(1, 1))); - Assert.assertTrue(types2D.getTypes().contains(1)); // Point XY + assertThat(types2D.getTypes()).containsExactly(1); // Point XY // Test XYZ (Z dimension, prefix = 1000) GeospatialTypes types3D = new GeospatialTypes(); types3D.update(gf.createPoint(new Coordinate(1, 1, 1))); - Assert.assertTrue(types3D.getTypes().contains(1001)); // Point XYZ + assertThat(types3D.getTypes()).containsExactly(1001); // Point XYZ // Test XYM (M dimension, prefix = 2000) GeospatialTypes typesXYM = new GeospatialTypes(); CoordinateXYZM coordXYM = new CoordinateXYZM(1, 1, Double.NaN, 10); typesXYM.update(gf.createPoint(coordXYM)); - Assert.assertTrue(typesXYM.getTypes().contains(2001)); // Point XYM + assertThat(typesXYM.getTypes()).containsExactly(2001); // Point XYM // Test XYZM (Z and M dimensions, prefix = 3000) GeospatialTypes typesXYZM = new GeospatialTypes(); CoordinateXYZM coordXYZM = new CoordinateXYZM(1, 1, 1, 10); typesXYZM.update(gf.createPoint(coordXYZM)); - Assert.assertTrue(typesXYZM.getTypes().contains(3001)); // Point XYZM + assertThat(typesXYZM.getTypes()).containsExactly(3001); // Point XYZM } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/TestValuesReaderImpl.java b/parquet-column/src/test/java/org/apache/parquet/column/values/TestValuesReaderImpl.java index 2730155350..7242071634 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/TestValuesReaderImpl.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/TestValuesReaderImpl.java @@ -19,14 +19,13 @@ package org.apache.parquet.column.values; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.parquet.bytes.ByteBufferInputStream; import org.apache.parquet.io.api.Binary; -import org.junit.Assert; import org.junit.Test; /** @@ -50,10 +49,6 @@ public void initFromPage(int valueCount, ByteBuffer page, int offset) throws IOE buffer.get(data); } - public void assertPageEquals(String expected) { - Assert.assertEquals(expected, new String(data)); - } - @Override public void skip() {} @@ -90,21 +85,18 @@ public Binary readBytes() { @Test public void testInvalidValuesReaderImpl() throws IOException { ValuesReader reader = new InvalidValuesReaderImpl(); - try { - validateWithByteArray(reader); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } - try { - validateWithByteBuffer(reader); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } - try { - validateWithByteBufferInputStream(reader); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + String expectedMessage = + "Either initFromPage(int, ByteBuffer, int) or initFromPage(int, ByteBufferInputStream) must be implemented in " + + InvalidValuesReaderImpl.class.getName(); + assertThatThrownBy(() -> validateWithByteArray(reader)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage(expectedMessage); + assertThatThrownBy(() -> validateWithByteBuffer(reader)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage(expectedMessage); + assertThatThrownBy(() -> validateWithByteBufferInputStream(reader)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessage(expectedMessage); } @Test @@ -125,12 +117,12 @@ public void testByteBufferInputStreamValuesReaderImpl() throws IOException { private void validateWithByteArray(ValuesReader reader) throws IOException { reader.initFromPage(25, "==padding==The expected page content".getBytes(), 11); - assertEquals("The expected page content", reader.readBytes().toStringUsingUTF8()); + assertThat(reader.readBytes().toStringUsingUTF8()).isEqualTo("The expected page content"); } private void validateWithByteBuffer(ValuesReader reader) throws IOException { reader.initFromPage(25, ByteBuffer.wrap("==padding==The expected page content".getBytes()), 11); - assertEquals("The expected page content", reader.readBytes().toStringUsingUTF8()); + assertThat(reader.readBytes().toStringUsingUTF8()).isEqualTo("The expected page content"); } private void validateWithByteBufferInputStream(ValuesReader reader) throws IOException { @@ -140,6 +132,6 @@ private void validateWithByteBufferInputStream(ValuesReader reader) throws IOExc ByteBuffer.wrap("page content".getBytes())); bbis.skipFully(11); reader.initFromPage(25, bbis); - assertEquals("The expected page content", reader.readBytes().toStringUsingUTF8()); + assertThat(reader.readBytes().toStringUsingUTF8()).isEqualTo("The expected page content"); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/bitpacking/TestBitPackingColumn.java b/parquet-column/src/test/java/org/apache/parquet/column/values/bitpacking/TestBitPackingColumn.java index d7eb3be028..5d19a70dd6 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/bitpacking/TestBitPackingColumn.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/bitpacking/TestBitPackingColumn.java @@ -19,8 +19,7 @@ package org.apache.parquet.column.values.bitpacking; import static org.apache.parquet.column.values.bitpacking.Packer.BIG_ENDIAN; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.ByteBuffer; @@ -168,7 +167,7 @@ private void validateEncodeDecode(int bitLength, int[] vals, String expected) th byte[] bytes = w.getBytes().toByteArray(); LOG.debug("vals (" + bitLength + "): " + TestBitPacking.toString(vals)); LOG.debug("bytes: {}", TestBitPacking.toString(bytes)); - assertEquals(type.toString(), expected, TestBitPacking.toString(bytes)); + assertThat(TestBitPacking.toString(bytes)).isEqualTo(expected); ValuesReader r = type.getReader(bound); r.initFromPage(vals.length, ByteBufferInputStream.wrap(ByteBuffer.wrap(bytes))); int[] result = new int[vals.length]; @@ -176,12 +175,14 @@ private void validateEncodeDecode(int bitLength, int[] vals, String expected) th result[i] = r.readInteger(); } LOG.debug("result: {}", TestBitPacking.toString(result)); - assertArrayEquals(type + " result: " + TestBitPacking.toString(result), vals, result); + assertThat(result) + .as(type + " result: " + TestBitPacking.toString(result)) + .isEqualTo(vals); // Test skipping r.initFromPage(vals.length, ByteBufferInputStream.wrap(ByteBuffer.wrap(bytes))); for (int i = 0; i < vals.length; i += 2) { - assertEquals(vals[i], r.readInteger()); + assertThat(r.readInteger()).isEqualTo(vals[i]); r.skip(); } @@ -190,7 +191,7 @@ private void validateEncodeDecode(int bitLength, int[] vals, String expected) th int skipCount; for (int i = 0; i < vals.length; i += skipCount + 1) { skipCount = (vals.length - i) / 2; - assertEquals(vals[i], r.readInteger()); + assertThat(r.readInteger()).isEqualTo(vals[i]); r.skip(skipCount); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/bloomfilter/TestBlockSplitBloomFilter.java b/parquet-column/src/test/java/org/apache/parquet/column/values/bloomfilter/TestBlockSplitBloomFilter.java index fc293cf4a8..2da7b66a80 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/bloomfilter/TestBlockSplitBloomFilter.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/bloomfilter/TestBlockSplitBloomFilter.java @@ -18,10 +18,8 @@ */ package org.apache.parquet.column.values.bloomfilter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.nio.ByteBuffer; @@ -32,7 +30,6 @@ import net.openhft.hashing.LongHashFunction; import org.apache.commons.lang3.RandomStringUtils; import org.apache.parquet.io.api.Binary; -import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -42,9 +39,9 @@ public class TestBlockSplitBloomFilter { @Test public void testConstructor() { BloomFilter bloomFilter1 = new BlockSplitBloomFilter(0); - assertEquals(bloomFilter1.getBitsetSize(), BlockSplitBloomFilter.LOWER_BOUND_BYTES); + assertThat(bloomFilter1.getBitsetSize()).isEqualTo(BlockSplitBloomFilter.LOWER_BOUND_BYTES); BloomFilter bloomFilter3 = new BlockSplitBloomFilter(1000); - assertEquals(bloomFilter3.getBitsetSize(), 1024); + assertThat(bloomFilter3.getBitsetSize()).isEqualTo(1024); } @Rule @@ -68,7 +65,8 @@ public void testBloomFilterForString() { } for (String testString : testStrings) { - assertTrue(bloomFilter.findHash(bloomFilter.hash(Binary.fromString(testString)))); + assertThat(bloomFilter.findHash(bloomFilter.hash(Binary.fromString(testString)))) + .isTrue(); } } @@ -113,9 +111,9 @@ private void testBloomFilterForPrimitives(long seed) { } for (Object v : values) { - assertTrue( - String.format("the value %s should not be filtered, seed = %d", v, seed), - bloomFilter.findHash(bloomFilter.hash(v))); + assertThat(bloomFilter.findHash(bloomFilter.hash(v))) + .as(String.format("the value %s should not be filtered, seed = %d", v, seed)) + .isTrue(); } } @@ -146,7 +144,7 @@ public void testBloomFilterFPPAccuracy() { } // The exist should be probably less than 1000 according FPP 0.01. Add 20% here for error space. - assertTrue(exist < totalCount * (FPP * 1.2)); + assertThat((double) exist).isLessThan(totalCount * (FPP * 1.2)); } @Test @@ -160,12 +158,12 @@ public void testEquals() { bloomFilterTwo.insertHash(bloomFilterTwo.hash(Binary.fromString(word))); } - assertEquals(bloomFilterOne, bloomFilterTwo); + assertThat(bloomFilterTwo).isEqualTo(bloomFilterOne); BloomFilter bloomFilterThree = new BlockSplitBloomFilter(1024); bloomFilterThree.insertHash(bloomFilterThree.hash(Binary.fromString("parquet"))); - assertNotEquals(bloomFilterTwo, bloomFilterThree); + assertThat(bloomFilterThree).isNotEqualTo(bloomFilterTwo); } @Test @@ -177,13 +175,13 @@ public void testBloomFilterNDVs() { // the optimal value formula double numBits = -8 * ndv / Math.log(1 - Math.pow(0.01, 1.0 / 8)); int bytes = (int) numBits / 8; - assertTrue(bytes < 20 * 1024 * 1024); + assertThat(bytes).isLessThan(20 * 1024 * 1024); // a row group of 128MB with one column of UUID type ndv = 128 * 1024 * 1024 / java.util.UUID.randomUUID().toString().length(); numBits = -8 * ndv / Math.log(1 - Math.pow(fpp, 1.0 / 8)); bytes = (int) numBits / 8; - assertTrue(bytes < 5 * 1024 * 1024); + assertThat(bytes).isLessThan(5 * 1024 * 1024); } @Test @@ -193,7 +191,7 @@ public void testAdaptiveBloomFilter() { AdaptiveBlockSplitBloomFilter adaptiveBloomFilter = new AdaptiveBlockSplitBloomFilter(maxBloomFilterSize, candidateNumber, 0.01, null); - assertEquals(candidateNumber, adaptiveBloomFilter.getCandidates().size()); + assertThat(adaptiveBloomFilter.getCandidates()).hasSize(candidateNumber); Set existedValue = new HashSet<>(); while (existedValue.size() < 10000) { @@ -202,11 +200,12 @@ public void testAdaptiveBloomFilter() { existedValue.add(str); } // removed some small bloom filter - assertEquals(7, adaptiveBloomFilter.getCandidates().size()); + assertThat(adaptiveBloomFilter.getCandidates()).hasSize(7); BlockSplitBloomFilter optimalCandidate = adaptiveBloomFilter.optimalCandidate().getBloomFilter(); for (String value : existedValue) { - assertTrue(optimalCandidate.findHash(optimalCandidate.hash(Binary.fromString(value)))); + assertThat(optimalCandidate.findHash(optimalCandidate.hash(Binary.fromString(value)))) + .isTrue(); } int maxCandidateNDV = adaptiveBloomFilter.getCandidates().stream() @@ -220,7 +219,7 @@ public void testAdaptiveBloomFilter() { } // the number of distinct value exceeds the maximum candidate's expected NDV, so only the maximum candidate is // kept - assertEquals(1, adaptiveBloomFilter.getCandidates().size()); + assertThat(adaptiveBloomFilter.getCandidates()).hasSize(1); } @Test @@ -234,16 +233,16 @@ public void testMergeBloomFilter() throws IOException { for (int i = 1024; i < 2048; i++) { otherBloomFilter.insertHash(otherBloomFilter.hash(i)); // Before merging BloomFilter, `mergedBloomFilter` doesn't have any value in `otherBloomFilter` - assertFalse(mergedBloomFilter.findHash(mergedBloomFilter.hash(i))); + assertThat(mergedBloomFilter.findHash(mergedBloomFilter.hash(i))).isFalse(); } mergedBloomFilter.merge(otherBloomFilter); // After merging BloomFilter, `mergedBloomFilter` should have all values in `otherBloomFilter` for (int i = 0; i < 2048; i++) { - assertTrue(mergedBloomFilter.findHash(mergedBloomFilter.hash(i))); + assertThat(mergedBloomFilter.findHash(mergedBloomFilter.hash(i))).isTrue(); } for (int i = 2048; i < 3096; i++) { - assertFalse(otherBloomFilter.findHash(otherBloomFilter.hash(i))); - assertFalse(mergedBloomFilter.findHash(mergedBloomFilter.hash(i))); + assertThat(otherBloomFilter.findHash(otherBloomFilter.hash(i))).isFalse(); + assertThat(mergedBloomFilter.findHash(mergedBloomFilter.hash(i))).isFalse(); } } @@ -252,12 +251,9 @@ public void testMergeBloomFilterFailed() throws IOException { int numBytes = BlockSplitBloomFilter.optimalNumOfBits(1024 * 5, 0.01) / 8; BloomFilter mergedBloomFilter = new BlockSplitBloomFilter(numBytes); BloomFilter otherBloomFilter = new BlockSplitBloomFilter(numBytes * 1024); - try { - mergedBloomFilter.merge(otherBloomFilter); - Assert.fail(); - } catch (IllegalArgumentException e) { - // expected, BloomFilters should have the same size of bitsets - } + assertThatThrownBy(() -> mergedBloomFilter.merge(otherBloomFilter)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("BloomFilters must have the same size of bitset, hashStrategy and algorithm."); } /** @@ -316,13 +312,9 @@ public void testXxHashCorrectness() { data[i] = (byte) i; ByteBuffer input = ByteBuffer.wrap(data, 0, i).order(ByteOrder.nativeOrder()); - assertEquals( - HASHES_OF_LOOPING_BYTES_WITH_SEED_0[i], - LongHashFunction.xx(0).hashBytes(input)); + assertThat(LongHashFunction.xx(0).hashBytes(input)).isEqualTo(HASHES_OF_LOOPING_BYTES_WITH_SEED_0[i]); - assertEquals( - HASHES_OF_LOOPING_BYTES_WITH_SEED_42[i], - LongHashFunction.xx(42).hashBytes(input)); + assertThat(LongHashFunction.xx(42).hashBytes(input)).isEqualTo(HASHES_OF_LOOPING_BYTES_WITH_SEED_42[i]); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesEndToEndTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesEndToEndTest.java index cef7f0ba77..812a025e32 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesEndToEndTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesEndToEndTest.java @@ -18,7 +18,8 @@ */ package org.apache.parquet.column.values.bytestreamsplit; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import java.util.Random; import org.apache.parquet.bytes.ByteBufferInputStream; @@ -49,9 +50,9 @@ public void testFloatPipeline() throws Exception { writer.writeFloat(v); } - assertEquals(numElements * 4, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(numElements * 4); BytesInput input = writer.getBytes(); - assertEquals(numElements * 4, input.size()); + assertThat(input.size()).isEqualTo(numElements * 4); ByteStreamSplitValuesReaderForFloat reader = new ByteStreamSplitValuesReaderForFloat(); @@ -59,7 +60,7 @@ public void testFloatPipeline() throws Exception { for (float expectedValue : values) { float newValue = reader.readFloat(); - assertEquals(expectedValue, newValue, 0.0f); + assertThat(newValue).isCloseTo(expectedValue, offset(0.0f)); } } finally { if (writer != null) { @@ -93,7 +94,8 @@ public void testFloatPipelinePreservesNaNBits() throws Exception { reader.initFromPage(values.length, ByteBufferInputStream.wrap(input.toByteBuffer())); for (float expectedValue : values) { - assertEquals(Float.floatToRawIntBits(expectedValue), Float.floatToRawIntBits(reader.readFloat())); + assertThat(Float.floatToRawIntBits(reader.readFloat())) + .isEqualTo(Float.floatToRawIntBits(expectedValue)); } } finally { if (writer != null) { @@ -118,9 +120,9 @@ public void testDoublePipeline() throws Exception { writer.writeDouble(v); } - assertEquals(numElements * 8, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(numElements * 8); BytesInput input = writer.getBytes(); - assertEquals(numElements * 8, input.size()); + assertThat(input.size()).isEqualTo(numElements * 8); ByteStreamSplitValuesReaderForDouble reader = new ByteStreamSplitValuesReaderForDouble(); @@ -128,7 +130,7 @@ public void testDoublePipeline() throws Exception { for (double expectedValue : values) { double newValue = reader.readDouble(); - assertEquals(expectedValue, newValue, 0.0); + assertThat(newValue).isCloseTo(expectedValue, offset(0.0)); } writer.reset(); @@ -158,7 +160,8 @@ public void testDoublePipelinePreservesNaNBits() throws Exception { reader.initFromPage(values.length, ByteBufferInputStream.wrap(input.toByteBuffer())); for (double expectedValue : values) { - assertEquals(Double.doubleToRawLongBits(expectedValue), Double.doubleToRawLongBits(reader.readDouble())); + assertThat(Double.doubleToRawLongBits(reader.readDouble())) + .isEqualTo(Double.doubleToRawLongBits(expectedValue)); } writer.reset(); @@ -180,16 +183,16 @@ public void testIntegerPipeline() throws Exception { writer.writeInteger(v); } - assertEquals(numElements * 4, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(numElements * 4); BytesInput input = writer.getBytes(); - assertEquals(numElements * 4, input.size()); + assertThat(input.size()).isEqualTo(numElements * 4); ByteStreamSplitValuesReaderForInteger reader = new ByteStreamSplitValuesReaderForInteger(); reader.initFromPage(numElements, ByteBufferInputStream.wrap(input.toByteBuffer())); for (int expectedValue : values) { int newValue = reader.readInteger(); - assertEquals(expectedValue, newValue); + assertThat(newValue).isEqualTo(expectedValue); } writer.reset(); @@ -211,16 +214,16 @@ public void testLongPipeline() throws Exception { writer.writeLong(v); } - assertEquals(numElements * 8, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(numElements * 8); BytesInput input = writer.getBytes(); - assertEquals(numElements * 8, input.size()); + assertThat(input.size()).isEqualTo(numElements * 8); ByteStreamSplitValuesReaderForLong reader = new ByteStreamSplitValuesReaderForLong(); reader.initFromPage(numElements, ByteBufferInputStream.wrap(input.toByteBuffer())); for (long expectedValue : values) { long newValue = reader.readLong(); - assertEquals(expectedValue, newValue); + assertThat(newValue).isEqualTo(expectedValue); } writer.reset(); @@ -250,9 +253,9 @@ public void testFixedLenByteArrayPipeline() throws Exception { writer.writeBytes(Binary.fromConstantByteArray(v)); } - assertEquals(numElements * typeLength, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(numElements * typeLength); BytesInput input = writer.getBytes(); - assertEquals(numElements * typeLength, input.size()); + assertThat(input.size()).isEqualTo(numElements * typeLength); ByteStreamSplitValuesReaderForFLBA reader = new ByteStreamSplitValuesReaderForFLBA(typeLength); reader.initFromPage(numElements, ByteBufferInputStream.wrap(input.toByteBuffer())); @@ -261,10 +264,10 @@ public void testFixedLenByteArrayPipeline() throws Exception { for (byte[] expectedValue : values) { Binary expected = Binary.fromConstantByteArray(expectedValue); Binary actual = reader.readBytes(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); if (previousExpected != null) { // The latest readBytes() call shouldn't have clobbered the result of the previous call. - assertEquals(previousExpected, previousActual); + assertThat(previousActual).isEqualTo(previousExpected); } previousExpected = expected; previousActual = actual; diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesReaderTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesReaderTest.java index dc37ed67ca..3ea2d06a52 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesReaderTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesReaderTest.java @@ -18,8 +18,9 @@ */ package org.apache.parquet.column.values.bytestreamsplit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.data.Offset.offset; import java.nio.ByteBuffer; import java.util.Random; @@ -49,10 +50,12 @@ private void testReader(byte[] input, float[] values) throws Exception { makeReader(input, values.length, ByteStreamSplitValuesReaderForFloat.class); for (float expectedValue : values) { float f = reader.readFloat(); - assertEquals(expectedValue, f, 0.0f); + assertThat(f).isCloseTo(expectedValue, offset(0.0f)); } // All data exhausted - assertThrows(ParquetDecodingException.class, () -> reader.readFloat()); + assertThatThrownBy(() -> reader.readFloat()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("Byte-stream data was already exhausted."); } @Test @@ -105,8 +108,10 @@ public void testExtraReads() throws Exception { ByteStreamSplitValuesReaderForFloat reader = makeReader(byteData, 1, ByteStreamSplitValuesReaderForFloat.class); float f = reader.readFloat(); - assertEquals(2.25f, f, 0.0f); - assertThrows(ParquetDecodingException.class, () -> reader.readFloat()); + assertThat(f).isCloseTo(2.25f, offset(0.0f)); + assertThatThrownBy(() -> reader.readFloat()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("Byte-stream data was already exhausted."); } @Test @@ -124,9 +129,11 @@ public void testSkip() throws Exception { makeReader(byteData, 4, ByteStreamSplitValuesReaderForFloat.class); reader.skip(3); float f = reader.readFloat(); - assertEquals(2.25f, f, 0.0f); + assertThat(f).isCloseTo(2.25f, offset(0.0f)); // Data exhausted - assertThrows(ParquetDecodingException.class, () -> reader.readFloat()); + assertThatThrownBy(() -> reader.readFloat()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("Byte-stream data was already exhausted."); } @Test @@ -134,7 +141,9 @@ public void testSkipOverflow() throws Exception { byte[] byteData = new byte[128]; ByteStreamSplitValuesReaderForFloat reader = makeReader(byteData, 32, ByteStreamSplitValuesReaderForFloat.class); - assertThrows(ParquetDecodingException.class, () -> reader.skip(33)); + assertThatThrownBy(() -> reader.skip(33)) + .isInstanceOf(ParquetDecodingException.class) + .hasMessageContaining("Cannot skip this many elements"); } @Test @@ -142,7 +151,9 @@ public void testSkipUnderflow() throws Exception { byte[] byteData = new byte[128]; ByteStreamSplitValuesReaderForFloat reader = makeReader(byteData, 32, ByteStreamSplitValuesReaderForFloat.class); - assertThrows(ParquetDecodingException.class, () -> reader.skip(-1)); + assertThatThrownBy(() -> reader.skip(-1)) + .isInstanceOf(ParquetDecodingException.class) + .hasMessageContaining("Cannot skip this many elements"); } } @@ -153,10 +164,12 @@ private void testReader(byte[] input, double[] values) throws Exception { makeReader(input, values.length, ByteStreamSplitValuesReaderForDouble.class); for (double expectedValue : values) { double d = reader.readDouble(); - assertEquals(expectedValue, d, 0.0); + assertThat(d).isCloseTo(expectedValue, offset(0.0)); } // All data exhausted - assertThrows(ParquetDecodingException.class, () -> reader.readDouble()); + assertThatThrownBy(() -> reader.readDouble()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("Byte-stream data was already exhausted."); } @Test @@ -223,10 +236,12 @@ private void testReader(byte[] input, int[] values) throws Exception { makeReader(input, values.length, ByteStreamSplitValuesReaderForInteger.class); for (int expectedValue : values) { int actual = reader.readInteger(); - assertEquals(expectedValue, actual); + assertThat(actual).isEqualTo(expectedValue); } // All data exhausted - assertThrows(ParquetDecodingException.class, () -> reader.readInteger()); + assertThatThrownBy(() -> reader.readInteger()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("Byte-stream data was already exhausted."); } @Test @@ -251,10 +266,12 @@ private void testReader(byte[] input, long[] values) throws Exception { makeReader(input, values.length, ByteStreamSplitValuesReaderForLong.class); for (long expectedValue : values) { long actual = reader.readLong(); - assertEquals(expectedValue, actual); + assertThat(actual).isEqualTo(expectedValue); } // All data exhausted - assertThrows(ParquetDecodingException.class, () -> reader.readLong()); + assertThatThrownBy(() -> reader.readLong()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("Byte-stream data was already exhausted."); } @Test @@ -294,16 +311,18 @@ private void testReader(byte[] input, byte[][] values) throws Exception { for (byte[] expectedValue : values) { Binary expected = Binary.fromReusedByteArray(expectedValue); Binary actual = reader.readBytes(); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); if (previousExpected != null) { // The latest readBytes() call shouldn't have clobbered the result of the previous call. - assertEquals(previousExpected, previousActual); + assertThat(previousActual).isEqualTo(previousExpected); } previousExpected = expected; previousActual = actual; } // All data exhausted - assertThrows(ParquetDecodingException.class, () -> reader.readBytes()); + assertThatThrownBy(() -> reader.readBytes()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("Byte-stream data was already exhausted."); } @Test diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesWriterTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesWriterTest.java index 5293adf9d3..61eb8b70f3 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesWriterTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/bytestreamsplit/ByteStreamSplitValuesWriterTest.java @@ -18,7 +18,8 @@ */ package org.apache.parquet.column.values.bytestreamsplit; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import org.apache.parquet.bytes.BytesInput; import org.apache.parquet.bytes.DirectByteBufferAllocator; @@ -54,21 +55,21 @@ public void testSingleElement() throws Exception { writer.writeFloat(value); // Check that the buffer size is exactly the size of one float in bytes. - assertEquals(4, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(4); // Get bytes and check that this doesn't modify the internal state. BytesInput bytesInput = writer.getBytes(); - assertEquals(4, writer.getBufferedSize()); - assertEquals(4, bytesInput.size()); + assertThat(writer.getBufferedSize()).isEqualTo(4); + assertThat(bytesInput.size()).isEqualTo(4); // Check that the bytes are as expected. final float newValue = convertType(bytesInput.toByteArray()); - assertEquals(value, newValue, 0.0f); + assertThat(newValue).isCloseTo(value, offset(0.0f)); // Check that reseting the writer clears the buffered data. writer.reset(); - assertEquals(0, writer.getBufferedSize()); - assertEquals(0, writer.getBytes().size()); + assertThat(writer.getBufferedSize()).isEqualTo(0); + assertThat(writer.getBytes().size()).isEqualTo(0); } finally { if (writer != null) { writer.reset(); @@ -86,9 +87,8 @@ public void testSmallBuffer() throws Exception { writer.writeFloat(1024.921875f); writer.writeFloat(2024.5f); - assertEquals(12, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(12); byte[] rawBytes = writer.getBytes().toByteArray(); - assertEquals(12, rawBytes.length); final byte[] expectedBytes = { (byte) 0x00, (byte) 0x80, (byte) 0x00, @@ -96,9 +96,7 @@ public void testSmallBuffer() throws Exception { (byte) 0x4a, (byte) 0x80, (byte) 0xfd, (byte) 0x43, (byte) 0x44, (byte) 0x44 }; - for (int i = 0; i < 12; ++i) { - assertEquals(expectedBytes[i], rawBytes[i]); - } + assertThat(rawBytes).hasSize(12).isEqualTo(expectedBytes); } finally { if (writer != null) { writer.reset(); @@ -132,21 +130,21 @@ public void testSingleElement() throws Exception { writer.writeDouble(value); // Check that the buffer size is exactly the size of one double in bytes. - assertEquals(8, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(8); // Get bytes and check that this doesn't modify the internal state. BytesInput bytesInput = writer.getBytes(); - assertEquals(8, writer.getBufferedSize()); - assertEquals(8, bytesInput.size()); + assertThat(writer.getBufferedSize()).isEqualTo(8); + assertThat(bytesInput.size()).isEqualTo(8); // Check that the bytes are as expected. final double newValue = convertType(bytesInput.toByteArray()); - assertEquals(value, newValue, 0.0); + assertThat(newValue).isCloseTo(value, offset(0.0)); // Check that reseting the writer clears the buffered data. writer.reset(); - assertEquals(0, writer.getBufferedSize()); - assertEquals(0, writer.getBytes().size()); + assertThat(writer.getBufferedSize()).isEqualTo(0); + assertThat(writer.getBytes().size()).isEqualTo(0); } finally { if (writer != null) { writer.reset(); @@ -164,9 +162,8 @@ public void testSmallBuffer() throws Exception { writer.writeDouble(671.99901111); writer.writeDouble(3500199909.3019013); - assertEquals(24, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(24); byte[] rawBytes = writer.getBytes().toByteArray(); - assertEquals(24, rawBytes.length); final byte[] expectedBytes = { (byte) 0x0c, (byte) 0x53, (byte) 0x2D, @@ -178,10 +175,7 @@ public void testSmallBuffer() throws Exception { (byte) 0x2b, (byte) 0x84, (byte) 0xEA, (byte) 0x40, (byte) 0x40, (byte) 0x41 }; - - for (int i = 0; i < 24; ++i) { - assertEquals(expectedBytes[i], rawBytes[i]); - } + assertThat(rawBytes).hasSize(24).isEqualTo(expectedBytes); } finally { if (writer != null) { writer.reset(); @@ -204,9 +198,8 @@ public void testSmallBuffer() throws Exception { writer.writeInteger(0xFFEEDDCC); writer.writeInteger(0x66778899); - assertEquals(12, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(12); byte[] rawBytes = writer.getBytes().toByteArray(); - assertEquals(12, rawBytes.length); final byte[] expectedBytes = { (byte) 0x44, (byte) 0xCC, (byte) 0x99, @@ -214,9 +207,7 @@ public void testSmallBuffer() throws Exception { (byte) 0x22, (byte) 0xEE, (byte) 0x77, (byte) 0x11, (byte) 0xFF, (byte) 0x66 }; - for (int i = 0; i < expectedBytes.length; ++i) { - assertEquals(expectedBytes[i], rawBytes[i]); - } + assertThat(rawBytes).hasSize(12).isEqualTo(expectedBytes); writer.reset(); writer.close(); } @@ -234,9 +225,8 @@ public void testSmallBuffer() throws Exception { writer.writeLong(0x1122334455667700L); writer.writeLong(0xFFEEDDCCBBAA9988L); - assertEquals(16, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(16); byte[] rawBytes = writer.getBytes().toByteArray(); - assertEquals(16, rawBytes.length); final byte[] expectedBytes = { (byte) 0x00, (byte) 0x88, @@ -248,9 +238,7 @@ public void testSmallBuffer() throws Exception { (byte) 0x22, (byte) 0xEE, (byte) 0x11, (byte) 0xFF, }; - for (int i = 0; i < expectedBytes.length; ++i) { - assertEquals(expectedBytes[i], rawBytes[i]); - } + assertThat(rawBytes).hasSize(16).isEqualTo(expectedBytes); writer.reset(); writer.close(); } @@ -269,16 +257,13 @@ public void testSmallBuffer() throws Exception { writer.writeBytes(Binary.fromString("abc")); writer.writeBytes(Binary.fromString("ghi")); - assertEquals(6, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isEqualTo(6); byte[] rawBytes = writer.getBytes().toByteArray(); - assertEquals(6, rawBytes.length); final byte[] expectedBytes = { 'a', 'g', 'b', 'h', 'c', 'i', }; - for (int i = 0; i < expectedBytes.length; ++i) { - assertEquals(expectedBytes[i], rawBytes[i]); - } + assertThat(rawBytes).hasSize(6).isEqualTo(expectedBytes); writer.reset(); writer.close(); } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForIntegerTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForIntegerTest.java index b293ad881e..ab7b533dac 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForIntegerTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForIntegerTest.java @@ -18,9 +18,8 @@ */ package org.apache.parquet.column.values.delta; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.nio.ByteBuffer; @@ -164,19 +163,19 @@ public void shouldConsumePageDataInInitialization() throws IOException { stream.skipFully(contentOffsetInPage); reader.initFromPage(100, stream); long offset = stream.position(); - assertEquals(valueContent.length + contentOffsetInPage, offset); + assertThat(offset).isEqualTo(valueContent.length + contentOffsetInPage); // should be able to read data correctly for (int i : data) { - assertEquals(i, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(i); } // Testing the deprecated behavior of using byte arrays directly reader = new DeltaBinaryPackingValuesReader(); reader.initFromPage(100, pageContent, contentOffsetInPage); - assertEquals(valueContent.length + contentOffsetInPage, reader.getNextOffset()); + assertThat(reader.getNextOffset()).isEqualTo(valueContent.length + contentOffsetInPage); for (int i : data) { - assertEquals(i, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(i); } } @@ -187,11 +186,9 @@ public void shouldThrowExceptionWhenReadMoreThanWritten() throws IOException { data[i] = i * 32; } shouldWriteAndRead(data); - try { - reader.readInteger(); - } catch (ParquetDecodingException e) { - assertEquals("no more value to read, total value count is " + data.length, e.getMessage()); - } + assertThatThrownBy(() -> reader.readInteger()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("no more value to read, total value count is " + data.length); } @Test @@ -207,7 +204,7 @@ public void shouldSkip() throws IOException { if (i % 3 == 0) { reader.skip(); } else { - assertEquals(i * 32, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(i * 32); } } } @@ -224,7 +221,7 @@ public void shouldSkipN() throws IOException { int skipCount; for (int i = 0; i < data.length; i += skipCount + 1) { skipCount = (data.length - i) / 2; - assertEquals(i * 32, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(i * 32); reader.skip(skipCount); } } @@ -273,11 +270,11 @@ private void shouldReadAndWrite(int[] data, int length) throws IOException { + 4 * miniBlockFlushed * miniBlockSize // data(aligned to miniBlock) + blockFlushed * miniBlockNum // bitWidth of mini blocks + (5.0 * blockFlushed); // min delta for each block - assertTrue(estimatedSize >= page.length); + assertThat(estimatedSize).isGreaterThanOrEqualTo(page.length); reader.initFromPage(100, ByteBufferInputStream.wrap(ByteBuffer.wrap(page))); for (int i = 0; i < length; i++) { - assertEquals(data[i], reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(data[i]); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForLongTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForLongTest.java index cd5571efe1..a22f957f44 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForLongTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/delta/DeltaBinaryPackingValuesWriterForLongTest.java @@ -18,9 +18,8 @@ */ package org.apache.parquet.column.values.delta; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import java.io.IOException; import java.nio.ByteBuffer; @@ -164,19 +163,19 @@ public void shouldReturnCorrectOffsetAfterInitialization() throws IOException { stream.skipFully(contentOffsetInPage); reader.initFromPage(100, stream); long offset = stream.position(); - assertEquals(valueContent.length + contentOffsetInPage, offset); + assertThat(offset).isEqualTo(valueContent.length + contentOffsetInPage); // should be able to read data correctly for (long i : data) { - assertEquals(i, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(i); } // Testing the deprecated behavior of using byte arrays directly reader = new DeltaBinaryPackingValuesReader(); reader.initFromPage(100, pageContent, contentOffsetInPage); - assertEquals(valueContent.length + contentOffsetInPage, reader.getNextOffset()); + assertThat(reader.getNextOffset()).isEqualTo(valueContent.length + contentOffsetInPage); for (long i : data) { - assertEquals(i, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(i); } } @@ -187,11 +186,9 @@ public void shouldThrowExceptionWhenReadMoreThanWritten() throws IOException { data[i] = i * 32; } shouldWriteAndRead(data); - try { - reader.readLong(); - } catch (ParquetDecodingException e) { - assertEquals("no more value to read, total value count is " + data.length, e.getMessage()); - } + assertThatThrownBy(() -> reader.readLong()) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage("no more value to read, total value count is " + data.length); } @Test @@ -207,7 +204,7 @@ public void shouldSkip() throws IOException { if (i % 3 == 0) { reader.skip(); } else { - assertEquals(i * 32, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(i * 32); } } } @@ -224,7 +221,7 @@ public void shouldSkipN() throws IOException { int skipCount; for (int i = 0; i < data.length; i += skipCount + 1) { skipCount = (data.length - i) / 2; - assertEquals(i * 32, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(i * 32); reader.skip(skipCount); } } @@ -273,11 +270,11 @@ private void shouldReadAndWrite(long[] data, int length) throws IOException { + 8 * miniBlockFlushed * miniBlockSize // data(aligned to miniBlock) + blockFlushed * miniBlockNum // bitWidth of mini blocks + (10.0 * blockFlushed); // min delta for each block - assertTrue(estimatedSize >= page.length); + assertThat(estimatedSize).isGreaterThanOrEqualTo(page.length); reader.initFromPage(100, ByteBufferInputStream.wrap(ByteBuffer.wrap(page))); for (int i = 0; i < length; i++) { - assertEquals(data[i], reader.readLong()); + assertThat(reader.readLong()).isEqualTo(data[i]); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/deltalengthbytearray/TestDeltaLengthByteArray.java b/parquet-column/src/test/java/org/apache/parquet/column/values/deltalengthbytearray/TestDeltaLengthByteArray.java index e14dc49329..662b9c1111 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/deltalengthbytearray/TestDeltaLengthByteArray.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/deltalengthbytearray/TestDeltaLengthByteArray.java @@ -18,13 +18,14 @@ */ package org.apache.parquet.column.values.deltalengthbytearray; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; import org.apache.parquet.bytes.DirectByteBufferAllocator; import org.apache.parquet.column.values.Utils; import org.apache.parquet.column.values.ValuesReader; import org.apache.parquet.column.values.delta.DeltaBinaryPackingValuesReader; import org.apache.parquet.io.api.Binary; -import org.junit.Assert; import org.junit.Test; public class TestDeltaLengthByteArray { @@ -44,7 +45,7 @@ public void testSerialization() throws IOException { Binary[] bin = Utils.readData(reader, writer.getBytes().toInputStream(), values.length); for (int i = 0; i < bin.length; i++) { - Assert.assertEquals(Binary.fromString(values[i]), bin[i]); + assertThat(bin[i]).isEqualTo(Binary.fromString(values[i])); } } @@ -58,7 +59,7 @@ public void testRandomStrings() throws IOException { Binary[] bin = Utils.readData(reader, writer.getBytes().toInputStream(), values.length); for (int i = 0; i < bin.length; i++) { - Assert.assertEquals(Binary.fromString(values[i]), bin[i]); + assertThat(bin[i]).isEqualTo(Binary.fromString(values[i])); } } @@ -72,7 +73,7 @@ public void testSkipWithRandomStrings() throws IOException { reader.initFromPage(values.length, writer.getBytes().toInputStream()); for (int i = 0; i < values.length; i += 2) { - Assert.assertEquals(Binary.fromString(values[i]), reader.readBytes()); + assertThat(reader.readBytes()).isEqualTo(Binary.fromString(values[i])); reader.skip(); } @@ -81,7 +82,7 @@ public void testSkipWithRandomStrings() throws IOException { int skipCount; for (int i = 0; i < values.length; i += skipCount + 1) { skipCount = (values.length - i) / 2; - Assert.assertEquals(Binary.fromString(values[i]), reader.readBytes()); + assertThat(reader.readBytes()).isEqualTo(Binary.fromString(values[i])); reader.skip(skipCount); } } @@ -95,7 +96,7 @@ public void testLengths() throws IOException { int[] bin = Utils.readInts(reader, writer.getBytes().toInputStream(), values.length); for (int i = 0; i < bin.length; i++) { - Assert.assertEquals(values[i].length(), bin[i]); + assertThat(bin[i]).isEqualTo(values[i].length()); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/deltastrings/TestDeltaByteArray.java b/parquet-column/src/test/java/org/apache/parquet/column/values/deltastrings/TestDeltaByteArray.java index b73e5562dc..34dba738b7 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/deltastrings/TestDeltaByteArray.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/deltastrings/TestDeltaByteArray.java @@ -18,6 +18,8 @@ */ package org.apache.parquet.column.values.deltastrings; +import static org.assertj.core.api.Assertions.assertThat; + import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.parquet.bytes.ByteBufferInputStream; @@ -26,7 +28,6 @@ import org.apache.parquet.column.values.ValuesReader; import org.apache.parquet.column.values.delta.DeltaBinaryPackingValuesReader; import org.apache.parquet.io.api.Binary; -import org.junit.Assert; import org.junit.Test; public class TestDeltaByteArray { @@ -73,16 +74,16 @@ public void testLengths() throws IOException { int[] bin = Utils.readInts(reader, data, values.length); // test prefix lengths - Assert.assertEquals(0, bin[0]); - Assert.assertEquals(7, bin[1]); - Assert.assertEquals(7, bin[2]); + assertThat(bin[0]).isEqualTo(0); + assertThat(bin[1]).isEqualTo(7); + assertThat(bin[2]).isEqualTo(7); reader = new DeltaBinaryPackingValuesReader(); bin = Utils.readInts(reader, data, values.length); // test suffix lengths - Assert.assertEquals(10, bin[0]); - Assert.assertEquals(0, bin[1]); - Assert.assertEquals(7, bin[2]); + assertThat(bin[0]).isEqualTo(10); + assertThat(bin[1]).isEqualTo(0); + assertThat(bin[2]).isEqualTo(7); } private void assertReadWrite(DeltaByteArrayWriter writer, DeltaByteArrayReader reader, String[] vals) @@ -91,7 +92,7 @@ private void assertReadWrite(DeltaByteArrayWriter writer, DeltaByteArrayReader r Binary[] bin = Utils.readData(reader, writer.getBytes().toInputStream(), vals.length); for (int i = 0; i < bin.length; i++) { - Assert.assertEquals(Binary.fromString(vals[i]), bin[i]); + assertThat(bin[i]).isEqualTo(Binary.fromString(vals[i])); } } @@ -101,7 +102,7 @@ private void assertReadWriteWithSkip(DeltaByteArrayWriter writer, DeltaByteArray reader.initFromPage(vals.length, writer.getBytes().toInputStream()); for (int i = 0; i < vals.length; i += 2) { - Assert.assertEquals(Binary.fromString(vals[i]), reader.readBytes()); + assertThat(reader.readBytes()).isEqualTo(Binary.fromString(vals[i])); reader.skip(); } } @@ -114,7 +115,7 @@ private void assertReadWriteWithSkipN(DeltaByteArrayWriter writer, DeltaByteArra int skipCount; for (int i = 0; i < vals.length; i += skipCount + 1) { skipCount = (vals.length - i) / 2; - Assert.assertEquals(Binary.fromString(vals[i]), reader.readBytes()); + assertThat(reader.readBytes()).isEqualTo(Binary.fromString(vals[i])); reader.skip(skipCount); } } @@ -145,8 +146,8 @@ public void testReusedBackingArrayRegression() throws Exception { writer.writeBytes(Binary.fromReusedByteArray(buffer)); Binary[] decoded = Utils.readData(reader, writer.getBytes().toInputStream(), 3); - Assert.assertEquals(Binary.fromString("parquet-000"), decoded[0]); - Assert.assertEquals(Binary.fromString("parquet-111"), decoded[1]); - Assert.assertEquals(Binary.fromString("parquet-222"), decoded[2]); + assertThat(decoded[0]).isEqualTo(Binary.fromString("parquet-000")); + assertThat(decoded[1]).isEqualTo(Binary.fromString("parquet-111")); + assertThat(decoded[2]).isEqualTo(Binary.fromString("parquet-222")); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/IntListTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/IntListTest.java index 6b5182ab73..2b290781d4 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/IntListTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/IntListTest.java @@ -18,7 +18,8 @@ */ package org.apache.parquet.column.values.dictionary; -import junit.framework.Assert; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; public class IntListTest { @@ -58,7 +59,7 @@ private void doTestIntList(int testSize, int expectedSlabSize) { verifyIteratorResults(testSize, testList); // confirm the size of the current slab - Assert.assertEquals(expectedSlabSize, testList.getCurrentSlabSize()); + assertThat(testList.getCurrentSlabSize()).isEqualTo(expectedSlabSize); } private void populateList(IntList testList, int size) { @@ -73,11 +74,11 @@ private void verifyIteratorResults(int testSize, IntList testList) { while (iterator.hasNext()) { int val = iterator.next(); - Assert.assertEquals(expected, val); + assertThat(val).isEqualTo(expected); expected++; } // ensure we have the correct final value of expected - Assert.assertEquals(testSize, expected); + assertThat(expected).isEqualTo(testSize); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/TestDictionary.java b/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/TestDictionary.java index 52956a5bfc..c7f43ec024 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/TestDictionary.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/dictionary/TestDictionary.java @@ -25,9 +25,7 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.FLOAT; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.data.Offset.offset; import java.io.IOException; import java.nio.ByteBuffer; @@ -55,7 +53,6 @@ import org.apache.parquet.io.api.Binary; import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -144,38 +141,38 @@ public void testSkipInBinaryDictionary() throws Exception { try (ValuesWriter cw = newPlainBinaryDictionaryValuesWriter(1000, 10000)) { writeRepeated(100, cw, "a"); writeDistinct(100, cw, "b"); - assertEquals(PLAIN_DICTIONARY, cw.getEncoding()); + assertThat(cw.getEncoding()).isEqualTo(PLAIN_DICTIONARY); // Test skip and skip-n with dictionary encoding ByteBufferInputStream stream = cw.getBytes().toInputStream(); DictionaryValuesReader cr = initDicReader(cw, BINARY); cr.initFromPage(200, stream); for (int i = 0; i < 100; i += 2) { - assertEquals(Binary.fromString("a" + i % 10), cr.readBytes()); + assertThat(cr.readBytes()).isEqualTo(Binary.fromString("a" + i % 10)); cr.skip(); } int skipCount; for (int i = 0; i < 100; i += skipCount + 1) { skipCount = (100 - i) / 2; - assertEquals(Binary.fromString("b" + i), cr.readBytes()); + assertThat(cr.readBytes()).isEqualTo(Binary.fromString("b" + i)); cr.skip(skipCount); } // Ensure fallback writeDistinct(1000, cw, "c"); - assertEquals(PLAIN, cw.getEncoding()); + assertThat(cw.getEncoding()).isEqualTo(PLAIN); // Test skip and skip-n with plain encoding (after fallback) ValuesReader plainReader = new BinaryPlainValuesReader(); plainReader.initFromPage(1200, cw.getBytes().toInputStream()); plainReader.skip(200); for (int i = 0; i < 100; i += 2) { - assertEquals("c" + i, plainReader.readBytes().toStringUsingUTF8()); + assertThat(plainReader.readBytes().toStringUsingUTF8()).isEqualTo("c" + i); plainReader.skip(); } for (int i = 100; i < 1000; i += skipCount + 1) { skipCount = (1000 - i) / 2; - assertEquals(Binary.fromString("c" + i), plainReader.readBytes()); + assertThat(plainReader.readBytes()).isEqualTo(Binary.fromString("c" + i)); plainReader.skip(skipCount); } } @@ -193,9 +190,9 @@ public void testBinaryDictionaryFallBack() throws IOException { cw.writeBytes(binary); dataSize += (binary.length() + 4); if (dataSize < fallBackThreshold) { - assertEquals(PLAIN_DICTIONARY, cw.getEncoding()); + assertThat(cw.getEncoding()).isEqualTo(PLAIN_DICTIONARY); } else { - assertEquals(PLAIN, cw.getEncoding()); + assertThat(cw.getEncoding()).isEqualTo(PLAIN); } } @@ -204,12 +201,12 @@ public void testBinaryDictionaryFallBack() throws IOException { reader.initFromPage(100, cw.getBytes().toInputStream()); for (long i = 0; i < 100; i++) { - assertEquals(Binary.fromString("str" + i), reader.readBytes()); + assertThat(reader.readBytes()).isEqualTo(Binary.fromString("str" + i)); } // simulate cutting the page cw.reset(); - assertEquals(0, cw.getBufferedSize()); + assertThat(cw.getBufferedSize()).isEqualTo(0); } } @@ -224,7 +221,7 @@ public void testBinaryDictionaryIntegerOverflow() { cw.writeBytes(Binary.fromString("hello")); cw.writeBytes(mock); - assertEquals(PLAIN, cw.getEncoding()); + assertThat(cw.getEncoding()).isEqualTo(PLAIN); } } @@ -357,26 +354,26 @@ public void testLongDictionary() throws IOException { cw.writeLong(i % 50); } BytesInput bytes1 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); for (long i = COUNT2; i > 0; i--) { cw.writeLong(i % 50); } BytesInput bytes2 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); DictionaryValuesReader cr = initDicReader(cw, PrimitiveTypeName.INT64); cr.initFromPage(COUNT, bytes1.toInputStream()); for (long i = 0; i < COUNT; i++) { long back = cr.readLong(); - assertEquals(i % 50, back); + assertThat(back).isEqualTo(i % 50); } cr.initFromPage(COUNT2, bytes2.toInputStream()); for (long i = COUNT2; i > 0; i--) { long back = cr.readLong(); - assertEquals(i % 50, back); + assertThat(back).isEqualTo(i % 50); } } } @@ -390,22 +387,22 @@ private void roundTripLong( for (long i = 0; i < 100; i++) { cw.writeLong(i); if (i < fallBackThreshold) { - assertEquals(cw.getEncoding(), PLAIN_DICTIONARY); + assertThat(cw.getEncoding()).isEqualTo(PLAIN_DICTIONARY); } else { - assertEquals(cw.getEncoding(), PLAIN); + assertThat(cw.getEncoding()).isEqualTo(PLAIN); } } reader.initFromPage(100, cw.getBytes().toInputStream()); for (long i = 0; i < 100; i++) { - assertEquals(i, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(i); } // Test skip with plain encoding reader.initFromPage(100, cw.getBytes().toInputStream()); for (int i = 0; i < 100; i += 2) { - assertEquals(i, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(i); reader.skip(); } @@ -414,7 +411,7 @@ private void roundTripLong( int skipCount; for (int i = 0; i < 100; i += skipCount + 1) { skipCount = (100 - i) / 2; - assertEquals(i, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(i); reader.skip(skipCount); } } @@ -431,7 +428,7 @@ public void testLongDictionaryFallBack() throws IOException { roundTripLong(cw, reader, maxDictionaryByteSize); // simulate cutting the page cw.reset(); - assertEquals(0, cw.getBufferedSize()); + assertThat(cw.getBufferedSize()).isEqualTo(0); cw.resetDictionary(); roundTripLong(cw, reader, maxDictionaryByteSize); @@ -451,26 +448,26 @@ public void testDoubleDictionary() throws IOException { } BytesInput bytes1 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); for (double i = COUNT2; i > 0; i--) { cw.writeDouble(i % 50); } BytesInput bytes2 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); final DictionaryValuesReader cr = initDicReader(cw, DOUBLE); cr.initFromPage(COUNT, bytes1.toInputStream()); for (double i = 0; i < COUNT; i++) { double back = cr.readDouble(); - assertEquals(i % 50, back, 0.0); + assertThat(back).isCloseTo(i % 50, offset(0.0)); } cr.initFromPage(COUNT2, bytes2.toInputStream()); for (double i = COUNT2; i > 0; i--) { double back = cr.readDouble(); - assertEquals(i % 50, back, 0.0); + assertThat(back).isCloseTo(i % 50, offset(0.0)); } } } @@ -494,13 +491,14 @@ public void testDoubleDictionaryPreservesNaNBits() throws IOException { } BytesInput bytes = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(dictionaryValues.length, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(dictionaryValues.length); final DictionaryValuesReader cr = initDicReader(cw, DOUBLE); cr.initFromPage(dictionaryValues.length * 10, bytes.toInputStream()); for (int i = 0; i < 10; i++) { for (double expected : dictionaryValues) { - assertEquals(Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(cr.readDouble())); + assertThat(Double.doubleToRawLongBits(cr.readDouble())) + .isEqualTo(Double.doubleToRawLongBits(expected)); } } } @@ -515,22 +513,22 @@ private void roundTripDouble( for (double i = 0; i < 100; i++) { cw.writeDouble(i); if (i < fallBackThreshold) { - assertEquals(cw.getEncoding(), PLAIN_DICTIONARY); + assertThat(cw.getEncoding()).isEqualTo(PLAIN_DICTIONARY); } else { - assertEquals(cw.getEncoding(), PLAIN); + assertThat(cw.getEncoding()).isEqualTo(PLAIN); } } reader.initFromPage(100, cw.getBytes().toInputStream()); for (double i = 0; i < 100; i++) { - assertEquals(i, reader.readDouble(), 0.00001); + assertThat(reader.readDouble()).isCloseTo(i, offset(0.00001)); } // Test skip with plain encoding reader.initFromPage(100, cw.getBytes().toInputStream()); for (int i = 0; i < 100; i += 2) { - assertEquals(i, reader.readDouble(), 0.0); + assertThat(reader.readDouble()).isCloseTo(i, offset(0.0)); reader.skip(); } @@ -539,7 +537,7 @@ private void roundTripDouble( int skipCount; for (int i = 0; i < 100; i += skipCount + 1) { skipCount = (100 - i) / 2; - assertEquals(i, reader.readDouble(), 0.0); + assertThat(reader.readDouble()).isCloseTo(i, offset(0.0)); reader.skip(skipCount); } } @@ -557,7 +555,7 @@ public void testDoubleDictionaryFallBack() throws IOException { roundTripDouble(cw, reader, maxDictionaryByteSize); // simulate cutting the page cw.reset(); - assertEquals(0, cw.getBufferedSize()); + assertThat(cw.getBufferedSize()).isEqualTo(0); cw.resetDictionary(); roundTripDouble(cw, reader, maxDictionaryByteSize); @@ -576,26 +574,26 @@ public void testIntDictionary() throws IOException { cw.writeInteger(i % 50); } BytesInput bytes1 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); for (int i = COUNT2; i > 0; i--) { cw.writeInteger(i % 50); } BytesInput bytes2 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); DictionaryValuesReader cr = initDicReader(cw, INT32); cr.initFromPage(COUNT, bytes1.toInputStream()); for (int i = 0; i < COUNT; i++) { int back = cr.readInteger(); - assertEquals(i % 50, back); + assertThat(back).isEqualTo(i % 50); } cr.initFromPage(COUNT2, bytes2.toInputStream()); for (int i = COUNT2; i > 0; i--) { int back = cr.readInteger(); - assertEquals(i % 50, back); + assertThat(back).isEqualTo(i % 50); } } } @@ -609,22 +607,22 @@ private void roundTripInt( for (int i = 0; i < 100; i++) { cw.writeInteger(i); if (i < fallBackThreshold) { - assertEquals(cw.getEncoding(), PLAIN_DICTIONARY); + assertThat(cw.getEncoding()).isEqualTo(PLAIN_DICTIONARY); } else { - assertEquals(cw.getEncoding(), PLAIN); + assertThat(cw.getEncoding()).isEqualTo(PLAIN); } } reader.initFromPage(100, cw.getBytes().toInputStream()); for (int i = 0; i < 100; i++) { - assertEquals(i, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(i); } // Test skip with plain encoding reader.initFromPage(100, cw.getBytes().toInputStream()); for (int i = 0; i < 100; i += 2) { - assertEquals(i, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(i); reader.skip(); } @@ -633,7 +631,7 @@ private void roundTripInt( int skipCount; for (int i = 0; i < 100; i += skipCount + 1) { skipCount = (100 - i) / 2; - assertEquals(i, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(i); reader.skip(skipCount); } } @@ -651,7 +649,7 @@ public void testIntDictionaryFallBack() throws IOException { roundTripInt(cw, reader, maxDictionaryByteSize); // simulate cutting the page cw.reset(); - assertEquals(0, cw.getBufferedSize()); + assertThat(cw.getBufferedSize()).isEqualTo(0); cw.resetDictionary(); roundTripInt(cw, reader, maxDictionaryByteSize); @@ -670,26 +668,26 @@ public void testFloatDictionary() throws IOException { cw.writeFloat(i % 50); } BytesInput bytes1 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); for (float i = COUNT2; i > 0; i--) { cw.writeFloat(i % 50); } BytesInput bytes2 = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(50, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(50); DictionaryValuesReader cr = initDicReader(cw, FLOAT); cr.initFromPage(COUNT, bytes1.toInputStream()); for (float i = 0; i < COUNT; i++) { float back = cr.readFloat(); - assertEquals(i % 50, back, 0.0f); + assertThat(back).isCloseTo(i % 50, offset(0.0f)); } cr.initFromPage(COUNT2, bytes2.toInputStream()); for (float i = COUNT2; i > 0; i--) { float back = cr.readFloat(); - assertEquals(i % 50, back, 0.0f); + assertThat(back).isCloseTo(i % 50, offset(0.0f)); } } } @@ -713,13 +711,13 @@ public void testFloatDictionaryPreservesNaNBits() throws IOException { } BytesInput bytes = getBytesAndCheckEncoding(cw, PLAIN_DICTIONARY); - assertEquals(dictionaryValues.length, cw.initialWriter.getDictionarySize()); + assertThat(cw.initialWriter.getDictionarySize()).isEqualTo(dictionaryValues.length); final DictionaryValuesReader cr = initDicReader(cw, FLOAT); cr.initFromPage(dictionaryValues.length * 10, bytes.toInputStream()); for (int i = 0; i < 10; i++) { for (float expected : dictionaryValues) { - assertEquals(Float.floatToRawIntBits(expected), Float.floatToRawIntBits(cr.readFloat())); + assertThat(Float.floatToRawIntBits(cr.readFloat())).isEqualTo(Float.floatToRawIntBits(expected)); } } } @@ -734,22 +732,22 @@ private void roundTripFloat( for (float i = 0; i < 100; i++) { cw.writeFloat(i); if (i < fallBackThreshold) { - assertEquals(cw.getEncoding(), PLAIN_DICTIONARY); + assertThat(cw.getEncoding()).isEqualTo(PLAIN_DICTIONARY); } else { - assertEquals(cw.getEncoding(), PLAIN); + assertThat(cw.getEncoding()).isEqualTo(PLAIN); } } reader.initFromPage(100, cw.getBytes().toInputStream()); for (float i = 0; i < 100; i++) { - assertEquals(i, reader.readFloat(), 0.00001); + assertThat(reader.readFloat()).isCloseTo(i, offset(0.00001f)); } // Test skip with plain encoding reader.initFromPage(100, cw.getBytes().toInputStream()); for (int i = 0; i < 100; i += 2) { - assertEquals(i, reader.readFloat(), 0.0f); + assertThat(reader.readFloat()).isCloseTo(i, offset(0.0f)); reader.skip(); } @@ -758,7 +756,7 @@ private void roundTripFloat( int skipCount; for (int i = 0; i < 100; i += skipCount + 1) { skipCount = (100 - i) / 2; - assertEquals(i, reader.readFloat(), 0.0f); + assertThat(reader.readFloat()).isCloseTo(i, offset(0.0f)); reader.skip(skipCount); } } @@ -776,7 +774,7 @@ public void testFloatDictionaryFallBack() throws IOException { roundTripFloat(cw, reader, maxDictionaryByteSize); // simulate cutting the page cw.reset(); - assertEquals(0, cw.getBufferedSize()); + assertThat(cw.getBufferedSize()).isEqualTo(0); cw.resetDictionary(); roundTripFloat(cw, reader, maxDictionaryByteSize); @@ -815,9 +813,9 @@ public void testBooleanDictionary() throws IOException { PlainBooleanDictionary dictionary = new PlainBooleanDictionary(dictionaryPage); // Verify dictionary decoding - assertFalse(dictionary.decodeToBoolean(0)); - assertTrue(dictionary.decodeToBoolean(1)); - assertEquals(1, dictionary.getMaxId()); + assertThat(dictionary.decodeToBoolean(0)).isFalse(); + assertThat(dictionary.decodeToBoolean(1)).isTrue(); + assertThat(dictionary.getMaxId()).isEqualTo(1); } @Test @@ -829,8 +827,8 @@ public void testBooleanDictionarySingleValue() throws IOException { PlainBooleanDictionary dictionaryTrue = new PlainBooleanDictionary(dictionaryPageTrue); - assertTrue(dictionaryTrue.decodeToBoolean(0)); - assertEquals(0, dictionaryTrue.getMaxId()); + assertThat(dictionaryTrue.decodeToBoolean(0)).isTrue(); + assertThat(dictionaryTrue.getMaxId()).isEqualTo(0); // Test dictionary with only false value // Bit-packed: bit 0 = false (0) => byte = 0b00000000 = 0x00 @@ -839,8 +837,8 @@ public void testBooleanDictionarySingleValue() throws IOException { PlainBooleanDictionary dictionaryFalse = new PlainBooleanDictionary(dictionaryPageFalse); - assertFalse(dictionaryFalse.decodeToBoolean(0)); - assertEquals(0, dictionaryFalse.getMaxId()); + assertThat(dictionaryFalse.decodeToBoolean(0)).isFalse(); + assertThat(dictionaryFalse.getMaxId()).isEqualTo(0); } @Test @@ -852,9 +850,9 @@ public void testBooleanDictionaryToString() throws IOException { PlainBooleanDictionary dictionary = new PlainBooleanDictionary(dictionaryPage); String str = dictionary.toString(); - Assert.assertTrue(str.contains("PlainBooleanDictionary")); - Assert.assertTrue(str.contains("0 => false")); - Assert.assertTrue(str.contains("1 => true")); + assertThat(str).contains("PlainBooleanDictionary"); + assertThat(str).contains("0 => false"); + assertThat(str).contains("1 => true"); } @Test @@ -866,9 +864,9 @@ public void testBooleanDictionaryWithDictionaryEncoding() throws IOException { PlainBooleanDictionary dictionary = new PlainBooleanDictionary(dictionaryPage); - assertEquals(true, dictionary.decodeToBoolean(0)); - assertEquals(false, dictionary.decodeToBoolean(1)); - assertEquals(1, dictionary.getMaxId()); + assertThat(dictionary.decodeToBoolean(0)).isTrue(); + assertThat(dictionary.decodeToBoolean(1)).isFalse(); + assertThat(dictionary.getMaxId()).isEqualTo(1); } private DictionaryValuesReader initDicReader(ValuesWriter cw, PrimitiveTypeName type) throws IOException { @@ -882,7 +880,7 @@ private DictionaryValuesReader initDicReader(ValuesWriter cw, PrimitiveTypeName private void checkDistinct(int COUNT, BytesInput bytes, ValuesReader cr, String prefix) throws IOException { cr.initFromPage(COUNT, bytes.toInputStream()); for (int i = 0; i < COUNT; i++) { - Assert.assertEquals(prefix + i, cr.readBytes().toStringUsingUTF8()); + assertThat(cr.readBytes().toStringUsingUTF8()).isEqualTo(prefix + i); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/factory/DefaultValuesWriterFactoryTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/factory/DefaultValuesWriterFactoryTest.java index 17f786c4a5..397679a3ae 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/factory/DefaultValuesWriterFactoryTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/factory/DefaultValuesWriterFactoryTest.java @@ -23,8 +23,7 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.FLOAT; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.apache.parquet.schema.Types.required; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Field; import org.apache.parquet.bytes.ByteBufferAllocator; @@ -795,10 +794,7 @@ private ValuesWriterFactory getDefaultFactory( } private void validateWriterType(ValuesWriter writer, Class valuesWriterClass) { - assertTrue( - "Not instance of " + valuesWriterClass.getName() + ": actual class is " - + writer.getClass().getName(), - valuesWriterClass.isInstance(writer)); + assertThat(writer).isInstanceOf(valuesWriterClass); } private void validateFallbackWriter( @@ -841,14 +837,17 @@ public void testFactoryIsolation_eachPropertiesUsesOwnAllocator() throws Excepti ValuesWriter writerA2 = propsA.getValuesWriterFactory().newValuesWriter(col); // All writers from propsA should use allocatorA - assertSame("writerA should use allocatorA", allocatorA, getDictionaryWriterAllocator(writerA)); - assertSame( - "writerA2 should use allocatorA (not allocatorB from later initialization)", - allocatorA, - getDictionaryWriterAllocator(writerA2)); + assertThat(getDictionaryWriterAllocator(writerA)) + .as("writerA should use allocatorA") + .isSameAs(allocatorA); + assertThat(getDictionaryWriterAllocator(writerA2)) + .as("writerA2 should use allocatorA (not allocatorB from later initialization)") + .isSameAs(allocatorA); // Writers from propsB should use allocatorB - assertSame("writerB should use allocatorB", allocatorB, getDictionaryWriterAllocator(writerB)); + assertThat(getDictionaryWriterAllocator(writerB)) + .as("writerB should use allocatorB") + .isSameAs(allocatorB); } private static ByteBufferAllocator getDictionaryWriterAllocator(ValuesWriter writer) throws Exception { diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBinaryPlainValuesWriterReader.java b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBinaryPlainValuesWriterReader.java index da29bddb95..bec0ddcd5c 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBinaryPlainValuesWriterReader.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBinaryPlainValuesWriterReader.java @@ -18,8 +18,7 @@ */ package org.apache.parquet.column.values.plain; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.ByteBuffer; @@ -76,7 +75,7 @@ public void testScalarRoundTrip() throws IOException { reader.initFromPage(strings.length, wrapForReading(writer)); for (String s : strings) { - assertEquals(s, reader.readBytes().toStringUsingUTF8()); + assertThat(reader.readBytes().toStringUsingUTF8()).isEqualTo(s); } } } @@ -94,7 +93,7 @@ public void testSkip() throws IOException { reader.initFromPage(3, wrapForReading(writer)); reader.skip(); // skip "first" - assertEquals("second", reader.readBytes().toStringUsingUTF8()); + assertThat(reader.readBytes().toStringUsingUTF8()).isEqualTo("second"); } } @@ -125,8 +124,8 @@ public void testBinaryContent() throws IOException { BinaryPlainValuesReader reader = new BinaryPlainValuesReader(); reader.initFromPage(2, wrapForReading(writer)); - assertArrayEquals(raw1, reader.readBytes().getBytes()); - assertArrayEquals(raw2, reader.readBytes().getBytes()); + assertThat(reader.readBytes().getBytes()).isEqualTo(raw1); + assertThat(reader.readBytes().getBytes()).isEqualTo(raw2); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBooleanPlainValuesWriterReader.java b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBooleanPlainValuesWriterReader.java index aba92ec68e..66943daf0f 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBooleanPlainValuesWriterReader.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestBooleanPlainValuesWriterReader.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.column.values.plain; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.ByteBuffer; @@ -42,7 +42,7 @@ private ByteBufferInputStream wrapForReading(BooleanPlainValuesWriter writer) th @Test public void testEncoding() { try (BooleanPlainValuesWriter writer = new BooleanPlainValuesWriter()) { - assertEquals(Encoding.PLAIN, writer.getEncoding()); + assertThat(writer.getEncoding()).isEqualTo(Encoding.PLAIN); } } @@ -60,7 +60,7 @@ public void testScalarRoundTrip() throws IOException { reader.initFromPage(expected.length, wrapForReading(writer)); for (int i = 0; i < expected.length; i++) { - assertEquals("value at index " + i, expected[i], reader.readBoolean()); + assertThat(reader.readBoolean()).as("value at index " + i).isEqualTo(expected[i]); } } } @@ -79,7 +79,7 @@ public void testPartialByte() throws IOException { reader.initFromPage(expected.length, wrapForReading(writer)); for (int i = 0; i < expected.length; i++) { - assertEquals("value at index " + i, expected[i], reader.readBoolean()); + assertThat(reader.readBoolean()).as("value at index " + i).isEqualTo(expected[i]); } } } @@ -98,9 +98,9 @@ public void testSkip() throws IOException { reader.initFromPage(values.length, wrapForReading(writer)); reader.skip(); // skip true - assertEquals(false, reader.readBoolean()); + assertThat(reader.readBoolean()).isFalse(); reader.skip(2); // skip true, false - assertEquals(true, reader.readBoolean()); + assertThat(reader.readBoolean()).isTrue(); } } @@ -114,7 +114,7 @@ public void testSingleValue() throws IOException { BooleanPlainValuesReader reader = new BooleanPlainValuesReader(); reader.initFromPage(1, wrapForReading(writer)); - assertEquals(true, reader.readBoolean()); + assertThat(reader.readBoolean()).isTrue(); } } @@ -126,7 +126,7 @@ public void testWriterReset() throws IOException { writer.writeBoolean(true); writer.writeBoolean(false); writer.reset(); - assertEquals(0, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isZero(); writer.writeBoolean(false); writer.writeBoolean(true); @@ -134,8 +134,8 @@ public void testWriterReset() throws IOException { BooleanPlainValuesReader reader = new BooleanPlainValuesReader(); reader.initFromPage(2, wrapForReading(writer)); - assertEquals(false, reader.readBoolean()); - assertEquals(true, reader.readBoolean()); + assertThat(reader.readBoolean()).isFalse(); + assertThat(reader.readBoolean()).isTrue(); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestFixedLenByteArrayPlainValuesWriterReader.java b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestFixedLenByteArrayPlainValuesWriterReader.java index 09ec6dbe7a..3700d05dbf 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestFixedLenByteArrayPlainValuesWriterReader.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestFixedLenByteArrayPlainValuesWriterReader.java @@ -18,9 +18,8 @@ */ package org.apache.parquet.column.values.plain; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.nio.ByteBuffer; @@ -76,7 +75,7 @@ private Binary fixedBinary(int seed) { @Test public void testEncoding() { try (FixedLenByteArrayPlainValuesWriter writer = newWriter()) { - assertEquals(Encoding.PLAIN, writer.getEncoding()); + assertThat(writer.getEncoding()).isEqualTo(Encoding.PLAIN); } } @@ -94,10 +93,9 @@ public void testScalarRoundTrip() throws IOException { reader.initFromPage(expected.length, wrapForReading(writer)); for (int i = 0; i < expected.length; i++) { - assertArrayEquals( - "value at index " + i, - expected[i].getBytes(), - reader.readBytes().getBytes()); + assertThat(reader.readBytes().getBytes()) + .as("value at index " + i) + .isEqualTo(expected[i].getBytes()); } } } @@ -116,9 +114,9 @@ public void testSkip() throws IOException { reader.initFromPage(4, wrapForReading(writer)); reader.skip(); // skip 1 - assertArrayEquals(fixedBinary(2).getBytes(), reader.readBytes().getBytes()); + assertThat(reader.readBytes().getBytes()).isEqualTo(fixedBinary(2).getBytes()); reader.skip(1); // skip 3 - assertArrayEquals(fixedBinary(4).getBytes(), reader.readBytes().getBytes()); + assertThat(reader.readBytes().getBytes()).isEqualTo(fixedBinary(4).getBytes()); } } @@ -128,12 +126,9 @@ public void testSkip() throws IOException { public void testRejectWrongLengthScalar() { try (FixedLenByteArrayPlainValuesWriter writer = newWriter()) { Binary wrongLen = Binary.fromConstantByteArray(new byte[FIXED_LEN + 1]); - try { - writer.writeBytes(wrongLen); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } + assertThatThrownBy(() -> writer.writeBytes(wrongLen)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Fixed Binary size 13 does not match field type length 12"); } } @@ -144,14 +139,14 @@ public void testWriterReset() throws IOException { try (FixedLenByteArrayPlainValuesWriter writer = newWriter()) { writer.writeBytes(fixedBinary(99)); writer.reset(); - assertEquals(0, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isZero(); writer.writeBytes(fixedBinary(42)); FixedLenByteArrayPlainValuesReader reader = new FixedLenByteArrayPlainValuesReader(FIXED_LEN); reader.initFromPage(1, wrapForReading(writer)); - assertArrayEquals(fixedBinary(42).getBytes(), reader.readBytes().getBytes()); + assertThat(reader.readBytes().getBytes()).isEqualTo(fixedBinary(42).getBytes()); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestPlainValuesWriterReader.java b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestPlainValuesWriterReader.java index 6b98f74b07..93356897f7 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestPlainValuesWriterReader.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/plain/TestPlainValuesWriterReader.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.column.values.plain; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.nio.ByteBuffer; @@ -62,7 +62,7 @@ private ByteBufferInputStream wrapForReading(PlainValuesWriter writer) throws IO @Test public void testEncoding() { try (PlainValuesWriter writer = newWriter()) { - assertEquals(Encoding.PLAIN, writer.getEncoding()); + assertThat(writer.getEncoding()).isEqualTo(Encoding.PLAIN); } } @@ -80,7 +80,7 @@ public void testIntegerScalarRoundTrip() throws IOException { reader.initFromPage(expected.length, wrapForReading(writer)); for (int i = 0; i < expected.length; i++) { - assertEquals("value at index " + i, expected[i], reader.readInteger()); + assertThat(reader.readInteger()).as("value at index " + i).isEqualTo(expected[i]); } } } @@ -99,7 +99,7 @@ public void testLongScalarRoundTrip() throws IOException { reader.initFromPage(expected.length, wrapForReading(writer)); for (int i = 0; i < expected.length; i++) { - assertEquals("value at index " + i, expected[i], reader.readLong()); + assertThat(reader.readLong()).as("value at index " + i).isEqualTo(expected[i]); } } } @@ -127,10 +127,9 @@ public void testFloatScalarRoundTrip() throws IOException { reader.initFromPage(expected.length, wrapForReading(writer)); for (int i = 0; i < expected.length; i++) { - assertEquals( - "value at index " + i, - Float.floatToIntBits(expected[i]), - Float.floatToIntBits(reader.readFloat())); + assertThat(Float.floatToIntBits(reader.readFloat())) + .as("value at index " + i) + .isEqualTo(Float.floatToIntBits(expected[i])); } } } @@ -158,10 +157,9 @@ public void testDoubleScalarRoundTrip() throws IOException { reader.initFromPage(expected.length, wrapForReading(writer)); for (int i = 0; i < expected.length; i++) { - assertEquals( - "value at index " + i, - Double.doubleToLongBits(expected[i]), - Double.doubleToLongBits(reader.readDouble())); + assertThat(Double.doubleToLongBits(reader.readDouble())) + .as("value at index " + i) + .isEqualTo(Double.doubleToLongBits(expected[i])); } } } @@ -180,9 +178,9 @@ public void testIntegerSkipThenRead() throws IOException { reader.initFromPage(4, wrapForReading(writer)); reader.skip(); // skip 1 - assertEquals(2, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(2); reader.skip(1); // skip 3 - assertEquals(4, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(4); } } @@ -197,7 +195,7 @@ public void testLongSkip() throws IOException { reader.initFromPage(3, wrapForReading(writer)); reader.skip(2); - assertEquals(300L, reader.readLong()); + assertThat(reader.readLong()).isEqualTo(300L); } } @@ -212,7 +210,7 @@ public void testFloatSkip() throws IOException { reader.initFromPage(3, wrapForReading(writer)); reader.skip(); - assertEquals(Float.floatToIntBits(2.0f), Float.floatToIntBits(reader.readFloat())); + assertThat(Float.floatToIntBits(reader.readFloat())).isEqualTo(Float.floatToIntBits(2.0f)); } } @@ -227,7 +225,7 @@ public void testDoubleSkip() throws IOException { reader.initFromPage(3, wrapForReading(writer)); reader.skip(); - assertEquals(Double.doubleToLongBits(2.0), Double.doubleToLongBits(reader.readDouble())); + assertThat(Double.doubleToLongBits(reader.readDouble())).isEqualTo(Double.doubleToLongBits(2.0)); } } @@ -238,14 +236,14 @@ public void testWriterReset() throws IOException { try (PlainValuesWriter writer = newWriter()) { writer.writeInteger(999); writer.reset(); - assertEquals(0, writer.getBufferedSize()); + assertThat(writer.getBufferedSize()).isZero(); writer.writeInteger(42); PlainValuesReader.IntegerPlainValuesReader reader = new PlainValuesReader.IntegerPlainValuesReader(); reader.initFromPage(1, wrapForReading(writer)); - assertEquals(42, reader.readInteger()); + assertThat(reader.readInteger()).isEqualTo(42); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/rle/RunLengthBitPackingHybridIntegrationTest.java b/parquet-column/src/test/java/org/apache/parquet/column/values/rle/RunLengthBitPackingHybridIntegrationTest.java index 01a4c96e85..c4bbea4d11 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/rle/RunLengthBitPackingHybridIntegrationTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/rle/RunLengthBitPackingHybridIntegrationTest.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.column.values.rle; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.nio.ByteBuffer; import org.apache.parquet.bytes.ByteBufferInputStream; @@ -62,25 +62,25 @@ private void doIntegrationTest(int bitWidth) throws Exception { RunLengthBitPackingHybridDecoder decoder = new RunLengthBitPackingHybridDecoder(bitWidth, in); for (int i = 0; i < 100; i++) { - assertEquals(i % modValue, decoder.readInt()); + assertThat(decoder.readInt()).isEqualTo(i % modValue); } for (int i = 0; i < 100; i++) { - assertEquals(77 % modValue, decoder.readInt()); + assertThat(decoder.readInt()).isEqualTo(77 % modValue); } for (int i = 0; i < 100; i++) { - assertEquals(88 % modValue, decoder.readInt()); + assertThat(decoder.readInt()).isEqualTo(88 % modValue); } for (int i = 0; i < 1000; i++) { - assertEquals(i % modValue, decoder.readInt()); - assertEquals(i % modValue, decoder.readInt()); - assertEquals(i % modValue, decoder.readInt()); + assertThat(decoder.readInt()).isEqualTo(i % modValue); + assertThat(decoder.readInt()).isEqualTo(i % modValue); + assertThat(decoder.readInt()).isEqualTo(i % modValue); } for (int i = 0; i < 1000; i++) { - assertEquals(17 % modValue, decoder.readInt()); + assertThat(decoder.readInt()).isEqualTo(17 % modValue); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/column/values/rle/TestRunLengthBitPackingHybridEncoder.java b/parquet-column/src/test/java/org/apache/parquet/column/values/rle/TestRunLengthBitPackingHybridEncoder.java index 93a6c8deb4..c3976ea4f7 100644 --- a/parquet-column/src/test/java/org/apache/parquet/column/values/rle/TestRunLengthBitPackingHybridEncoder.java +++ b/parquet-column/src/test/java/org/apache/parquet/column/values/rle/TestRunLengthBitPackingHybridEncoder.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.column.values.rle; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.util.ArrayList; @@ -54,17 +54,17 @@ public void testRLEOnly() throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(encoder.toBytes().toByteArray()); // header = 100 << 1 = 200 - assertEquals(200, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(200); // payload = 4 - assertEquals(4, BytesUtils.readIntLittleEndianOnOneByte(is)); + assertThat(BytesUtils.readIntLittleEndianOnOneByte(is)).isEqualTo(4); // header = 100 << 1 = 200 - assertEquals(200, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(200); // payload = 5 - assertEquals(5, BytesUtils.readIntLittleEndianOnOneByte(is)); + assertThat(BytesUtils.readIntLittleEndianOnOneByte(is)).isEqualTo(5); // end of stream - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -81,12 +81,12 @@ public void testRepeatedZeros() throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(encoder.toBytes().toByteArray()); // header = 10 << 1 = 20 - assertEquals(20, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(20); // payload = 4 - assertEquals(0, BytesUtils.readIntLittleEndianOnOneByte(is)); + assertThat(BytesUtils.readIntLittleEndianOnOneByte(is)).isEqualTo(0); // end of stream - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -99,10 +99,10 @@ public void testBitWidthZero() throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(encoder.toBytes().toByteArray()); // header = 10 << 1 = 20 - assertEquals(20, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(20); // end of stream - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -115,16 +115,16 @@ public void testBitPackingOnly() throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(encoder.toBytes().toByteArray()); // header = ((104/8) << 1) | 1 = 27 - assertEquals(27, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(27); List values = unpack(3, 104, is); for (int i = 0; i < 100; i++) { - assertEquals(i % 3, (int) values.get(i)); + assertThat((int) values.get(i)).isEqualTo(i % 3); } // end of stream - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -140,23 +140,23 @@ public void testBitPackingOverflow() throws Exception { // 504 is the max number of values in a bit packed run // that still has a header of 1 byte // header = ((504/8) << 1) | 1 = 127 - assertEquals(127, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(127); List values = unpack(3, 504, is); for (int i = 0; i < 504; i++) { - assertEquals(i % 3, (int) values.get(i)); + assertThat((int) values.get(i)).isEqualTo(i % 3); } // there should now be 496 values in another bit-packed run // header = ((496/8) << 1) | 1 = 125 - assertEquals(125, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(125); values = unpack(3, 496, is); for (int i = 0; i < 496; i++) { - assertEquals((i + 504) % 3, (int) values.get(i)); + assertThat((int) values.get(i)).isEqualTo((i + 504) % 3); } // end of stream - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -183,18 +183,18 @@ public void testTransitionFromBitPackingToRle() throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(encoder.toBytes().toByteArray()); // header = ((8/8) << 1) | 1 = 3 - assertEquals(3, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(3); List values = unpack(3, 8, is); - assertEquals(List.of(0, 1, 0, 1, 0, 2, 2, 2), values); + assertThat(values).containsExactly(0, 1, 0, 1, 0, 2, 2, 2); // header = 100 << 1 = 200 - assertEquals(200, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(200); // payload = 2 - assertEquals(2, BytesUtils.readIntLittleEndianOnOneByte(is)); + assertThat(BytesUtils.readIntLittleEndianOnOneByte(is)).isEqualTo(2); // end of stream - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -207,13 +207,13 @@ public void testPaddingZerosOnUnfinishedBitPackedRuns() throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(encoder.toBytes().toByteArray()); // header = ((16/8) << 1) | 1 = 5 - assertEquals(5, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(5); List values = unpack(5, 16, is); - assertEquals(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0), values); + assertThat(values).containsExactly(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0); - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -247,40 +247,40 @@ public void testSwitchingModes() throws Exception { ByteArrayInputStream is = new ByteArrayInputStream(encoder.toBytes().toByteArray()); // header = 25 << 1 = 50 - assertEquals(50, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(50); // payload = 17, stored in 2 bytes - assertEquals(17, BytesUtils.readIntLittleEndianOnTwoBytes(is)); + assertThat(BytesUtils.readIntLittleEndianOnTwoBytes(is)).isEqualTo(17); // header = ((16/8) << 1) | 1 = 5 - assertEquals(5, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(5); List values = unpack(9, 16, is); int v = 0; for (int i = 0; i < 7; i++) { - assertEquals(7, (int) values.get(v)); + assertThat((int) values.get(v)).isEqualTo(7); v++; } - assertEquals(8, (int) values.get(v++)); - assertEquals(9, (int) values.get(v++)); - assertEquals(10, (int) values.get(v++)); + assertThat((int) values.get(v++)).isEqualTo(8); + assertThat((int) values.get(v++)).isEqualTo(9); + assertThat((int) values.get(v++)).isEqualTo(10); for (int i = 0; i < 6; i++) { - assertEquals(6, (int) values.get(v)); + assertThat((int) values.get(v)).isEqualTo(6); v++; } // header = 19 << 1 = 38 - assertEquals(38, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(38); // payload = 6, stored in 2 bytes - assertEquals(6, BytesUtils.readIntLittleEndianOnTwoBytes(is)); + assertThat(BytesUtils.readIntLittleEndianOnTwoBytes(is)).isEqualTo(6); // header = 8 << 1 = 16 - assertEquals(16, BytesUtils.readUnsignedVarInt(is)); + assertThat(BytesUtils.readUnsignedVarInt(is)).isEqualTo(16); // payload = 5, stored in 2 bytes - assertEquals(5, BytesUtils.readIntLittleEndianOnTwoBytes(is)); + assertThat(BytesUtils.readIntLittleEndianOnTwoBytes(is)).isEqualTo(5); // end of stream - assertEquals(-1, is.read()); + assertThat(is.read()).isEqualTo(-1); } @Test @@ -292,10 +292,10 @@ public void testGroupBoundary() throws Exception { bytes[1] = (1 << 0) | (2 << 2) | (3 << 4); ByteArrayInputStream stream = new ByteArrayInputStream(bytes); RunLengthBitPackingHybridDecoder decoder = new RunLengthBitPackingHybridDecoder(2, stream); - assertEquals(decoder.readInt(), 1); - assertEquals(decoder.readInt(), 2); - assertEquals(decoder.readInt(), 3); - assertEquals(stream.available(), 0); + assertThat(decoder.readInt()).isEqualTo(1); + assertThat(decoder.readInt()).isEqualTo(2); + assertThat(decoder.readInt()).isEqualTo(3); + assertThat(stream.available()).isEqualTo(0); } private static List unpack(int bitWidth, int numValues, ByteArrayInputStream is) throws Exception { diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/columnindex/TestRowRanges.java b/parquet-column/src/test/java/org/apache/parquet/filter2/columnindex/TestRowRanges.java index 67f65b8702..d30cf77c2a 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/columnindex/TestRowRanges.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/columnindex/TestRowRanges.java @@ -20,14 +20,9 @@ import static org.apache.parquet.filter2.columnindex.RowRanges.intersection; import static org.apache.parquet.filter2.columnindex.RowRanges.union; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -import it.unimi.dsi.fastutil.longs.LongArrayList; -import it.unimi.dsi.fastutil.longs.LongList; -import java.util.Arrays; import java.util.PrimitiveIterator; import org.apache.parquet.internal.column.columnindex.OffsetIndexBuilder; import org.junit.Test; @@ -67,13 +62,6 @@ public int nextInt() { rowIndexes[rowIndexes.length - 1], pageIndexes, builder.build()); } - private static void assertAllRowsEqual(PrimitiveIterator.OfLong actualIt, long... expectedValues) { - LongList actualList = new LongArrayList(); - actualIt.forEachRemaining((long value) -> actualList.add(value)); - assertArrayEquals( - Arrays.toString(expectedValues) + "!= " + actualList, expectedValues, actualList.toLongArray()); - } - @Test public void testCreate() { // Offset-index pages never overlap; consecutive pages are at most adjacent ([6, 7] then [8, 10]), @@ -84,24 +72,24 @@ public void testCreate() { 6, 7, 8, 10, 15, 17); - assertAllRowsEqual(ranges.iterator(), 1, 2, 3, 4, 6, 7, 8, 9, 10, 15, 16, 17); - assertEquals(12, ranges.rowCount()); - assertTrue(ranges.isOverlapping(4, 5)); - assertFalse(ranges.isOverlapping(5, 5)); - assertTrue(ranges.isOverlapping(10, 14)); - assertFalse(ranges.isOverlapping(11, 14)); - assertFalse(ranges.isOverlapping(18, Long.MAX_VALUE)); + assertThat(ranges.iterator()).toIterable().containsExactly(1L, 2L, 3L, 4L, 6L, 7L, 8L, 9L, 10L, 15L, 16L, 17L); + assertThat(ranges.rowCount()).isEqualTo(12); + assertThat(ranges.isOverlapping(4, 5)).isTrue(); + assertThat(ranges.isOverlapping(5, 5)).isFalse(); + assertThat(ranges.isOverlapping(10, 14)).isTrue(); + assertThat(ranges.isOverlapping(11, 14)).isFalse(); + assertThat(ranges.isOverlapping(18, Long.MAX_VALUE)).isFalse(); ranges = RowRanges.createSingle(5); - assertAllRowsEqual(ranges.iterator(), 0, 1, 2, 3, 4); - assertEquals(5, ranges.rowCount()); - assertTrue(ranges.isOverlapping(0, 100)); - assertFalse(ranges.isOverlapping(5, Long.MAX_VALUE)); + assertThat(ranges.iterator()).toIterable().containsExactly(0L, 1L, 2L, 3L, 4L); + assertThat(ranges.rowCount()).isEqualTo(5); + assertThat(ranges.isOverlapping(0, 100)).isTrue(); + assertThat(ranges.isOverlapping(5, Long.MAX_VALUE)).isFalse(); ranges = RowRanges.EMPTY; - assertAllRowsEqual(ranges.iterator()); - assertEquals(0, ranges.rowCount()); - assertFalse(ranges.isOverlapping(0, Long.MAX_VALUE)); + assertThat(ranges.iterator()).toIterable().isEmpty(); + assertThat(ranges.rowCount()).isZero(); + assertThat(ranges.isOverlapping(0, Long.MAX_VALUE)).isFalse(); } @Test @@ -118,17 +106,31 @@ public void testUnion() { 14, 15, 21, 22); RowRanges empty = buildRanges(); - assertAllRowsEqual( - union(ranges1, ranges2).iterator(), 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 14, 15, 20, 21, 22, 23, 24); - assertAllRowsEqual( - union(ranges2, ranges1).iterator(), 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 14, 15, 20, 21, 22, 23, 24); - assertAllRowsEqual(union(ranges1, ranges1).iterator(), 2, 3, 4, 5, 7, 8, 9, 14, 20, 21, 22, 23, 24); - assertAllRowsEqual(union(ranges1, empty).iterator(), 2, 3, 4, 5, 7, 8, 9, 14, 20, 21, 22, 23, 24); - assertAllRowsEqual(union(empty, ranges1).iterator(), 2, 3, 4, 5, 7, 8, 9, 14, 20, 21, 22, 23, 24); - assertAllRowsEqual(union(ranges2, ranges2).iterator(), 1, 2, 4, 5, 11, 12, 14, 15, 21, 22); - assertAllRowsEqual(union(ranges2, empty).iterator(), 1, 2, 4, 5, 11, 12, 14, 15, 21, 22); - assertAllRowsEqual(union(empty, ranges2).iterator(), 1, 2, 4, 5, 11, 12, 14, 15, 21, 22); - assertAllRowsEqual(union(empty, empty).iterator()); + assertThat(union(ranges1, ranges2).iterator()) + .toIterable() + .containsExactly(1L, 2L, 3L, 4L, 5L, 7L, 8L, 9L, 11L, 12L, 14L, 15L, 20L, 21L, 22L, 23L, 24L); + assertThat(union(ranges2, ranges1).iterator()) + .toIterable() + .containsExactly(1L, 2L, 3L, 4L, 5L, 7L, 8L, 9L, 11L, 12L, 14L, 15L, 20L, 21L, 22L, 23L, 24L); + assertThat(union(ranges1, ranges1).iterator()) + .toIterable() + .containsExactly(2L, 3L, 4L, 5L, 7L, 8L, 9L, 14L, 20L, 21L, 22L, 23L, 24L); + assertThat(union(ranges1, empty).iterator()) + .toIterable() + .containsExactly(2L, 3L, 4L, 5L, 7L, 8L, 9L, 14L, 20L, 21L, 22L, 23L, 24L); + assertThat(union(empty, ranges1).iterator()) + .toIterable() + .containsExactly(2L, 3L, 4L, 5L, 7L, 8L, 9L, 14L, 20L, 21L, 22L, 23L, 24L); + assertThat(union(ranges2, ranges2).iterator()) + .toIterable() + .containsExactly(1L, 2L, 4L, 5L, 11L, 12L, 14L, 15L, 21L, 22L); + assertThat(union(ranges2, empty).iterator()) + .toIterable() + .containsExactly(1L, 2L, 4L, 5L, 11L, 12L, 14L, 15L, 21L, 22L); + assertThat(union(empty, ranges2).iterator()) + .toIterable() + .containsExactly(1L, 2L, 4L, 5L, 11L, 12L, 14L, 15L, 21L, 22L); + assertThat(union(empty, empty).iterator()).toIterable().isEmpty(); } @Test @@ -146,15 +148,19 @@ public void testIntersection() { 14, 15, 21, 22); RowRanges empty = buildRanges(); - assertAllRowsEqual(intersection(ranges1, ranges2).iterator(), 2, 7, 9, 14, 21, 22); - assertAllRowsEqual(intersection(ranges2, ranges1).iterator(), 2, 7, 9, 14, 21, 22); - assertAllRowsEqual(intersection(ranges1, ranges1).iterator(), 2, 3, 4, 5, 7, 8, 9, 14, 20, 21, 22, 23, 24); - assertAllRowsEqual(intersection(ranges1, empty).iterator()); - assertAllRowsEqual(intersection(empty, ranges1).iterator()); - assertAllRowsEqual(intersection(ranges2, ranges2).iterator(), 1, 2, 6, 7, 9, 11, 12, 14, 15, 21, 22); - assertAllRowsEqual(intersection(ranges2, empty).iterator()); - assertAllRowsEqual(intersection(empty, ranges2).iterator()); - assertAllRowsEqual(intersection(empty, empty).iterator()); + assertThat(intersection(ranges1, ranges2).iterator()).toIterable().containsExactly(2L, 7L, 9L, 14L, 21L, 22L); + assertThat(intersection(ranges2, ranges1).iterator()).toIterable().containsExactly(2L, 7L, 9L, 14L, 21L, 22L); + assertThat(intersection(ranges1, ranges1).iterator()) + .toIterable() + .containsExactly(2L, 3L, 4L, 5L, 7L, 8L, 9L, 14L, 20L, 21L, 22L, 23L, 24L); + assertThat(intersection(ranges1, empty).iterator()).toIterable().isEmpty(); + assertThat(intersection(empty, ranges1).iterator()).toIterable().isEmpty(); + assertThat(intersection(ranges2, ranges2).iterator()) + .toIterable() + .containsExactly(1L, 2L, 6L, 7L, 9L, 11L, 12L, 14L, 15L, 21L, 22L); + assertThat(intersection(ranges2, empty).iterator()).toIterable().isEmpty(); + assertThat(intersection(empty, ranges2).iterator()).toIterable().isEmpty(); + assertThat(intersection(empty, empty).iterator()).toIterable().isEmpty(); } @Test @@ -166,8 +172,8 @@ public void testBuilderBasic() { .addSelectedRow(4) .addSelectedRow(5) .build(); - assertAllRowsEqual(ranges.iterator(), 2, 3, 4, 5); - assertEquals(4, ranges.rowCount()); + assertThat(ranges.iterator()).toIterable().containsExactly(2L, 3L, 4L, 5L); + assertThat(ranges.rowCount()).isEqualTo(4); } @Test @@ -180,20 +186,20 @@ public void testBuilderMultipleRanges() { .addSelectedRow(6) .addSelectedRow(7) .build(); - assertAllRowsEqual(ranges.iterator(), 1, 2, 5, 6, 7); - assertEquals(5, ranges.rowCount()); - assertTrue(ranges.isOverlapping(1, 2)); - assertTrue(ranges.isOverlapping(5, 7)); - assertFalse(ranges.isOverlapping(3, 4)); + assertThat(ranges.iterator()).toIterable().containsExactly(1L, 2L, 5L, 6L, 7L); + assertThat(ranges.rowCount()).isEqualTo(5); + assertThat(ranges.isOverlapping(1, 2)).isTrue(); + assertThat(ranges.isOverlapping(5, 7)).isTrue(); + assertThat(ranges.isOverlapping(3, 4)).isFalse(); } @Test public void testBuilderEmpty() { // No rows selected RowRanges ranges = RowRanges.builder().build(); - assertEquals(RowRanges.EMPTY, ranges); - assertEquals(0, ranges.rowCount()); - assertAllRowsEqual(ranges.iterator()); + assertThat(ranges).isEqualTo(RowRanges.EMPTY); + assertThat(ranges.rowCount()).isZero(); + assertThat(ranges.iterator()).toIterable().isEmpty(); } @Test @@ -204,18 +210,18 @@ public void testBuilderAllSelected() { builder.addSelectedRow(i); } RowRanges ranges = builder.build(); - assertAllRowsEqual(ranges.iterator(), 0, 1, 2, 3, 4); - assertEquals(5, ranges.rowCount()); + assertThat(ranges.iterator()).toIterable().containsExactly(0L, 1L, 2L, 3L, 4L); + assertThat(ranges.rowCount()).isEqualTo(5); } @Test public void testBuilderSingleRow() { RowRanges ranges = RowRanges.builder().addSelectedRow(3).build(); - assertAllRowsEqual(ranges.iterator(), 3); - assertEquals(1, ranges.rowCount()); - assertTrue(ranges.isOverlapping(3, 3)); - assertFalse(ranges.isOverlapping(0, 2)); - assertFalse(ranges.isOverlapping(4, 10)); + assertThat(ranges.iterator()).toIterable().containsExactly(3L); + assertThat(ranges.rowCount()).isEqualTo(1); + assertThat(ranges.isOverlapping(3, 3)).isTrue(); + assertThat(ranges.isOverlapping(0, 2)).isFalse(); + assertThat(ranges.isOverlapping(4, 10)).isFalse(); } @Test @@ -226,49 +232,40 @@ public void testBuilderAlternating() { builder.addSelectedRow(i); } RowRanges ranges = builder.build(); - assertAllRowsEqual(ranges.iterator(), 0, 2, 4, 6, 8); - assertEquals(5, ranges.rowCount()); + assertThat(ranges.iterator()).toIterable().containsExactly(0L, 2L, 4L, 6L, 8L); + assertThat(ranges.rowCount()).isEqualTo(5); } @Test public void testBuilderFirstAndLast() { RowRanges ranges = RowRanges.builder().addSelectedRow(0).addSelectedRow(99).build(); - assertAllRowsEqual(ranges.iterator(), 0, 99); - assertEquals(2, ranges.rowCount()); + assertThat(ranges.iterator()).toIterable().containsExactly(0L, 99L); + assertThat(ranges.rowCount()).isEqualTo(2); } @Test public void testBuilderRejectsOutOfOrder() { RowRanges.Builder builder = RowRanges.builder().addSelectedRow(5).addSelectedRow(7); - try { - builder.addSelectedRow(6); - org.junit.Assert.fail("expected IllegalArgumentException for out-of-order index"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThatThrownBy(() -> builder.addSelectedRow(6)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("addSelectedRange requires strictly increasing ranges; got [6, 6] after 7"); } @Test public void testBuilderRejectsDuplicate() { RowRanges.Builder builder = RowRanges.builder().addSelectedRow(3); - try { - builder.addSelectedRow(3); - org.junit.Assert.fail("expected IllegalArgumentException for duplicate index"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThatThrownBy(() -> builder.addSelectedRow(3)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("addSelectedRange requires strictly increasing ranges; got [3, 3] after 3"); } @Test public void testBuilderRejectsNegativeRow() { RowRanges.Builder builder = RowRanges.builder(); - try { - builder.addSelectedRow(-1); - org.junit.Assert.fail("expected IllegalArgumentException for negative index"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThatThrownBy(() -> builder.addSelectedRow(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("addSelectedRange requires a non-negative row index; got -1"); } @Test @@ -276,14 +273,11 @@ public void testBuilderRejectsFollowUpAfterMaxValue() { // After Long.MAX_VALUE, runEnd + 1 would overflow; the strictly-increasing guard must still // reject any follow-up index rather than silently starting a new run. RowRanges.Builder builder = RowRanges.builder().addSelectedRow(Long.MAX_VALUE); - try { - builder.addSelectedRow(5); - org.junit.Assert.fail("expected IllegalArgumentException for index after Long.MAX_VALUE"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThatThrownBy(() -> builder.addSelectedRow(5)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("addSelectedRange requires strictly increasing ranges; got [5, 5] after " + Long.MAX_VALUE); // Long.MAX_VALUE alone is a valid single-row selection. - assertAllRowsEqual(builder.build().iterator(), Long.MAX_VALUE); + assertThat(builder.build().iterator()).toIterable().containsExactly(Long.MAX_VALUE); } @Test @@ -293,30 +287,24 @@ public void testBuilderAddSelectedRangeCoalescesAndSeparates() { .addSelectedRange(3, 5) // adjacent to the previous run -> coalesced into [0, 5] .addSelectedRange(8, 9) // gap -> separate run .build(); - assertAllRowsEqual(ranges.iterator(), 0, 1, 2, 3, 4, 5, 8, 9); - assertEquals(8, ranges.rowCount()); + assertThat(ranges.iterator()).toIterable().containsExactly(0L, 1L, 2L, 3L, 4L, 5L, 8L, 9L); + assertThat(ranges.rowCount()).isEqualTo(8); } @Test public void testBuilderAddSelectedRangeRejectsOverlap() { RowRanges.Builder builder = RowRanges.builder().addSelectedRange(0, 10); - try { - builder.addSelectedRange(5, 15); - org.junit.Assert.fail("expected IllegalArgumentException for overlapping range"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThatThrownBy(() -> builder.addSelectedRange(5, 15)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("addSelectedRange requires strictly increasing ranges; got [5, 15] after 10"); } @Test public void testBuilderAddSelectedRangeRejectsFromGreaterThanTo() { RowRanges.Builder builder = RowRanges.builder(); - try { - builder.addSelectedRange(5, 3); - org.junit.Assert.fail("expected IllegalArgumentException for from > to"); - } catch (IllegalArgumentException expected) { - // expected - } + assertThatThrownBy(() -> builder.addSelectedRange(5, 3)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("addSelectedRange requires from <= to; got [5, 3]"); } @Test @@ -325,17 +313,17 @@ public void testBuilderBuildReturnsSnapshot() { // mutate a previously built result. RowRanges.Builder builder = RowRanges.builder().addSelectedRow(0).addSelectedRow(1); RowRanges first = builder.build(); - assertAllRowsEqual(first.iterator(), 0, 1); - assertEquals(2, first.rowCount()); + assertThat(first.iterator()).toIterable().containsExactly(0L, 1L); + assertThat(first.rowCount()).isEqualTo(2); builder.addSelectedRow(5); RowRanges second = builder.build(); // The first result is unchanged. - assertAllRowsEqual(first.iterator(), 0, 1); - assertEquals(2, first.rowCount()); + assertThat(first.iterator()).toIterable().containsExactly(0L, 1L); + assertThat(first.rowCount()).isEqualTo(2); // The second result reflects the additional row. - assertAllRowsEqual(second.iterator(), 0, 1, 5); - assertEquals(3, second.rowCount()); + assertThat(second.iterator()).toIterable().containsExactly(0L, 1L, 5L); + assertThat(second.rowCount()).isEqualTo(3); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestContainsRewriter.java b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestContainsRewriter.java index 5daa5d79b8..51b188106b 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestContainsRewriter.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestContainsRewriter.java @@ -31,7 +31,7 @@ import static org.apache.parquet.filter2.predicate.FilterApi.notEq; import static org.apache.parquet.filter2.predicate.FilterApi.or; import static org.apache.parquet.filter2.predicate.FilterApi.userDefined; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.filter2.predicate.Operators.Contains; import org.apache.parquet.filter2.predicate.Operators.DoubleColumn; @@ -44,7 +44,7 @@ public class TestContainsRewriter { private static final DoubleColumn doubleColumn = doubleColumn("a.b.c"); private static void assertNoOp(FilterPredicate p) { - assertEquals(p, rewrite(p)); + assertThat(rewrite(p)).isEqualTo(p); } @Test @@ -65,8 +65,8 @@ public void testBaseCases() { Contains containsRhs = contains(eq(intColumn, 7)); assertNoOp(containsLhs); - assertEquals(containsLhs.and(containsRhs), rewrite(and(containsLhs, containsRhs))); - assertEquals(containsLhs.or(containsRhs), rewrite(or(containsLhs, containsRhs))); + assertThat(rewrite(and(containsLhs, containsRhs))).isEqualTo(containsLhs.and(containsRhs)); + assertThat(rewrite(or(containsLhs, containsRhs))).isEqualTo(containsLhs.or(containsRhs)); } @Test @@ -76,14 +76,13 @@ public void testNested() { Contains contains3 = contains(eq(intColumn, 3)); Contains contains4 = contains(eq(intColumn, 4)); - assertEquals(contains1.and(contains2.or(contains3)), rewrite(and(contains1, or(contains2, contains3)))); - assertEquals(contains1.and(contains2).or(contains3), rewrite(or(and(contains1, contains2), contains3))); + assertThat(rewrite(and(contains1, or(contains2, contains3)))).isEqualTo(contains1.and(contains2.or(contains3))); + assertThat(rewrite(or(and(contains1, contains2), contains3))) + .isEqualTo(contains1.and(contains2).or(contains3)); - assertEquals( - contains1.and(contains2).and(contains2.or(contains3)), - rewrite(and(and(contains1, contains2), or(contains2, contains3)))); - assertEquals( - contains1.and(contains2).or(contains3.or(contains4)), - rewrite(or(and(contains1, contains2), or(contains3, contains4)))); + assertThat(rewrite(and(and(contains1, contains2), or(contains2, contains3)))) + .isEqualTo(contains1.and(contains2).and(contains2.or(contains3))); + assertThat(rewrite(or(and(contains1, contains2), or(contains3, contains4)))) + .isEqualTo(contains1.and(contains2).or(contains3.or(contains4))); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestFilterApiMethods.java b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestFilterApiMethods.java index 9bb180087b..40585c4064 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestFilterApiMethods.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestFilterApiMethods.java @@ -31,9 +31,8 @@ import static org.apache.parquet.filter2.predicate.FilterApi.or; import static org.apache.parquet.filter2.predicate.FilterApi.userDefined; import static org.apache.parquet.filter2.predicate.Operators.NotEq; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -69,44 +68,41 @@ public class TestFilterApiMethods { public void testFilterPredicateCreation() { FilterPredicate outerAnd = predicate; - assertTrue(outerAnd instanceof And); + assertThat(outerAnd).isInstanceOf(And.class); FilterPredicate not = ((And) outerAnd).getLeft(); FilterPredicate gt = ((And) outerAnd).getRight(); - assertTrue(not instanceof Not); + assertThat(not).isInstanceOf(Not.class); FilterPredicate or = ((Not) not).getPredicate(); - assertTrue(or instanceof Or); + assertThat(or).isInstanceOf(Or.class); FilterPredicate leftEq = ((Or) or).getLeft(); FilterPredicate rightNotEq = ((Or) or).getRight(); - assertTrue(leftEq instanceof Eq); - assertTrue(rightNotEq instanceof NotEq); - assertEquals(7, ((Eq) leftEq).getValue()); - assertEquals(17, ((NotEq) rightNotEq).getValue()); - assertEquals(ColumnPath.get("a", "b", "c"), ((Eq) leftEq).getColumn().getColumnPath()); - assertEquals( - ColumnPath.get("a", "b", "c"), ((NotEq) rightNotEq).getColumn().getColumnPath()); - - assertTrue(gt instanceof Gt); - assertEquals(100.0, ((Gt) gt).getValue()); - assertEquals(ColumnPath.get("x", "y", "z"), ((Gt) gt).getColumn().getColumnPath()); + assertThat(leftEq).isInstanceOf(Eq.class); + assertThat(rightNotEq).isInstanceOf(NotEq.class); + assertThat(((Eq) leftEq).getValue()).isEqualTo(7); + assertThat(((NotEq) rightNotEq).getValue()).isEqualTo(17); + assertThat(((Eq) leftEq).getColumn().getColumnPath()).isEqualTo(ColumnPath.get("a", "b", "c")); + assertThat(((NotEq) rightNotEq).getColumn().getColumnPath()).isEqualTo(ColumnPath.get("a", "b", "c")); + + assertThat(gt).isInstanceOf(Gt.class); + assertThat(((Gt) gt).getValue()).isEqualTo(100.0); + assertThat(((Gt) gt).getColumn().getColumnPath()).isEqualTo(ColumnPath.get("x", "y", "z")); } @Test public void testContainsCreation() { - assertThrows( - "Contains predicate does not support null element value", - IllegalArgumentException.class, - () -> contains(eq(binColumn, null))); + assertThatThrownBy(() -> contains(eq(binColumn, null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Contains predicate does not support null element value(s)"); // Assert that a single Contains predicate referencing multiple columns throws an error - assertThrows( - "Composed Contains predicates must reference the same column name; found [a.b.c, b.c.d]", - IllegalArgumentException.class, - () -> contains(eq(binaryColumn("a.b.c"), Binary.fromString("foo"))) + assertThatThrownBy(() -> contains(eq(binaryColumn("a.b.c"), Binary.fromString("foo"))) .and(contains(eq(binaryColumn("b.c.d"), Binary.fromString("bar")))) - .and(contains(eq(binaryColumn("b.c.d"), Binary.fromString("bar"))))); + .and(contains(eq(binaryColumn("b.c.d"), Binary.fromString("bar"))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Composed Contains predicates must reference the same column name; found [a.b.c, b.c.d]"); // Assert that a Contains predicate referencing multiple columns is allowed when composed with and() or or() final FilterPredicate rewritten = ContainsRewriter.rewrite(or( @@ -114,41 +110,42 @@ public void testContainsCreation() { and( contains(eq(binaryColumn("b.c.d"), Binary.fromString("bar"))), contains(eq(binaryColumn("b.c.d"), Binary.fromString("baz")))))); - assertTrue(rewritten instanceof Or); + assertThat(rewritten).isInstanceOf(Or.class); // Assert that the predicates for column b.c.d have been combined into a single Contains predicate, // while the predicate for column a.b.c is separate final Or or = (Or) rewritten; - assertEquals(binaryColumn("a.b.c"), ((Operators.Contains) or.getLeft()).getColumn()); - assertEquals(binaryColumn("b.c.d"), ((Operators.Contains) or.getRight()).getColumn()); + assertThat(((Operators.Contains) or.getLeft()).getColumn()).isEqualTo(binaryColumn("a.b.c")); + assertThat(((Operators.Contains) or.getRight()).getColumn()).isEqualTo(binaryColumn("b.c.d")); } @Test public void testToString() { FilterPredicate pred = or(predicate, notEq(binColumn, Binary.fromString("foobarbaz"))); - assertEquals( - "or(and(not(or(eq(a.b.c, 7), noteq(a.b.c, 17))), gt(x.y.z, 100.0)), " - + "noteq(a.string.column, Binary{\"foobarbaz\"}))", - pred.toString()); + assertThat(pred) + .asString() + .isEqualTo("or(and(not(or(eq(a.b.c, 7), noteq(a.b.c, 17))), gt(x.y.z, 100.0)), " + + "noteq(a.string.column, Binary{\"foobarbaz\"}))"); pred = ContainsRewriter.rewrite(or( contains(eq(binColumn, Binary.fromString("foo"))), and( contains(eq(binColumn, Binary.fromString("bar"))), not(contains(eq(binColumn, Binary.fromString("baz"))))))); - assertEquals( - "or(contains(eq(a.string.column, Binary{\"foo\"})), and(contains(eq(a.string.column, Binary{\"bar\"})), not(contains(eq(a.string.column, Binary{\"baz\"})))))", - pred.toString()); + assertThat(pred) + .asString() + .isEqualTo( + "or(contains(eq(a.string.column, Binary{\"foo\"})), and(contains(eq(a.string.column, Binary{\"bar\"})), not(contains(eq(a.string.column, Binary{\"baz\"})))))"); } @Test public void testUdp() { FilterPredicate predicate = or(eq(doubleColumn, 12.0), userDefined(intColumn, DummyUdp.class)); - assertTrue(predicate instanceof Or); + assertThat(predicate).isInstanceOf(Or.class); FilterPredicate ud = ((Or) predicate).getRight(); - assertTrue(ud instanceof UserDefinedByClass); - assertEquals(DummyUdp.class, ((UserDefinedByClass) ud).getUserDefinedPredicateClass()); - assertTrue(((UserDefined) ud).getUserDefinedPredicate() instanceof DummyUdp); + assertThat(ud).isInstanceOf(UserDefinedByClass.class); + assertThat(((UserDefinedByClass) ud).getUserDefinedPredicateClass()).isEqualTo(DummyUdp.class); + assertThat(((UserDefined) ud).getUserDefinedPredicate()).isInstanceOf(DummyUdp.class); } @Test @@ -164,7 +161,7 @@ public void testSerializable() throws Exception { ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); FilterPredicate read = (FilterPredicate) is.readObject(); - assertEquals(p, read); + assertThat(read).isEqualTo(p); } public static class IsMultipleOf extends UserDefinedPredicate implements Serializable { diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverseRewriter.java b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverseRewriter.java index 7f085de138..b7f8d968d5 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverseRewriter.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverseRewriter.java @@ -31,7 +31,7 @@ import static org.apache.parquet.filter2.predicate.FilterApi.or; import static org.apache.parquet.filter2.predicate.FilterApi.userDefined; import static org.apache.parquet.filter2.predicate.LogicalInverseRewriter.rewrite; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.filter2.predicate.Operators.DoubleColumn; import org.apache.parquet.filter2.predicate.Operators.IntColumn; @@ -58,7 +58,7 @@ public class TestLogicalInverseRewriter { or(gt(doubleColumn, 100.0), lt(intColumn, 77))); private static void assertNoOp(FilterPredicate p) { - assertEquals(p, rewrite(p)); + assertThat(rewrite(p)).isEqualTo(p); } @Test @@ -75,25 +75,25 @@ public void testBaseCases() { assertNoOp(or(eq(intColumn, 17), eq(doubleColumn, 12.0))); assertNoOp(ud); - assertEquals(notEq(intColumn, 17), rewrite(not(eq(intColumn, 17)))); - assertEquals(eq(intColumn, 17), rewrite(not(notEq(intColumn, 17)))); - assertEquals(gtEq(intColumn, 17), rewrite(not(lt(intColumn, 17)))); - assertEquals(gt(intColumn, 17), rewrite(not(ltEq(intColumn, 17)))); - assertEquals(ltEq(intColumn, 17), rewrite(not(gt(intColumn, 17)))); - assertEquals(lt(intColumn, 17), rewrite(not(gtEq(intColumn, 17)))); - assertEquals(new LogicalNotUserDefined<>(ud), rewrite(not(ud))); + assertThat(rewrite(not(eq(intColumn, 17)))).isEqualTo(notEq(intColumn, 17)); + assertThat(rewrite(not(notEq(intColumn, 17)))).isEqualTo(eq(intColumn, 17)); + assertThat(rewrite(not(lt(intColumn, 17)))).isEqualTo(gtEq(intColumn, 17)); + assertThat(rewrite(not(ltEq(intColumn, 17)))).isEqualTo(gt(intColumn, 17)); + assertThat(rewrite(not(gt(intColumn, 17)))).isEqualTo(ltEq(intColumn, 17)); + assertThat(rewrite(not(gtEq(intColumn, 17)))).isEqualTo(lt(intColumn, 17)); + assertThat(rewrite(not(ud))).isEqualTo(new LogicalNotUserDefined<>(ud)); FilterPredicate notedAnd = not(and(eq(intColumn, 17), eq(doubleColumn, 12.0))); FilterPredicate distributedAnd = or(notEq(intColumn, 17), notEq(doubleColumn, 12.0)); - assertEquals(distributedAnd, rewrite(notedAnd)); + assertThat(rewrite(notedAnd)).isEqualTo(distributedAnd); FilterPredicate andWithNots = and(not(gtEq(intColumn, 17)), lt(intColumn, 7)); FilterPredicate andWithoutNots = and(lt(intColumn, 17), lt(intColumn, 7)); - assertEquals(andWithoutNots, rewrite(andWithNots)); + assertThat(rewrite(andWithNots)).isEqualTo(andWithoutNots); } @Test public void testComplex() { - assertEquals(complexCollapsed, rewrite(complex)); + assertThat(rewrite(complex)).isEqualTo(complexCollapsed); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverter.java b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverter.java index 6a7f81a6c2..56e7a5db0d 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverter.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestLogicalInverter.java @@ -31,7 +31,7 @@ import static org.apache.parquet.filter2.predicate.FilterApi.or; import static org.apache.parquet.filter2.predicate.FilterApi.userDefined; import static org.apache.parquet.filter2.predicate.LogicalInverter.invert; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.filter2.predicate.Operators.DoubleColumn; import org.apache.parquet.filter2.predicate.Operators.IntColumn; @@ -61,31 +61,31 @@ public class TestLogicalInverter { @Test public void testBaseCases() { - assertEquals(notEq(intColumn, 17), invert(eq(intColumn, 17))); - assertEquals(eq(intColumn, 17), invert(notEq(intColumn, 17))); - assertEquals(gtEq(intColumn, 17), invert(lt(intColumn, 17))); - assertEquals(gt(intColumn, 17), invert(ltEq(intColumn, 17))); - assertEquals(ltEq(intColumn, 17), invert(gt(intColumn, 17))); - assertEquals(lt(intColumn, 17), invert(gtEq(intColumn, 17))); + assertThat(invert(eq(intColumn, 17))).isEqualTo(notEq(intColumn, 17)); + assertThat(invert(notEq(intColumn, 17))).isEqualTo(eq(intColumn, 17)); + assertThat(invert(lt(intColumn, 17))).isEqualTo(gtEq(intColumn, 17)); + assertThat(invert(ltEq(intColumn, 17))).isEqualTo(gt(intColumn, 17)); + assertThat(invert(gt(intColumn, 17))).isEqualTo(ltEq(intColumn, 17)); + assertThat(invert(gtEq(intColumn, 17))).isEqualTo(lt(intColumn, 17)); FilterPredicate andPos = and(eq(intColumn, 17), eq(doubleColumn, 12.0)); FilterPredicate andInv = or(notEq(intColumn, 17), notEq(doubleColumn, 12.0)); - assertEquals(andInv, invert(andPos)); + assertThat(invert(andPos)).isEqualTo(andInv); FilterPredicate orPos = or(eq(intColumn, 17), eq(doubleColumn, 12.0)); FilterPredicate orInv = and(notEq(intColumn, 17), notEq(doubleColumn, 12.0)); - assertEquals(orPos, invert(orInv)); + assertThat(invert(orInv)).isEqualTo(orPos); - assertEquals(eq(intColumn, 17), invert(not(eq(intColumn, 17)))); + assertThat(invert(not(eq(intColumn, 17)))).isEqualTo(eq(intColumn, 17)); UserDefined ud = userDefined(intColumn, DummyUdp.class); - assertEquals(new LogicalNotUserDefined<>(ud), invert(ud)); - assertEquals(ud, invert(not(ud))); - assertEquals(ud, invert(new LogicalNotUserDefined<>(ud))); + assertThat(invert(ud)).isEqualTo(new LogicalNotUserDefined<>(ud)); + assertThat(invert(not(ud))).isEqualTo(ud); + assertThat(invert(new LogicalNotUserDefined<>(ud))).isEqualTo(ud); } @Test public void testComplex() { - assertEquals(complexInverse, invert(complex)); + assertThat(invert(complex)).isEqualTo(complexInverse); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestSchemaCompatibilityValidator.java b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestSchemaCompatibilityValidator.java index 47e9bdd5e6..cfbf90caab 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestSchemaCompatibilityValidator.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestSchemaCompatibilityValidator.java @@ -31,8 +31,8 @@ import static org.apache.parquet.filter2.predicate.FilterApi.or; import static org.apache.parquet.filter2.predicate.FilterApi.userDefined; import static org.apache.parquet.filter2.predicate.SchemaCompatibilityValidator.validate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.apache.parquet.filter2.predicate.Operators.BinaryColumn; import org.apache.parquet.filter2.predicate.Operators.IntColumn; @@ -100,64 +100,47 @@ public void testValidType() { @Test public void testFindsInvalidTypes() { - try { - validate(complexWrongType, schema); - fail("this should throw"); - } catch (IllegalArgumentException e) { - assertEquals( - "FilterPredicate column: x.bar's declared type (java.lang.Long) does not match the schema found in file metadata. " - + "Column x.bar is of type: INT32\n" - + "Valid types for this column are: [class java.lang.Integer]", - e.getMessage()); - } + assertThatThrownBy(() -> validate(complexWrongType, schema)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "FilterPredicate column: x.bar's declared type (java.lang.Long) does not match the schema found in file metadata. " + + "Column x.bar is of type: INT32\n" + + "Valid types for this column are: [class java.lang.Integer]"); } @Test public void testTwiceDeclaredColumn() { validate(eq(stringC, Binary.fromString("larry")), schema); - try { - validate(complexMixedType, schema); - fail("this should throw"); - } catch (IllegalArgumentException e) { - assertEquals( - "Column: x.bar was provided with different types in the same predicate. Found both: (class java.lang.Integer, class java.lang.Long)", - e.getMessage()); - } + assertThatThrownBy(() -> validate(complexMixedType, schema)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "Column: x.bar was provided with different types in the same predicate. Found both: (class java.lang.Integer, class java.lang.Long)"); } @Test public void testRepeatedNotSupportedForPrimitivePredicates() { - try { - validate(eq(lotsOfLongs, 10l), schema); - fail("this should throw"); - } catch (IllegalArgumentException e) { - assertEquals( - "FilterPredicates do not currently support repeated columns. Column lotsOfLongs is repeated.", - e.getMessage()); - } + assertThatThrownBy(() -> validate(eq(lotsOfLongs, 10l), schema)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "FilterPredicates do not currently support repeated columns. Column lotsOfLongs is repeated."); } @Test public void testRepeatedSupportedForContainsPredicates() { - try { - validate(contains(eq(lotsOfLongs, 10L)), schema); - validate(and(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); - validate(or(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); - } catch (IllegalArgumentException e) { - fail("Valid repeated column predicates should not throw exceptions"); - } + assertThatCode(() -> { + validate(contains(eq(lotsOfLongs, 10L)), schema); + validate(and(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); + validate(or(contains(eq(lotsOfLongs, 10L)), contains(eq(lotsOfLongs, 5l))), schema); + }) + .doesNotThrowAnyException(); } @Test public void testNonRepeatedNotSupportedForContainsPredicates() { - try { - validate(contains(eq(longBar, 10L)), schema); - fail("Non-repeated field " + longBar + " should fail to validate a containsEq() predicate"); - } catch (IllegalArgumentException e) { - assertEquals( - "FilterPredicate for column x.bar requires a repeated schema, but found max repetition level 0", - e.getMessage()); - } + assertThatThrownBy(() -> validate(contains(eq(longBar, 10L)), schema)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "FilterPredicate for column x.bar requires a repeated schema, but found max repetition level 0"); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestValidTypeMap.java b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestValidTypeMap.java index 5e44e09f62..b56c1cc6f2 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestValidTypeMap.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/predicate/TestValidTypeMap.java @@ -25,8 +25,7 @@ import static org.apache.parquet.filter2.predicate.FilterApi.intColumn; import static org.apache.parquet.filter2.predicate.FilterApi.longColumn; import static org.apache.parquet.filter2.predicate.ValidTypeMap.assertTypeValid; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.apache.parquet.filter2.predicate.Operators.BinaryColumn; import org.apache.parquet.filter2.predicate.Operators.BooleanColumn; @@ -71,30 +70,20 @@ public void testValidTypes() { @Test public void testMismatchedTypes() { - try { - assertTypeValid(intColumn, PrimitiveTypeName.DOUBLE); - fail("This should throw!"); - } catch (IllegalArgumentException e) { - assertEquals( - "FilterPredicate column: int.column's declared type (java.lang.Integer) does not match the " - + "schema found in file metadata. Column int.column is of type: " - + "DOUBLE\n" - + "Valid types for this column are: [class java.lang.Double]", - e.getMessage()); - } + assertThatThrownBy(() -> assertTypeValid(intColumn, PrimitiveTypeName.DOUBLE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "FilterPredicate column: int.column's declared type (java.lang.Integer) does not match the schema found in file metadata. " + + "Column int.column is of type: DOUBLE\n" + + "Valid types for this column are: [class java.lang.Double]"); } @Test public void testUnsupportedType() { - try { - assertTypeValid(invalidColumn, PrimitiveTypeName.INT32); - fail("This should throw!"); - } catch (IllegalArgumentException e) { - assertEquals( - "Column invalid.column was declared as type: " - + "org.apache.parquet.filter2.predicate.TestValidTypeMap$InvalidColumnType which is not supported " - + "in FilterPredicates. Supported types for this column are: [class java.lang.Integer]", - e.getMessage()); - } + assertThatThrownBy(() -> assertTypeValid(invalidColumn, PrimitiveTypeName.INT32)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Column invalid.column was declared as type: " + + "org.apache.parquet.filter2.predicate.TestValidTypeMap$InvalidColumnType which is not supported in FilterPredicates." + + " Supported types for this column are: [class java.lang.Integer]"); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateEvaluator.java b/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateEvaluator.java index 5fede737cb..680763a310 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateEvaluator.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateEvaluator.java @@ -19,10 +19,8 @@ package org.apache.parquet.filter2.recordlevel; import static org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicateEvaluator.evaluate; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate.And; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate.Or; @@ -84,44 +82,44 @@ public void testValueInspector() { // known, and set to false criteria, null considered false ValueInspector v = intIsEven(); v.update(11); - assertFalse(evaluate(v)); + assertThat(evaluate(v)).isFalse(); v.reset(); // known and set to true criteria, null considered false v.update(12); - assertTrue(evaluate(v)); + assertThat(evaluate(v)).isTrue(); v.reset(); // known and set to null, null considered false v.updateNull(); - assertFalse(evaluate(v)); + assertThat(evaluate(v)).isFalse(); v.reset(); // known, and set to false criteria, null considered true ValueInspector intIsNull = intIsNull(); intIsNull.update(10); - assertFalse(evaluate(intIsNull)); + assertThat(evaluate(intIsNull)).isFalse(); intIsNull.reset(); // known, and set to false criteria, null considered true intIsNull.updateNull(); - assertTrue(evaluate(intIsNull)); + assertThat(evaluate(intIsNull)).isTrue(); intIsNull.reset(); // unknown, null considered false v.reset(); - assertFalse(evaluate(v)); + assertThat(evaluate(v)).isFalse(); // unknown, null considered true intIsNull.reset(); - assertTrue(evaluate(intIsNull)); + assertThat(evaluate(intIsNull)).isTrue(); } private void doOrTest(ValueInspector v1, ValueInspector v2, int v1Value, int v2Value, boolean expected) { v1.update(v1Value); v2.update(v2Value); IncrementallyUpdatedFilterPredicate or = new Or(v1, v2); - assertEquals(expected, evaluate(or)); + assertThat(evaluate(or)).isEqualTo(expected); v1.reset(); v2.reset(); } @@ -130,7 +128,7 @@ private void doAndTest(ValueInspector v1, ValueInspector v2, int v1Value, int v2 v1.update(v1Value); v2.update(v2Value); IncrementallyUpdatedFilterPredicate and = new And(v1, v2); - assertEquals(expected, evaluate(and)); + assertThat(evaluate(and)).isEqualTo(expected); v1.reset(); v2.reset(); } @@ -180,24 +178,21 @@ public boolean accept(Visitor visitor) { } }; - try { - evaluate(neverCalled); - fail("this should throw"); - } catch (ShortCircuitException e) { - // - } + assertThatThrownBy(() -> evaluate(neverCalled)) + .isInstanceOf(ShortCircuitException.class) + .hasMessage("this was supposed to short circuit and never get here!"); // T || X should evaluate to true without inspecting X ValueInspector v = intIsEven(); v.update(10); IncrementallyUpdatedFilterPredicate or = new Or(v, neverCalled); - assertTrue(evaluate(or)); + assertThat(evaluate(or)).isTrue(); v.reset(); // F && X should evaluate to false without inspecting X v.update(11); IncrementallyUpdatedFilterPredicate and = new And(v, neverCalled); - assertFalse(evaluate(and)); + assertThat(evaluate(and)).isFalse(); v.reset(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateResetter.java b/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateResetter.java index 9bb3049170..28258ce9ac 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateResetter.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestIncrementallyUpdatedFilterPredicateResetter.java @@ -21,8 +21,7 @@ import static org.apache.parquet.filter2.recordlevel.TestIncrementallyUpdatedFilterPredicateEvaluator.doubleMoreThan10; import static org.apache.parquet.filter2.recordlevel.TestIncrementallyUpdatedFilterPredicateEvaluator.intIsEven; import static org.apache.parquet.filter2.recordlevel.TestIncrementallyUpdatedFilterPredicateEvaluator.intIsNull; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate.And; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate.Or; @@ -43,24 +42,24 @@ public void testReset() { intIsEven.update(11); doubleMoreThan10.update(20.0D); - assertTrue(intIsNull.isKnown()); - assertTrue(intIsEven.isKnown()); - assertTrue(doubleMoreThan10.isKnown()); + assertThat(intIsNull.isKnown()).isTrue(); + assertThat(intIsEven.isKnown()).isTrue(); + assertThat(doubleMoreThan10.isKnown()).isTrue(); IncrementallyUpdatedFilterPredicateResetter.reset(pred); - assertFalse(intIsNull.isKnown()); - assertFalse(intIsEven.isKnown()); - assertFalse(doubleMoreThan10.isKnown()); + assertThat(intIsNull.isKnown()).isFalse(); + assertThat(intIsEven.isKnown()).isFalse(); + assertThat(doubleMoreThan10.isKnown()).isFalse(); intIsNull.updateNull(); - assertTrue(intIsNull.isKnown()); - assertFalse(intIsEven.isKnown()); - assertFalse(doubleMoreThan10.isKnown()); + assertThat(intIsNull.isKnown()).isTrue(); + assertThat(intIsEven.isKnown()).isFalse(); + assertThat(doubleMoreThan10.isKnown()).isFalse(); IncrementallyUpdatedFilterPredicateResetter.reset(pred); - assertFalse(intIsNull.isKnown()); - assertFalse(intIsEven.isKnown()); - assertFalse(doubleMoreThan10.isKnown()); + assertThat(intIsNull.isKnown()).isFalse(); + assertThat(intIsEven.isKnown()).isFalse(); + assertThat(doubleMoreThan10.isKnown()).isFalse(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestValueInspector.java b/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestValueInspector.java index e0c55c2764..81e59a9770 100644 --- a/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestValueInspector.java +++ b/parquet-column/src/test/java/org/apache/parquet/filter2/recordlevel/TestValueInspector.java @@ -19,10 +19,8 @@ package org.apache.parquet.filter2.recordlevel; import static org.apache.parquet.filter2.recordlevel.TestIncrementallyUpdatedFilterPredicateEvaluator.intIsEven; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.List; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate.ValueInspector; @@ -35,49 +33,38 @@ public void testLifeCycle() { ValueInspector v = intIsEven(); // begins in unknown state - assertFalse(v.isKnown()); + assertThat(v.isKnown()).isFalse(); // calling getResult in unknown state throws - try { - v.getResult(); - fail("this should throw"); - } catch (IllegalStateException e) { - assertEquals("getResult() called on a ValueInspector whose result is not yet known!", e.getMessage()); - } + assertThatThrownBy(() -> v.getResult()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("getResult() called on a ValueInspector whose result is not yet known!"); // update state to known v.update(10); // v was updated with value 10, so result is known and should be true - assertTrue(v.isKnown()); - assertTrue(v.getResult()); + assertThat(v.isKnown()).isTrue(); + assertThat(v.getResult()).isTrue(); // calling update w/o resetting should throw - try { - v.update(11); - fail("this should throw"); - } catch (IllegalStateException e) { - assertEquals( - "setResult() called on a ValueInspector whose result is already known!" - + " Did you forget to call reset()?", - e.getMessage()); - } + assertThatThrownBy(() -> v.update(11)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("setResult() called on a ValueInspector whose result is already known!" + + " Did you forget to call reset()?"); // back to unknown state v.reset(); - assertFalse(v.isKnown()); + assertThat(v.isKnown()).isFalse(); // calling getResult in unknown state throws - try { - v.getResult(); - fail("this should throw"); - } catch (IllegalStateException e) { - assertEquals("getResult() called on a ValueInspector whose result is not yet known!", e.getMessage()); - } + assertThatThrownBy(() -> v.getResult()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("getResult() called on a ValueInspector whose result is not yet known!"); // v was updated with value 11, so result is known and should be false v.update(11); - assertTrue(v.isKnown()); - assertFalse(v.getResult()); + assertThat(v.isKnown()).isTrue(); + assertThat(v.getResult()).isFalse(); } @Test @@ -87,7 +74,7 @@ public void testReusable() { for (Integer x : values) { v.update(x); - assertEquals(x % 2 == 0, v.getResult()); + assertThat(v.getResult()).isEqualTo(x % 2 == 0); v.reset(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBinaryTruncator.java b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBinaryTruncator.java index 8d85f3b84f..ce6b42138d 100644 --- a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBinaryTruncator.java +++ b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBinaryTruncator.java @@ -27,10 +27,7 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.BINARY; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT96; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; @@ -72,12 +69,10 @@ public class TestBinaryTruncator { public void testNonStringTruncate() { BinaryTruncator truncator = BinaryTruncator.getTruncator( Types.required(BINARY).as(DECIMAL).precision(10).scale(2).named("test_binary_decimal")); - assertEquals( - binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA), - truncator.truncateMin(binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA), 2)); - assertEquals( - binary(0x01, 0x02, 0x03, 0x04, 0x05, 0x06), - truncator.truncateMax(binary(0x01, 0x02, 0x03, 0x04, 0x05, 0x06), 2)); + assertThat(truncator.truncateMin(binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA), 2)) + .isEqualTo(binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA)); + assertThat(truncator.truncateMax(binary(0x01, 0x02, 0x03, 0x04, 0x05, 0x06), 2)) + .isEqualTo(binary(0x01, 0x02, 0x03, 0x04, 0x05, 0x06)); } @Test @@ -102,49 +97,47 @@ public void testStringTruncate() { BinaryTruncator.getTruncator(Types.required(BINARY).as(UTF8).named("test_utf8")); // Truncate 1 byte characters - assertEquals(Binary.fromString("abc"), truncator.truncateMin(Binary.fromString("abcdef"), 3)); - assertEquals(Binary.fromString("abd"), truncator.truncateMax(Binary.fromString("abcdef"), 3)); + assertThat(truncator.truncateMin(Binary.fromString("abcdef"), 3)).isEqualTo(Binary.fromString("abc")); + assertThat(truncator.truncateMax(Binary.fromString("abcdef"), 3)).isEqualTo(Binary.fromString("abd")); // Truncate 1-2 bytes characters; the target length is "inside" a UTF-8 character - assertEquals(Binary.fromString("árvízt"), truncator.truncateMin(Binary.fromString("árvíztűrő"), 9)); - assertEquals(Binary.fromString("árvízu"), truncator.truncateMax(Binary.fromString("árvíztűrő"), 9)); + assertThat(truncator.truncateMin(Binary.fromString("árvíztűrő"), 9)).isEqualTo(Binary.fromString("árvízt")); + assertThat(truncator.truncateMax(Binary.fromString("árvíztűrő"), 9)).isEqualTo(Binary.fromString("árvízu")); // Truncate highest UTF-8 values -> unable to increment - assertEquals( - Binary.fromString(UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR), - truncator.truncateMin( + assertThat(truncator.truncateMin( Binary.fromString(UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR + UTF8_3BYTES_MAX_CHAR + UTF8_4BYTES_MAX_CHAR), - 5)); - assertEquals( - Binary.fromString( - UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR + UTF8_3BYTES_MAX_CHAR + UTF8_4BYTES_MAX_CHAR), - truncator.truncateMax( + 5)) + .isEqualTo(Binary.fromString(UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR)); + assertThat(truncator.truncateMax( Binary.fromString(UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR + UTF8_3BYTES_MAX_CHAR + UTF8_4BYTES_MAX_CHAR), - 5)); + 5)) + .isEqualTo(Binary.fromString( + UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR + UTF8_3BYTES_MAX_CHAR + UTF8_4BYTES_MAX_CHAR)); // Truncate highest UTF-8 values at the end -> increment the first possible character - assertEquals( - Binary.fromString(UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR + "b" + UTF8_3BYTES_MAX_CHAR), - truncator.truncateMax( + assertThat(truncator.truncateMax( Binary.fromString(UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR + "a" + UTF8_3BYTES_MAX_CHAR + UTF8_4BYTES_MAX_CHAR), - 10)); + 10)) + .isEqualTo(Binary.fromString(UTF8_1BYTE_MAX_CHAR + UTF8_2BYTES_MAX_CHAR + "b" + UTF8_3BYTES_MAX_CHAR)); // Truncate invalid UTF-8 values -> truncate without validity check - assertEquals(binary(0xFF, 0xFE, 0xFD), truncator.truncateMin(binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA), 3)); - assertEquals(binary(0xFF, 0xFE, 0xFE), truncator.truncateMax(binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA), 3)); - assertEquals( - binary(0xFF, 0xFE, 0xFE, 0x00, 0x00), - truncator.truncateMax(binary(0xFF, 0xFE, 0xFD, 0xFF, 0xFF, 0xFF), 5)); + assertThat(truncator.truncateMin(binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA), 3)) + .isEqualTo(binary(0xFF, 0xFE, 0xFD)); + assertThat(truncator.truncateMax(binary(0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA), 3)) + .isEqualTo(binary(0xFF, 0xFE, 0xFE)); + assertThat(truncator.truncateMax(binary(0xFF, 0xFE, 0xFD, 0xFF, 0xFF, 0xFF), 5)) + .isEqualTo(binary(0xFF, 0xFE, 0xFE, 0x00, 0x00)); } @Test @@ -217,10 +210,12 @@ private void checkContract( int length = value.length(); // Edge cases: returning the original value if no truncation is required - assertSame(value, truncator.truncateMin(value, length)); - assertSame(value, truncator.truncateMax(value, length)); - assertSame(value, truncator.truncateMin(value, random(length + 1, length * 2 + 1))); - assertSame(value, truncator.truncateMax(value, random(length + 1, length * 2 + 1))); + assertThat(truncator.truncateMin(value, length)).isSameAs(value); + assertThat(truncator.truncateMax(value, length)).isSameAs(value); + assertThat(truncator.truncateMin(value, random(length + 1, length * 2 + 1))) + .isSameAs(value); + assertThat(truncator.truncateMax(value, random(length + 1, length * 2 + 1))) + .isSameAs(value); if (length > 1) { checkMinContract(truncator, comparator, value, length - 1, strictMin); @@ -232,7 +227,7 @@ private void checkContract( // Edge case: possible to truncate min value to 0 length if original value is not empty checkMinContract(truncator, comparator, value, 0, strictMin); // Edge case: impossible to truncate max value to 0 length -> returning the original value - assertSame(value, truncator.truncateMax(value, 0)); + assertThat(truncator.truncateMax(value, 0)).isSameAs(value); } private void checkMinContract( @@ -244,17 +239,20 @@ private void checkMinContract( length, truncated.toStringUsingUTF8(), HEXA_STRINGIFIER.stringify(truncated)); - assertTrue("truncatedMin(value) should be <= than value", comparator.compare(truncated, value) <= 0); - assertFalse( - "length of truncateMin(value) should not be > than the length of value", - truncated.length() > value.length()); + assertThat(truncated) + .as("truncatedMin(value) should be <= than value") + .usingComparator(comparator) + .isLessThanOrEqualTo(value); + assertThat(truncated.length()) + .as("length of truncateMin(value) should not be > than the length of value") + .isLessThanOrEqualTo(value.length()); if (isValidUtf8(value)) { checkValidUtf8(truncated); } if (strict) { - assertTrue( - "length of truncateMin(value) ahould be < than the length of value", - truncated.length() < value.length()); + assertThat(truncated.length()) + .as("length of truncateMin(value) ahould be < than the length of value") + .isLessThan(value.length()); } } @@ -267,17 +265,20 @@ private void checkMaxContract( length, truncated.toStringUsingUTF8(), HEXA_STRINGIFIER.stringify(truncated)); - assertTrue("truncatedMax(value) should be >= than value", comparator.compare(truncated, value) >= 0); - assertFalse( - "length of truncateMax(value) should not be > than the length of value", - truncated.length() > value.length()); + assertThat(truncated) + .as("truncatedMax(value) should be >= than value") + .usingComparator(comparator) + .isGreaterThanOrEqualTo(value); + assertThat(truncated.length()) + .as("length of truncateMax(value) should not be > than the length of value") + .isLessThanOrEqualTo(value.length()); if (isValidUtf8(value)) { checkValidUtf8(truncated); } if (strict) { - assertTrue( - "length of truncateMax(value) ahould be < than the length of value", - truncated.length() < value.length()); + assertThat(truncated.length()) + .as("length of truncateMax(value) ahould be < than the length of value") + .isLessThan(value.length()); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBoundaryOrder.java b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBoundaryOrder.java index 658db8593f..4ea51b3219 100644 --- a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBoundaryOrder.java +++ b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestBoundaryOrder.java @@ -18,6 +18,8 @@ */ package org.apache.parquet.internal.column.columnindex; +import static org.assertj.core.api.Assertions.assertThat; + import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntList; import java.nio.ByteBuffer; @@ -32,7 +34,6 @@ import org.apache.parquet.schema.PrimitiveType; import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; import org.apache.parquet.schema.Types; -import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -276,7 +277,7 @@ private static ExecStats validateOperator( IntList expected = stats.measureLinear(validatorOp, comparator); IntList actual = stats.measureBinary(actualOp, comparator); - Assert.assertEquals(msg, expected, actual); + assertThat(actual.toIntArray()).isEqualTo(expected.toIntArray()); return stats; } diff --git a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilder.java b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilder.java index 96c66ea52e..530493c9f0 100644 --- a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilder.java +++ b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilder.java @@ -46,18 +46,13 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.FLOAT; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT64; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.List; @@ -243,8 +238,8 @@ public boolean inverseCanDrop(org.apache.parquet.filter2.predicate.Statistics toBBList(Binary... values) { @@ -1707,111 +1702,129 @@ private static Binary stringBinary(String str) { } private static void assertCorrectValues(List values, Binary... expectedValues) { - assertEquals(expectedValues.length, values.size()); + assertThat(values).hasSameSizeAs(expectedValues); for (int i = 0; i < expectedValues.length; ++i) { Binary expectedValue = expectedValues[i]; ByteBuffer value = values.get(i); if (expectedValue == null) { - assertFalse("The byte buffer should be empty for null pages", value.hasRemaining()); + assertThat(value.remaining()) + .as("The byte buffer should be empty for null pages") + .isZero(); } else { - assertArrayEquals("Invalid value for page " + i, expectedValue.getBytesUnsafe(), value.array()); + assertThat(value.array()).as("Invalid value for page " + i).isEqualTo(expectedValue.getBytesUnsafe()); } } } private static void assertCorrectValues(List values, Boolean... expectedValues) { - assertEquals(expectedValues.length, values.size()); + assertThat(values).hasSameSizeAs(expectedValues); for (int i = 0; i < expectedValues.length; ++i) { Boolean expectedValue = expectedValues[i]; ByteBuffer value = values.get(i); if (expectedValue == null) { - assertFalse("The byte buffer should be empty for null pages", value.hasRemaining()); + assertThat(value.remaining()) + .as("The byte buffer should be empty for null pages") + .isZero(); } else { - assertEquals("The byte buffer should be 1 byte long for boolean", 1, value.remaining()); - assertEquals("Invalid value for page " + i, expectedValue.booleanValue(), value.get(0) != 0); + assertThat(value.remaining()) + .as("The byte buffer should be 1 byte long for boolean") + .isEqualTo(1); + assertThat(value.get(0) != 0).isEqualTo(expectedValue.booleanValue()); } } } private static void assertCorrectValues(List values, Double... expectedValues) { - assertEquals(expectedValues.length, values.size()); + assertThat(values).hasSameSizeAs(expectedValues); for (int i = 0; i < expectedValues.length; ++i) { Double expectedValue = expectedValues[i]; ByteBuffer value = values.get(i); if (expectedValue == null) { - assertFalse("The byte buffer should be empty for null pages", value.hasRemaining()); + assertThat(value.remaining()) + .as("The byte buffer should be empty for null pages") + .isZero(); } else { - assertEquals("The byte buffer should be 8 bytes long for double", 8, value.remaining()); - assertTrue( - "Invalid value for page " + i, - Double.compare(expectedValue.doubleValue(), value.getDouble(0)) == 0); + assertThat(value.remaining()) + .as("The byte buffer should be 8 bytes long for double") + .isEqualTo(8); + assertThat(value.getDouble(0)) + .as("Invalid value for page " + i) + .usingComparator(Double::compare) + .isEqualByComparingTo(expectedValue); } } } private static void assertCorrectValues(List values, Float... expectedValues) { - assertEquals(expectedValues.length, values.size()); + assertThat(values).hasSameSizeAs(expectedValues); for (int i = 0; i < expectedValues.length; ++i) { Float expectedValue = expectedValues[i]; ByteBuffer value = values.get(i); if (expectedValue == null) { - assertFalse("The byte buffer should be empty for null pages", value.hasRemaining()); + assertThat(value.remaining()) + .as("The byte buffer should be empty for null pages") + .isZero(); } else { - assertEquals("The byte buffer should be 4 bytes long for double", 4, value.remaining()); - assertTrue( - "Invalid value for page " + i, - Float.compare(expectedValue.floatValue(), value.getFloat(0)) == 0); + assertThat(value.remaining()) + .as("The byte buffer should be 4 bytes long for double") + .isEqualTo(4); + assertThat(value.getFloat(0)) + .as("Invalid value for page " + i) + .usingComparator(Float::compare) + .isEqualByComparingTo(expectedValue); } } } private static void assertCorrectValues(List values, Integer... expectedValues) { - assertEquals(expectedValues.length, values.size()); + assertThat(values).hasSameSizeAs(expectedValues); for (int i = 0; i < expectedValues.length; ++i) { Integer expectedValue = expectedValues[i]; ByteBuffer value = values.get(i); if (expectedValue == null) { - assertFalse("The byte buffer should be empty for null pages", value.hasRemaining()); + assertThat(value.remaining()) + .as("The byte buffer should be empty for null pages") + .isZero(); } else { - assertEquals("The byte buffer should be 4 bytes long for int32", 4, value.remaining()); - assertEquals("Invalid value for page " + i, expectedValue.intValue(), value.getInt(0)); + assertThat(value.remaining()) + .as("The byte buffer should be 4 bytes long for int32") + .isEqualTo(4); + assertThat(value.getInt(0)).isEqualTo(expectedValue.intValue()); } } } private static void assertCorrectValues(List values, Long... expectedValues) { - assertEquals(expectedValues.length, values.size()); + assertThat(values).hasSameSizeAs(expectedValues); for (int i = 0; i < expectedValues.length; ++i) { Long expectedValue = expectedValues[i]; ByteBuffer value = values.get(i); if (expectedValue == null) { - assertFalse("The byte buffer should be empty for null pages", value.hasRemaining()); + assertThat(value.remaining()) + .as("The byte buffer should be empty for null pages") + .isZero(); } else { - assertEquals("The byte buffer should be 8 bytes long for int64", 8, value.remaining()); - assertEquals("Invalid value for page " + i, expectedValue.intValue(), value.getLong(0)); + assertThat(value.remaining()) + .as("The byte buffer should be 8 bytes long for int64") + .isEqualTo(8); + assertThat(value.getLong(0)).isEqualTo(expectedValue.intValue()); } } } private static void assertCorrectNullCounts(ColumnIndex columnIndex, long... expectedNullCounts) { List nullCounts = columnIndex.getNullCounts(); - assertEquals(expectedNullCounts.length, nullCounts.size()); + assertThat(nullCounts).hasSameSizeAs(expectedNullCounts); for (int i = 0; i < expectedNullCounts.length; ++i) { - assertEquals( - "Invalid null count at page " + i, - expectedNullCounts[i], - nullCounts.get(i).longValue()); + assertThat(nullCounts.get(i).longValue()).isEqualTo(expectedNullCounts[i]); } } private static void assertCorrectNullPages(ColumnIndex columnIndex, boolean... expectedNullPages) { List nullPages = columnIndex.getNullPages(); - assertEquals(expectedNullPages.length, nullPages.size()); + assertThat(nullPages).hasSameSizeAs(expectedNullPages); for (int i = 0; i < expectedNullPages.length; ++i) { - assertEquals( - "Invalid null pages at page " + i, - expectedNullPages[i], - nullPages.get(i).booleanValue()); + assertThat(nullPages.get(i).booleanValue()).isEqualTo(expectedNullPages[i]); } } @@ -1863,7 +1876,9 @@ long getMinMaxSize() { } private static void assertCorrectFiltering(ColumnIndex ci, FilterPredicate predicate, int... expectedIndexes) { - TestIndexIterator.assertEquals(predicate.accept(ci), expectedIndexes); + assertThat(predicate.accept(ci)) + .toIterable() + .containsExactly(Arrays.stream(expectedIndexes).boxed().toArray(Integer[]::new)); } @Test @@ -1874,59 +1889,59 @@ public void testBuildReturnsNullForNullPageCountContradiction() { PrimitiveType type = Types.required(INT32).named("test_col"); // Pages 1-3 have null_pages=true with null_counts=0 — contradictory - assertNull( - "Column index with null_pages=true and null_counts=0 should be rejected", - ColumnIndexBuilder.build( + assertThat(ColumnIndexBuilder.build( type, BoundaryOrder.ASCENDING, List.of(false, true, true, true), List.of(0L, 0L, 0L, 0L), toBBList(Integer.valueOf(-99), null, null, null), - toBBList(Integer.valueOf(5), null, null, null))); + toBBList(Integer.valueOf(5), null, null, null))) + .as("Column index with null_pages=true and null_counts=0 should be rejected") + .isNull(); // Contradiction on a single page (last page) should also be rejected - assertNull( - "Single contradictory page should cause rejection", - ColumnIndexBuilder.build( + assertThat(ColumnIndexBuilder.build( type, BoundaryOrder.UNORDERED, List.of(false, false, true), List.of(0L, 5L, 0L), toBBList(Integer.valueOf(1), Integer.valueOf(50), null), - toBBList(Integer.valueOf(49), Integer.valueOf(99), null))); + toBBList(Integer.valueOf(49), Integer.valueOf(99), null))) + .as("Single contradictory page should cause rejection") + .isNull(); // Contradiction on the first page - assertNull( - "Contradictory first page should cause rejection", - ColumnIndexBuilder.build( + assertThat(ColumnIndexBuilder.build( type, BoundaryOrder.UNORDERED, List.of(true, false, false), List.of(0L, 0L, 5L), toBBList(null, Integer.valueOf(1), Integer.valueOf(50)), - toBBList(null, Integer.valueOf(49), Integer.valueOf(99)))); + toBBList(null, Integer.valueOf(49), Integer.valueOf(99)))) + .as("Contradictory first page should cause rejection") + .isNull(); // Single page with contradiction - assertNull( - "Single-page column index with contradiction should be rejected", - ColumnIndexBuilder.build( + assertThat(ColumnIndexBuilder.build( type, BoundaryOrder.UNORDERED, List.of(true), List.of(0L), toBBList((Integer) null), - toBBList((Integer) null))); + toBBList((Integer) null))) + .as("Single-page column index with contradiction should be rejected") + .isNull(); // All pages are contradictory null pages - assertNull( - "All-contradictory column index should be rejected", - ColumnIndexBuilder.build( + assertThat(ColumnIndexBuilder.build( type, BoundaryOrder.UNORDERED, List.of(true, true, true), List.of(0L, 0L, 0L), toBBList((Integer) null, null, null), - toBBList((Integer) null, null, null))); + toBBList((Integer) null, null, null))) + .as("All-contradictory column index should be rejected") + .isNull(); } @Test @@ -2011,6 +2026,8 @@ public void testBuildWithoutNullCountsIsNotRejected() { toBBList(Integer.valueOf(1), null, null), toBBList(Integer.valueOf(99), null, null)); assertCorrectNullPages(ci, false, true, true); - assertNull("null_counts should be null when not provided", ci.getNullCounts()); + assertThat(ci.getNullCounts()) + .as("null_counts should be null when not provided") + .isNull(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilderNaN.java b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilderNaN.java index 85ef5a9b1b..cfea494782 100644 --- a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilderNaN.java +++ b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestColumnIndexBuilderNaN.java @@ -18,9 +18,7 @@ */ package org.apache.parquet.internal.column.columnindex; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -126,7 +124,7 @@ public void testFloatTypeDefinedOrderNaN() { builder.add(floatStats(FLOAT_TYPE, 1.0f, 2.0f)); builder.add(floatStats(FLOAT_TYPE, Float.NaN)); builder.add(floatStats(FLOAT_TYPE, 3.0f, 4.0f)); - assertNull(builder.build()); + assertThat(builder.build()).isNull(); } @Test @@ -135,7 +133,7 @@ public void testDoubleTypeDefinedOrderNaN() { builder.add(doubleStats(DOUBLE_TYPE, 1.0, 2.0)); builder.add(doubleStats(DOUBLE_TYPE, Double.NaN)); builder.add(doubleStats(DOUBLE_TYPE, 3.0, 4.0)); - assertNull(builder.build()); + assertThat(builder.build()).isNull(); } @Test @@ -144,7 +142,7 @@ public void testFloat16TypeDefinedOrderNaN() { builder.add(binaryStats(FLOAT16_TYPE, FLOAT16_ONE, FLOAT16_TWO)); builder.add(binaryStats(FLOAT16_TYPE, FLOAT16_NAN)); builder.add(binaryStats(FLOAT16_TYPE, FLOAT16_ONE)); - assertNull(builder.build()); + assertThat(builder.build()).isNull(); } // IEEE_754_TOTAL_ORDER: build column index with NaN @@ -156,8 +154,8 @@ public void testFloatIeee754BuildNanCounts() { builder.add(floatStats(FLOAT_IEEE754_TYPE, Float.NaN, 2.5f, Float.NaN)); builder.add(floatStats(FLOAT_IEEE754_TYPE, 3.0f, Float.NaN, 4.0f)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - assertEquals(List.of(0L, 2L, 1L), ci.getNanCounts()); + assertThat(ci).isNotNull(); + assertThat(ci.getNanCounts()).containsExactly(0L, 2L, 1L); } @Test @@ -167,8 +165,8 @@ public void testDoubleIeee754BuildNanCounts() { builder.add(doubleStats(DOUBLE_IEEE754_TYPE, Double.NaN, 2.5, Double.NaN)); builder.add(doubleStats(DOUBLE_IEEE754_TYPE, 3.0, Double.NaN, 4.0)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - assertEquals(List.of(0L, 2L, 1L), ci.getNanCounts()); + assertThat(ci).isNotNull(); + assertThat(ci.getNanCounts()).containsExactly(0L, 2L, 1L); } @Test @@ -178,8 +176,8 @@ public void testFloat16Ieee754BuildNanCounts() { builder.add(binaryStats(FLOAT16_IEEE754_TYPE, FLOAT16_NAN, FLOAT16_TWO, FLOAT16_NAN)); builder.add(binaryStats(FLOAT16_IEEE754_TYPE, FLOAT16_ONE)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - assertEquals(List.of(1L, 2L, 0L), ci.getNanCounts()); + assertThat(ci).isNotNull(); + assertThat(ci.getNanCounts()).containsExactly(1L, 2L, 0L); } @Test @@ -190,14 +188,12 @@ public void testFloatIeee754AllNanPageKeepsNanRangeInColumnIndex() { builder.add(floatStats(FLOAT_IEEE754_TYPE, maxNaN, minNaN)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - assertEquals(1, ci.getMinValues().size()); - assertEquals( - 0x7fc00001, - ci.getMinValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getInt(0)); - assertEquals( - 0x7fffffff, - ci.getMaxValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getInt(0)); + assertThat(ci).isNotNull(); + assertThat(ci.getMinValues()).hasSize(1); + assertThat(ci.getMinValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getInt(0)) + .isEqualTo(0x7fc00001); + assertThat(ci.getMaxValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getInt(0)) + .isEqualTo(0x7fffffff); } @Test @@ -208,14 +204,12 @@ public void testDoubleIeee754AllNanPageKeepsNanRangeInColumnIndex() { builder.add(doubleStats(DOUBLE_IEEE754_TYPE, maxNaN, minNaN)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - assertEquals(1, ci.getMinValues().size()); - assertEquals( - 0x7ff0000000000001L, - ci.getMinValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getLong(0)); - assertEquals( - 0x7fffffffffffffffL, - ci.getMaxValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getLong(0)); + assertThat(ci).isNotNull(); + assertThat(ci.getMinValues()).hasSize(1); + assertThat(ci.getMinValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getLong(0)) + .isEqualTo(0x7ff0000000000001L); + assertThat(ci.getMaxValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getLong(0)) + .isEqualTo(0x7fffffffffffffffL); } @Test @@ -224,14 +218,12 @@ public void testFloat16Ieee754AllNanPageKeepsNanRangeInColumnIndex() { builder.add(binaryStats(FLOAT16_IEEE754_TYPE, FLOAT16_NAN_LARGE, FLOAT16_NAN_SMALL)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - assertEquals(1, ci.getMinValues().size()); - assertEquals( - FLOAT16_NAN_SMALL.get2BytesLittleEndian(), - ci.getMinValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getShort(0)); - assertEquals( - FLOAT16_NAN_LARGE.get2BytesLittleEndian(), - ci.getMaxValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getShort(0)); + assertThat(ci).isNotNull(); + assertThat(ci.getMinValues()).hasSize(1); + assertThat(ci.getMinValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getShort(0)) + .isEqualTo(FLOAT16_NAN_SMALL.get2BytesLittleEndian()); + assertThat(ci.getMaxValues().get(0).order(ByteOrder.LITTLE_ENDIAN).getShort(0)) + .isEqualTo(FLOAT16_NAN_LARGE.get2BytesLittleEndian()); } // Column index filtering for float @@ -243,25 +235,27 @@ public void testNaNFloatZeroNaN() { builder.add(floatStats(FLOAT_IEEE754_TYPE, 1.0f, 2.0f)); builder.add(floatStats(FLOAT_IEEE754_TYPE, 3.0f, 4.0f)); ColumnIndex ci = builder.build(); - assertNotNull(ci); + assertThat(ci).isNotNull(); // Non-NaN literal (1.5 within page 0 range; ASCENDING boundary order) - assertEquals(List.of(0), toList(ci.visit(FilterApi.eq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.notEq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.lt(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.ltEq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gt(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gtEq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(1.5f)))))); + assertThat(toList(ci.visit(FilterApi.eq(FLOAT_COL, 1.5f)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT_COL, 1.5f)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT_COL, 1.5f)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT_COL, 1.5f)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT_COL, 1.5f)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT_COL, 1.5f)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(1.5f)))))) + .containsExactly(0); // NaN literal: nanCounts all zero, so eq returns empty and notEq returns all - assertEquals(List.of(), toList(ci.visit(FilterApi.eq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.notEq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.lt(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.ltEq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gt(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gtEq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(), toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(Float.NaN)))))); + assertThat(toList(ci.visit(FilterApi.eq(FLOAT_COL, Float.NaN)))).isEmpty(); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT_COL, Float.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT_COL, Float.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT_COL, Float.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT_COL, Float.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT_COL, Float.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(Float.NaN)))))) + .isEmpty(); } @Test @@ -276,12 +270,12 @@ public void testNaNFloatUnknownNaNCounts() { List.of(floatBuffer(2.0f), floatBuffer(4.0f)), null, null); - assertNotNull(ci); + assertThat(ci).isNotNull(); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.eq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.lt(FLOAT_COL, 0.0f)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gt(FLOAT_COL, 5.0f)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.notEq(FLOAT_COL, 1.5f)))); + assertThat(toList(ci.visit(FilterApi.eq(FLOAT_COL, Float.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT_COL, 0.0f)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT_COL, 5.0f)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT_COL, 1.5f)))).containsExactly(0, 1); } @Test @@ -292,23 +286,25 @@ public void testNaNFloatMixed() { builder.add(floatStats(FLOAT_IEEE754_TYPE, Float.NaN, 2.5f)); builder.add(floatStats(FLOAT_IEEE754_TYPE, 3.0f, 4.0f)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - - assertEquals(List.of(0), toList(ci.visit(FilterApi.eq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.notEq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.lt(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.ltEq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gt(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gtEq(FLOAT_COL, 1.5f)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(1.5f)))))); - - assertEquals(List.of(1), toList(ci.visit(FilterApi.eq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.notEq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.lt(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.ltEq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gt(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gtEq(FLOAT_COL, Float.NaN)))); - assertEquals(List.of(1), toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(Float.NaN)))))); + assertThat(ci).isNotNull(); + + assertThat(toList(ci.visit(FilterApi.eq(FLOAT_COL, 1.5f)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT_COL, 1.5f)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT_COL, 1.5f)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT_COL, 1.5f)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT_COL, 1.5f)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT_COL, 1.5f)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(1.5f)))))) + .containsExactly(0); + + assertThat(toList(ci.visit(FilterApi.eq(FLOAT_COL, Float.NaN)))).containsExactly(1); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT_COL, Float.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT_COL, Float.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT_COL, Float.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT_COL, Float.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT_COL, Float.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.in(FLOAT_COL, new HashSet<>(List.of(Float.NaN)))))) + .containsExactly(1); } // Column index filtering for double @@ -320,23 +316,25 @@ public void testNaNDoubleZeroNaN() { builder.add(doubleStats(DOUBLE_IEEE754_TYPE, 1.0, 2.0)); builder.add(doubleStats(DOUBLE_IEEE754_TYPE, 3.0, 4.0)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - - assertEquals(List.of(0), toList(ci.visit(FilterApi.eq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.notEq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.lt(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gt(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(1.5)))))); - - assertEquals(List.of(), toList(ci.visit(FilterApi.eq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.notEq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.lt(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gt(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(), toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(Double.NaN)))))); + assertThat(ci).isNotNull(); + + assertThat(toList(ci.visit(FilterApi.eq(DOUBLE_COL, 1.5)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.notEq(DOUBLE_COL, 1.5)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.lt(DOUBLE_COL, 1.5)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, 1.5)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.gt(DOUBLE_COL, 1.5)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, 1.5)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(1.5)))))) + .containsExactly(0); + + assertThat(toList(ci.visit(FilterApi.eq(DOUBLE_COL, Double.NaN)))).isEmpty(); + assertThat(toList(ci.visit(FilterApi.notEq(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.lt(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gt(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(Double.NaN)))))) + .isEmpty(); } @Test @@ -347,23 +345,25 @@ public void testNaNDoubleMixed() { builder.add(doubleStats(DOUBLE_IEEE754_TYPE, Double.NaN, 2.5)); builder.add(doubleStats(DOUBLE_IEEE754_TYPE, 3.0, 4.0)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - - assertEquals(List.of(0), toList(ci.visit(FilterApi.eq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.notEq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.lt(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gt(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, 1.5)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(1.5)))))); - - assertEquals(List.of(1), toList(ci.visit(FilterApi.eq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.notEq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.lt(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gt(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, Double.NaN)))); - assertEquals(List.of(1), toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(Double.NaN)))))); + assertThat(ci).isNotNull(); + + assertThat(toList(ci.visit(FilterApi.eq(DOUBLE_COL, 1.5)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.notEq(DOUBLE_COL, 1.5)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.lt(DOUBLE_COL, 1.5)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, 1.5)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gt(DOUBLE_COL, 1.5)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, 1.5)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(1.5)))))) + .containsExactly(0); + + assertThat(toList(ci.visit(FilterApi.eq(DOUBLE_COL, Double.NaN)))).containsExactly(1); + assertThat(toList(ci.visit(FilterApi.notEq(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.lt(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.ltEq(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gt(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gtEq(DOUBLE_COL, Double.NaN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.in(DOUBLE_COL, new HashSet<>(List.of(Double.NaN)))))) + .containsExactly(1); } // Column index filtering for float16 @@ -375,23 +375,25 @@ public void testNaNFloat16ZeroNaN() { builder.add(binaryStats(FLOAT16_IEEE754_TYPE, FLOAT16_ONE, FLOAT16_TWO)); builder.add(binaryStats(FLOAT16_IEEE754_TYPE, FLOAT16_THREE, FLOAT16_FOUR)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - - assertEquals(List.of(0), toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(), toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_ONE)))))); - - assertEquals(List.of(), toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(), toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_NAN)))))); + assertThat(ci).isNotNull(); + + assertThat(toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_ONE)))).isEmpty(); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_ONE)))))) + .containsExactly(0); + + assertThat(toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_NAN)))).isEmpty(); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_NAN)))))) + .isEmpty(); } @Test @@ -402,22 +404,24 @@ public void testNaNFloat16Mixed() { builder.add(binaryStats(FLOAT16_IEEE754_TYPE, FLOAT16_NAN, FLOAT16_TWO)); builder.add(binaryStats(FLOAT16_IEEE754_TYPE, FLOAT16_THREE, FLOAT16_FOUR)); ColumnIndex ci = builder.build(); - assertNotNull(ci); - - assertEquals(List.of(0), toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(1), toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0, 1), toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_ONE)))); - assertEquals(List.of(0), toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_ONE)))))); - - assertEquals(List.of(1), toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(0, 1, 2), toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_NAN)))); - assertEquals(List.of(1), toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_NAN)))))); + assertThat(ci).isNotNull(); + + assertThat(toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(1); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0, 1); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_ONE)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_ONE)))))) + .containsExactly(0); + + assertThat(toList(ci.visit(FilterApi.eq(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(1); + assertThat(toList(ci.visit(FilterApi.notEq(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.lt(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.ltEq(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gt(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.gtEq(FLOAT16_COL, FLOAT16_NAN)))).containsExactly(0, 1, 2); + assertThat(toList(ci.visit(FilterApi.in(FLOAT16_COL, new HashSet<>(List.of(FLOAT16_NAN)))))) + .containsExactly(1); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestIndexIterator.java b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestIndexIterator.java index cfbfeed1df..85541bdd6b 100644 --- a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestIndexIterator.java +++ b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestIndexIterator.java @@ -18,12 +18,8 @@ */ package org.apache.parquet.internal.column.columnindex; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; -import it.unimi.dsi.fastutil.ints.IntArrayList; -import it.unimi.dsi.fastutil.ints.IntList; -import java.util.Arrays; -import java.util.PrimitiveIterator; import org.junit.Test; /** @@ -32,123 +28,90 @@ public class TestIndexIterator { @Test public void testAll() { - assertEquals(IndexIterator.all(10), 0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + assertThat(IndexIterator.all(10)).toIterable().containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); } @Test public void testFilter() { - assertEquals(IndexIterator.filter(30, value -> value % 3 == 0), 0, 3, 6, 9, 12, 15, 18, 21, 24, 27); + assertThat(IndexIterator.filter(30, value -> value % 3 == 0)) + .toIterable() + .containsExactly(0, 3, 6, 9, 12, 15, 18, 21, 24, 27); } @Test public void testFilterTranslate() { - assertEquals(IndexIterator.filterTranslate(20, value -> value < 5, Math::negateExact), 0, -1, -2, -3, -4); + assertThat(IndexIterator.filterTranslate(20, value -> value < 5, Math::negateExact)) + .toIterable() + .containsExactly(0, -1, -2, -3, -4); } @Test public void testRangeTranslate() { - assertEquals(IndexIterator.rangeTranslate(11, 18, i -> i - 10), 1, 2, 3, 4, 5, 6, 7, 8); + assertThat(IndexIterator.rangeTranslate(11, 18, i -> i - 10)) + .toIterable() + .containsExactly(1, 2, 3, 4, 5, 6, 7, 8); } @Test public void testUnion() { // Test deduplication of intersecting ranges - assertEquals( - IndexIterator.union( - IndexIterator.rangeTranslate(0, 7, i -> i), IndexIterator.rangeTranslate(4, 10, i -> i)), - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10); + assertThat(IndexIterator.union( + IndexIterator.rangeTranslate(0, 7, i -> i), IndexIterator.rangeTranslate(4, 10, i -> i))) + .toIterable() + .containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Test inversion of LHS and RHS - assertEquals( - IndexIterator.union( - IndexIterator.rangeTranslate(4, 10, i -> i), IndexIterator.rangeTranslate(0, 7, i -> i)), - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10); + assertThat(IndexIterator.union( + IndexIterator.rangeTranslate(4, 10, i -> i), IndexIterator.rangeTranslate(0, 7, i -> i))) + .toIterable() + .containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Test non-intersecting ranges - assertEquals( - IndexIterator.union( - IndexIterator.rangeTranslate(2, 5, i -> i), IndexIterator.rangeTranslate(8, 10, i -> i)), - 2, - 3, - 4, - 5, - 8, - 9, - 10); + assertThat(IndexIterator.union( + IndexIterator.rangeTranslate(2, 5, i -> i), IndexIterator.rangeTranslate(8, 10, i -> i))) + .toIterable() + .containsExactly(2, 3, 4, 5, 8, 9, 10); } @Test public void testIntersection() { // Case 1: some overlap between LHS and RHS // LHS: [0, 1, 2, 3, 4, 5, 6, 7], RHS: [4, 5, 6, 7, 8, 9, 10] - assertEquals( - IndexIterator.intersection( - IndexIterator.rangeTranslate(0, 7, i -> i), IndexIterator.rangeTranslate(4, 10, i -> i)), - 4, - 5, - 6, - 7); + assertThat(IndexIterator.intersection( + IndexIterator.rangeTranslate(0, 7, i -> i), IndexIterator.rangeTranslate(4, 10, i -> i))) + .toIterable() + .containsExactly(4, 5, 6, 7); // Test inversion of LHS and RHS - assertEquals( - IndexIterator.intersection( - IndexIterator.rangeTranslate(4, 10, i -> i), IndexIterator.rangeTranslate(0, 7, i -> i)), - 4, - 5, - 6, - 7); + assertThat(IndexIterator.intersection( + IndexIterator.rangeTranslate(4, 10, i -> i), IndexIterator.rangeTranslate(0, 7, i -> i))) + .toIterable() + .containsExactly(4, 5, 6, 7); // Case 2: Single point of overlap at end of iterator // LHS: [1, 3, 5, 7], RHS: [0, 2, 4, 6, 7] - assertEquals( - IndexIterator.intersection( - IndexIterator.filter(8, i -> i % 2 == 1), IndexIterator.filter(8, i -> i % 2 == 0 || i == 7)), - 7); + assertThat(IndexIterator.intersection( + IndexIterator.filter(8, i -> i % 2 == 1), IndexIterator.filter(8, i -> i % 2 == 0 || i == 7))) + .toIterable() + .containsExactly(7); // Test inversion of LHS and RHS - assertEquals( - IndexIterator.intersection( - IndexIterator.filter(8, i -> i % 2 == 0 || i == 7), IndexIterator.filter(8, i -> i % 2 == 1)), - 7); + assertThat(IndexIterator.intersection( + IndexIterator.filter(8, i -> i % 2 == 0 || i == 7), IndexIterator.filter(8, i -> i % 2 == 1))) + .toIterable() + .containsExactly(7); // Test no intersection between ranges // LHS: [2, 3, 4, 5], RHS: [8, 9, 10] - assertEquals(IndexIterator.intersection( - IndexIterator.rangeTranslate(2, 5, i -> i), IndexIterator.rangeTranslate(8, 10, i -> i))); + assertThat(IndexIterator.intersection( + IndexIterator.rangeTranslate(2, 5, i -> i), IndexIterator.rangeTranslate(8, 10, i -> i))) + .toIterable() + .isEmpty(); // Test inversion of LHS and RHS - assertEquals(IndexIterator.intersection( - IndexIterator.rangeTranslate(8, 10, i -> i), IndexIterator.rangeTranslate(2, 5, i -> i))); - } - - static void assertEquals(PrimitiveIterator.OfInt actualIt, int... expectedValues) { - IntList actualList = new IntArrayList(); - actualIt.forEachRemaining((int value) -> actualList.add(value)); - int[] actualValues = actualList.toIntArray(); - assertArrayEquals( - "ExpectedValues: " + Arrays.toString(expectedValues) + " ActualValues: " - + Arrays.toString(actualValues), - expectedValues, - actualValues); + assertThat(IndexIterator.intersection( + IndexIterator.rangeTranslate(8, 10, i -> i), IndexIterator.rangeTranslate(2, 5, i -> i))) + .toIterable() + .isEmpty(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestOffsetIndexBuilder.java b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestOffsetIndexBuilder.java index adbd3ef33a..79d8867686 100644 --- a/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestOffsetIndexBuilder.java +++ b/parquet-column/src/test/java/org/apache/parquet/internal/column/columnindex/TestOffsetIndexBuilder.java @@ -18,8 +18,7 @@ */ package org.apache.parquet.internal.column.columnindex; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -30,8 +29,8 @@ public class TestOffsetIndexBuilder { @Test public void testBuilderWithSizeAndRowCount() { OffsetIndexBuilder builder = OffsetIndexBuilder.getBuilder(); - assertNull(builder.build()); - assertNull(builder.build(1234)); + assertThat(builder.build()).isNull(); + assertThat(builder.build(1234)).isNull(); builder.add(1000, 10); builder.add(2000, 19); @@ -48,15 +47,15 @@ public void testNoOpBuilderWithSizeAndRowCount() { builder.add(3, 4); builder.add(5, 6); builder.add(7, 8); - assertNull(builder.build()); - assertNull(builder.build(1000)); + assertThat(builder.build()).isNull(); + assertThat(builder.build(1000)).isNull(); } @Test public void testBuilderWithOffsetSizeIndex() { OffsetIndexBuilder builder = OffsetIndexBuilder.getBuilder(); - assertNull(builder.build()); - assertNull(builder.build(1234)); + assertThat(builder.build()).isNull(); + assertThat(builder.build(1234)).isNull(); builder.add(1000, 10000, 0); builder.add(22000, 12000, 100); @@ -74,28 +73,20 @@ public void testNoOpBuilderWithOffsetSizeIndex() { builder.add(4, 5, 6); builder.add(7, 8, 9); builder.add(10, 11, 12); - assertNull(builder.build()); - assertNull(builder.build(1000)); + assertThat(builder.build()).isNull(); + assertThat(builder.build(1000)).isNull(); } private void assertCorrectValues(OffsetIndex offsetIndex, long... offset_size_rowIndex_triplets) { - assertEquals(offset_size_rowIndex_triplets.length % 3, 0); + assertThat(offset_size_rowIndex_triplets.length % 3).isEqualTo(0); int pageCount = offset_size_rowIndex_triplets.length / 3; - assertEquals("Invalid pageCount", pageCount, offsetIndex.getPageCount()); + assertThat(offsetIndex.getPageCount()).as("Invalid pageCount").isEqualTo(pageCount); for (int i = 0; i < pageCount; ++i) { - assertEquals( - "Invalid offsetIndex at page " + i, offset_size_rowIndex_triplets[3 * i], offsetIndex.getOffset(i)); - assertEquals( - "Invalid compressedPageSize at page " + i, - offset_size_rowIndex_triplets[3 * i + 1], - offsetIndex.getCompressedPageSize(i)); - assertEquals( - "Invalid firstRowIndex at page " + i, - offset_size_rowIndex_triplets[3 * i + 2], - offsetIndex.getFirstRowIndex(i)); + assertThat(offsetIndex.getOffset(i)).isEqualTo(offset_size_rowIndex_triplets[3 * i]); + assertThat(offsetIndex.getCompressedPageSize(i)).isEqualTo(offset_size_rowIndex_triplets[3 * i + 1]); + assertThat(offsetIndex.getFirstRowIndex(i)).isEqualTo(offset_size_rowIndex_triplets[3 * i + 2]); long expectedLastPageIndex = (i < pageCount - 1) ? (offset_size_rowIndex_triplets[3 * i + 5] - 1) : 999; - assertEquals( - "Invalid lastRowIndex at page " + i, expectedLastPageIndex, offsetIndex.getLastRowIndex(i, 1000)); + assertThat(offsetIndex.getLastRowIndex(i, 1000)).isEqualTo(expectedLastPageIndex); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/internal/filter2/columnindex/TestColumnIndexFilter.java b/parquet-column/src/test/java/org/apache/parquet/internal/filter2/columnindex/TestColumnIndexFilter.java index 91327b3357..dda66630c9 100644 --- a/parquet-column/src/test/java/org/apache/parquet/internal/filter2/columnindex/TestColumnIndexFilter.java +++ b/parquet-column/src/test/java/org/apache/parquet/internal/filter2/columnindex/TestColumnIndexFilter.java @@ -49,7 +49,7 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT64; import static org.apache.parquet.schema.Types.optional; import static org.apache.parquet.schema.Types.repeated; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.longs.LongList; @@ -399,13 +399,17 @@ private static void assertAllRows(RowRanges ranges, long rowCount) { ranges.iterator().forEachRemaining((long value) -> actualList.add(value)); LongList expectedList = new LongArrayList(); LongStream.range(0, rowCount).forEach(expectedList::add); - assertArrayEquals(expectedList + " != " + actualList, expectedList.toLongArray(), actualList.toLongArray()); + assertThat(actualList.toLongArray()) + .as(expectedList + " != " + actualList) + .isEqualTo(expectedList.toLongArray()); } private static void assertRows(RowRanges ranges, long... expectedRows) { LongList actualList = new LongArrayList(); ranges.iterator().forEachRemaining((long value) -> actualList.add(value)); - assertArrayEquals(Arrays.toString(expectedRows) + " != " + actualList, expectedRows, actualList.toLongArray()); + assertThat(actualList.toLongArray()) + .as(Arrays.toString(expectedRows) + " != " + actualList) + .isEqualTo(expectedRows); } @Test diff --git a/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingConverter.java b/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingConverter.java index 99073c98ed..047a82ea7f 100644 --- a/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingConverter.java +++ b/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingConverter.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.io; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayDeque; import java.util.Deque; @@ -42,7 +42,7 @@ public class ExpectationValidatingConverter extends RecordMaterializer { int count = 0; public void validate(String got) { - assertEquals("event #" + count, expectations.pop(), got); + assertThat(got).isEqualTo(expectations.pop()); ++count; } diff --git a/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingRecordConsumer.java b/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingRecordConsumer.java index e21ebb6e10..5cde37795d 100644 --- a/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingRecordConsumer.java +++ b/parquet-column/src/test/java/org/apache/parquet/io/ExpectationValidatingRecordConsumer.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.io; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Deque; import org.apache.parquet.io.api.Binary; @@ -33,7 +33,7 @@ public ExpectationValidatingRecordConsumer(Deque expectations) { } private void validate(String got) { - assertEquals("event #" + count, expectations.pop(), got); + assertThat(got).isEqualTo(expectations.pop()); ++count; } diff --git a/parquet-column/src/test/java/org/apache/parquet/io/TestColumnIO.java b/parquet-column/src/test/java/org/apache/parquet/io/TestColumnIO.java index fa4fab710c..85556c978f 100644 --- a/parquet-column/src/test/java/org/apache/parquet/io/TestColumnIO.java +++ b/parquet-column/src/test/java/org/apache/parquet/io/TestColumnIO.java @@ -28,8 +28,8 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.apache.parquet.schema.Type.Repetition.OPTIONAL; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.util.ArrayList; @@ -60,7 +60,6 @@ import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; import org.apache.parquet.schema.Type; import org.apache.parquet.schema.Type.Repetition; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -155,7 +154,7 @@ public TestColumnIO(boolean useDictionary) { @Test public void testSchema() { - assertEquals(schemaString, schema.toString()); + assertThat(schema).asString().isEqualTo(schemaString); } @Test @@ -204,16 +203,12 @@ public void testReadUsingRequestedSchemaWithIncompatibleField() { SimpleGroupFactory groupFactory = new SimpleGroupFactory(originalSchema); writeGroups(originalSchema, store, groupFactory.newGroup().append("e", 4)); - try { - MessageType schemaWithIncompatibleField = new MessageType( - "schema", new PrimitiveType(OPTIONAL, BINARY, "e")); // Incompatible schema: different type - readGroups(store, originalSchema, schemaWithIncompatibleField, 1); - fail("should have thrown an incompatible schema exception"); - } catch (ParquetDecodingException e) { - assertEquals( - "The requested schema is not compatible with the file schema. incompatible types: optional binary e != optional int32 e", - e.getMessage()); - } + // Incompatible schema: different type + MessageType schemaWithIncompatibleField = new MessageType("schema", new PrimitiveType(OPTIONAL, BINARY, "e")); + assertThatThrownBy(() -> readGroups(store, originalSchema, schemaWithIncompatibleField, 1)) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage( + "The requested schema is not compatible with the file schema. incompatible types: optional binary e != optional int32 e"); } @Test @@ -223,17 +218,13 @@ public void testReadUsingSchemaWithRequiredFieldThatWasOptional() { SimpleGroupFactory groupFactory = new SimpleGroupFactory(originalSchema); writeGroups(originalSchema, store, groupFactory.newGroup().append("e", 4)); - try { - MessageType schemaWithRequiredFieldThatWasOptional = new MessageType( - "schema", - new PrimitiveType(REQUIRED, INT32, "e")); // Incompatible schema: required when it was optional - readGroups(store, originalSchema, schemaWithRequiredFieldThatWasOptional, 1); - fail("should have thrown an incompatible schema exception"); - } catch (ParquetDecodingException e) { - assertEquals( - "The requested schema is not compatible with the file schema. incompatible types: required int32 e != optional int32 e", - e.getMessage()); - } + // Incompatible schema: required when it was optional + MessageType schemaWithRequiredFieldThatWasOptional = + new MessageType("schema", new PrimitiveType(REQUIRED, INT32, "e")); + assertThatThrownBy(() -> readGroups(store, originalSchema, schemaWithRequiredFieldThatWasOptional, 1)) + .isInstanceOf(ParquetDecodingException.class) + .hasMessage( + "The requested schema is not compatible with the file schema. incompatible types: required int32 e != optional int32 e"); } @Test @@ -263,11 +254,10 @@ private void validateGroups(List groups1, Object[][] e1) { for (int j = 0; j < objects.length; j++) { Object object = objects[j]; if (object == null) { - assertEquals(0, next.getFieldRepetitionCount(j)); + assertThat(next.getFieldRepetitionCount(j)).isEqualTo(0); } else { - assertEquals( - "looking for r[" + i + "][" + j + "][0]=" + object, 1, next.getFieldRepetitionCount(j)); - assertEquals(object, next.getInteger(j, 0)); + assertThat(next.getFieldRepetitionCount(j)).isEqualTo(1); + assertThat(next.getInteger(j, 0)).isEqualTo(object); } } } @@ -336,14 +326,14 @@ public void testColumnIO() { log("r" + (++i)); log(record); } - assertEquals( - "deserialization does not display the same result", - r1.toString(), - records.get(0).toString()); - assertEquals( - "deserialization does not display the same result", - r2.toString(), - records.get(1).toString()); + assertThat(records.get(0)) + .as("deserialization does not display the same result") + .asString() + .isEqualTo(r1.toString()); + assertThat(records.get(1)) + .as("deserialization does not display the same result") + .asString() + .isEqualTo(r2.toString()); } { MessageColumnIO columnIO2 = columnIOFactory.getColumnIO(schema2); @@ -361,14 +351,14 @@ public void testColumnIO() { log("r" + (++i)); log(record); } - assertEquals( - "deserialization does not display the expected result", - pr1.toString(), - records.get(0).toString()); - assertEquals( - "deserialization does not display the expected result", - pr2.toString(), - records.get(1).toString()); + assertThat(records.get(0)) + .as("deserialization does not display the expected result") + .asString() + .isEqualTo(pr1.toString()); + assertThat(records.get(1)) + .as("deserialization does not display the expected result") + .asString() + .isEqualTo(pr2.toString()); } } @@ -487,7 +477,10 @@ private void testSchema(MessageType messageSchema, List groups) { RecordReaderImplementation recordReader = getRecordReader(columnIO, messageSchema, memPageStore); for (Group group : groups) { final Group got = recordReader.read(); - assertEquals("deserialization does not display the same result", group.toString(), got.toString()); + assertThat(got) + .as("deserialization does not display the same result") + .asString() + .isEqualTo(group.toString()); } } @@ -516,10 +509,7 @@ private void validateFSA( ? "end" : Arrays.toString(leaves.get(next).getFieldPath())) + ": " + recordReader.getNextLevel(i, r)); - assertEquals( - Arrays.toString(primitiveColumnIO.getFieldPath()) + ": " + r + " -> ", - next, - recordReader.getNextReader(i, r)); + assertThat(recordReader.getNextReader(i, r)).isEqualTo(next); } } log("----"); @@ -561,13 +551,9 @@ public void testEmptyField() { recordWriter.addLong(0); recordWriter.endField("DocId", 0); recordWriter.startField("Links", 1); - try { - recordWriter.endField("Links", 1); - Assert.fail("expected exception because of empty field"); - } catch (ParquetEncodingException e) { - Assert.assertEquals( - "empty fields are illegal, the field should be ommited completely instead", e.getMessage()); - } + assertThatThrownBy(() -> recordWriter.endField("Links", 1)) + .isInstanceOf(ParquetEncodingException.class) + .hasMessage("empty fields are illegal, the field should be ommited completely instead"); } @Test @@ -580,14 +566,14 @@ public void testGroupWriter() { result.add(groupRecordConverter.getCurrentRecord()); groupWriter.write(r2); result.add(groupRecordConverter.getCurrentRecord()); - assertEquals( - "deserialization does not display the expected result", - result.get(0).toString(), - r1.toString()); - assertEquals( - "deserialization does not display the expected result", - result.get(1).toString(), - r2.toString()); + assertThat(r1) + .as("deserialization does not display the expected result") + .asString() + .isEqualTo(result.get(0).toString()); + assertThat(r2) + .as("deserialization does not display the expected result") + .asString() + .isEqualTo(result.get(1).toString()); } @Test @@ -649,7 +635,7 @@ public ColumnWriter getColumnWriter(final ColumnDescriptor path) { private void validate(Object value, int repetitionLevel, int definitionLevel) { String actual = Arrays.toString(path.getPath()) + ": " + value + ", r:" + repetitionLevel + ", d:" + definitionLevel; - assertEquals("event #" + counter, expected[counter], actual); + assertThat(actual).isEqualTo(expected[counter]); ++counter; } @@ -699,7 +685,7 @@ public void write(double value, int repetitionLevel, int definitionLevel) { } public void validate() { - assertEquals("read all events", expected.length, counter); + assertThat(counter).as("read all events").isEqualTo(expected.length); } @Override diff --git a/parquet-column/src/test/java/org/apache/parquet/io/TestFiltered.java b/parquet-column/src/test/java/org/apache/parquet/io/TestFiltered.java index 5d505360f4..acd1f54686 100644 --- a/parquet-column/src/test/java/org/apache/parquet/io/TestFiltered.java +++ b/parquet-column/src/test/java/org/apache/parquet/io/TestFiltered.java @@ -29,7 +29,7 @@ import static org.apache.parquet.filter.NotRecordFilter.not; import static org.apache.parquet.filter.OrRecordFilter.or; import static org.apache.parquet.filter.PagedRecordFilter.page; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -75,11 +75,11 @@ private List readAll(RecordReader reader) { private void readOne(RecordReader reader, String message, Group expected) { List result = readAll(reader); - assertEquals(message + ": " + result, 1, result.size()); - assertEquals( - "filtering did not return the correct record", - expected.toString(), - result.get(0).toString()); + assertThat(result).hasSize(1); + assertThat(result.get(0)) + .as("filtering did not return the correct record") + .asString() + .isEqualTo(expected.toString()); } @Test @@ -140,7 +140,7 @@ public void testFilterOnString() { memPageStore, recordConverter, FilterCompat.get(column("Name.Url", equalTo("http://B")))); List all = readAll(recordReader); - assertEquals("There should be no matching records: " + all, 0, all.size()); + assertThat(all).isEmpty(); // Finally try matching against the C url in record 2 recordReader = (RecordReaderImplementation) columnIO.getRecordReader( @@ -169,7 +169,7 @@ public void testApplyFunctionFilterOnString() { memPageStore, recordConverter, FilterCompat.get(column("Name.Url", equalTo("http://B")))); List all = readAll(recordReader); - assertEquals("There should be no matching records: " + all, 0, all.size()); + assertThat(all).isEmpty(); // Finally try matching against the C url in record 2 recordReader = (RecordReaderImplementation) columnIO.getRecordReader( @@ -188,12 +188,9 @@ public void testPaged() { columnIO.getRecordReader(memPageStore, recordConverter, FilterCompat.get(page(4, 4))); List all = readAll(recordReader); - assertEquals("expecting records " + all, 4, all.size()); + assertThat(all).hasSize(4); for (int i = 0; i < all.size(); i++) { - assertEquals( - "expecting record", - (i % 2 == 0 ? r2 : r1).toString(), - all.get(i).toString()); + assertThat(all.get(i)).as("expecting record").asString().isEqualTo((i % 2 == 0 ? r2 : r1).toString()); } } @@ -207,9 +204,9 @@ public void testFilteredAndPaged() { memPageStore, recordConverter, FilterCompat.get(and(column("DocId", equalTo(10l)), page(2, 4)))); List all = readAll(recordReader); - assertEquals("expecting 4 records " + all, 4, all.size()); + assertThat(all).hasSize(4); for (int i = 0; i < all.size(); i++) { - assertEquals("expecting record1", r1.toString(), all.get(i).toString()); + assertThat(all.get(i)).as("expecting record1").asString().isEqualTo(r1.toString()); } } @@ -225,10 +222,10 @@ public void testFilteredOrPaged() { FilterCompat.get(or(column("DocId", equalTo(10l)), column("DocId", equalTo(20l))))); List all = readAll(recordReader); - assertEquals("expecting 8 records " + all, 16, all.size()); + assertThat(all).hasSize(16); for (int i = 0; i < all.size() / 2; i++) { - assertEquals("expecting record1", r1.toString(), all.get(2 * i).toString()); - assertEquals("expecting record2", r2.toString(), all.get(2 * i + 1).toString()); + assertThat(all.get(2 * i)).as("expecting record1").asString().isEqualTo(r1.toString()); + assertThat(all.get(2 * i + 1)).as("expecting record2").asString().isEqualTo(r2.toString()); } } @@ -242,9 +239,9 @@ public void testFilteredNotPaged() { memPageStore, recordConverter, FilterCompat.get(not(column("DocId", equalTo(10l))))); List all = readAll(recordReader); - assertEquals("expecting 8 records " + all, 8, all.size()); + assertThat(all).hasSize(8); for (int i = 0; i < all.size(); i++) { - assertEquals("expecting record2", r2.toString(), all.get(i).toString()); + assertThat(all.get(i)).as("expecting record2").asString().isEqualTo(r2.toString()); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/io/ValidatingRecordConsumerTest.java b/parquet-column/src/test/java/org/apache/parquet/io/ValidatingRecordConsumerTest.java index e6262238ee..deb4b393a0 100644 --- a/parquet-column/src/test/java/org/apache/parquet/io/ValidatingRecordConsumerTest.java +++ b/parquet-column/src/test/java/org/apache/parquet/io/ValidatingRecordConsumerTest.java @@ -20,7 +20,7 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Field; import java.util.Deque; @@ -90,8 +90,9 @@ public void testNoPreviousFieldLeakAfterMessage() throws Exception { consumer.endMessage(); Deque previousField = (Deque) previousFieldField.get(consumer); - assertEquals( - "previousField deque should be empty after endMessage (row " + row + ")", 0, previousField.size()); + assertThat(previousField) + .as("previousField deque should be empty after endMessage (row " + row + ")") + .isEmpty(); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/io/api/TestBinary.java b/parquet-column/src/test/java/org/apache/parquet/io/api/TestBinary.java index 515d4d5b9e..eebe9604c8 100644 --- a/parquet-column/src/test/java/org/apache/parquet/io/api/TestBinary.java +++ b/parquet-column/src/test/java/org/apache/parquet/io/api/TestBinary.java @@ -18,12 +18,8 @@ */ package org.apache.parquet.io.api; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -31,7 +27,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import org.apache.parquet.io.ParquetEncodingException; @@ -85,7 +80,7 @@ public BinaryAndOriginal get(byte[] bytes, boolean reused) throws Exception { } else { b = Binary.fromConstantByteArray(orig, 5, bytes.length); } - assertArrayEquals(bytes, b.getBytes()); + assertThat(b.getBytes()).isEqualTo(bytes); return new BinaryAndOriginal(b, orig); } }; @@ -104,7 +99,7 @@ public BinaryAndOriginal get(byte[] bytes, boolean reused) throws Exception { } buff.mark(); - assertArrayEquals(bytes, b.getBytes()); + assertThat(b.getBytes()).isEqualTo(bytes); buff.reset(); return new BinaryAndOriginal(b, orig); } @@ -124,7 +119,7 @@ public BinaryAndOriginal get(byte[] bytes, boolean reused) throws Exception { b = Binary.fromConstantByteBuffer(direct); } - assertArrayEquals(bytes, b.getBytes()); + assertThat(b.getBytes()).isEqualTo(bytes); // Return the backing byte[] so tests can mutate it, though for direct buffers // there is no accessible backing array. We return a copy of the original bytes. return new BinaryAndOriginal(b, bytes); @@ -198,9 +193,11 @@ public void testDirectByteBufferCopyAlwaysMaterializesToHeap() throws Exception Binary copy = binary.copy(); // The copy must NOT be the same object, even though the binary is constant - assertNotSame("copy() of a direct ByteBuffer-backed constant Binary must not return 'this'", binary, copy); - assertArrayEquals(data, copy.getBytes()); - assertArrayEquals(data, copy.getBytesUnsafe()); + assertThat(copy) + .as("copy() of a direct ByteBuffer-backed constant Binary must not return 'this'") + .isNotSameAs(binary); + assertThat(copy.getBytes()).isEqualTo(data); + assertThat(copy.getBytesUnsafe()).isEqualTo(data); } @Test @@ -222,8 +219,8 @@ public void testDirectByteBufferCopyIsIndependentOfOriginalBuffer() throws Excep } // The copy should still hold the original data - assertArrayEquals(data, copy.getBytes()); - assertArrayEquals(data, copy.getBytesUnsafe()); + assertThat(copy.getBytes()).isEqualTo(data); + assertThat(copy.getBytesUnsafe()).isEqualTo(data); } @Test @@ -235,14 +232,16 @@ public void testHeapByteBufferConstantCopyReturnsSame() throws Exception { Binary binary = Binary.fromConstantByteBuffer(heap); Binary copy = binary.copy(); - assertSame("copy() of a heap ByteBuffer-backed constant Binary should return 'this'", binary, copy); + assertThat(copy) + .as("copy() of a heap ByteBuffer-backed constant Binary should return 'this'") + .isSameAs(binary); } @Test public void testEqualityMethods() throws Exception { Binary bin1 = Binary.fromConstantByteArray("alice".getBytes(), 1, 3); Binary bin2 = Binary.fromConstantByteBuffer(ByteBuffer.wrap("alice".getBytes(), 1, 3)); - assertEquals(bin1, bin2); + assertThat(bin2).isEqualTo(bin1); } @Test @@ -258,7 +257,7 @@ public void testWriteAllTo() throws Exception { private void testWriteAllToHelper(Binary binary, byte[] orig) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(orig.length); binary.writeTo(out); - assertArrayEquals(orig, out.toByteArray()); + assertThat(out.toByteArray()).isEqualTo(orig); } @Test @@ -269,48 +268,46 @@ public void testFromStringBinary() throws Exception { private void testSlice(BinaryFactory bf, boolean reused) throws Exception { BinaryAndOriginal bao = bf.get(testString.getBytes(UTF8), reused); - assertArrayEquals( - testString.getBytes(UTF8), - bao.binary.slice(0, testString.length()).getBytesUnsafe()); - assertArrayEquals("123".getBytes(UTF8), bao.binary.slice(5, 3).getBytesUnsafe()); + assertThat(bao.binary.slice(0, testString.length()).getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.slice(5, 3).getBytesUnsafe()).isEqualTo("123".getBytes(UTF8)); } private void testConstantCopy(BinaryFactory bf) throws Exception { BinaryAndOriginal bao = bf.get(testString.getBytes(UTF8), false); - assertEquals(false, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isFalse(); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytes()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytes()); + assertThat(bao.binary.getBytes()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytes()).isEqualTo(testString.getBytes(UTF8)); bao = bf.get(testString.getBytes(UTF8), false); - assertEquals(false, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isFalse(); Binary copy = bao.binary.copy(); - assertSame(copy, bao.binary); + assertThat(bao.binary).isSameAs(copy); } private void testReusedCopy(BinaryFactory bf) throws Exception { BinaryAndOriginal bao = bf.get(testString.getBytes(UTF8), true); - assertEquals(true, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isTrue(); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytes()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytes()); + assertThat(bao.binary.getBytes()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytes()).isEqualTo(testString.getBytes(UTF8)); bao = bf.get(testString.getBytes(UTF8), true); - assertEquals(true, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isTrue(); Binary copy = bao.binary.copy(); mutate(bao.original); - assertArrayEquals(testString.getBytes(UTF8), copy.getBytes()); - assertArrayEquals(testString.getBytes(UTF8), copy.getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), copy.copy().getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), copy.copy().getBytes()); + assertThat(copy.getBytes()).isEqualTo(testString.getBytes(UTF8)); + assertThat(copy.getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(copy.copy().getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(copy.copy().getBytes()).isEqualTo(testString.getBytes(UTF8)); } /** @@ -320,22 +317,22 @@ private void testReusedCopy(BinaryFactory bf) throws Exception { */ private void testDirectConstantCopy(BinaryFactory bf) throws Exception { BinaryAndOriginal bao = bf.get(testString.getBytes(UTF8), false); - assertEquals(false, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isFalse(); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytes()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytes()); + assertThat(bao.binary.getBytes()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytes()).isEqualTo(testString.getBytes(UTF8)); bao = bf.get(testString.getBytes(UTF8), false); - assertEquals(false, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isFalse(); Binary copy = bao.binary.copy(); // Direct ByteBuffer-backed constant Binary.copy() must NOT return 'this' - assertNotSame(copy, bao.binary); + assertThat(bao.binary).isNotSameAs(copy); // But the data must be equal - assertEquals(bao.binary, copy); + assertThat(copy).isEqualTo(bao.binary); } /** @@ -344,23 +341,23 @@ private void testDirectConstantCopy(BinaryFactory bf) throws Exception { */ private void testDirectReusedCopy(BinaryFactory bf) throws Exception { BinaryAndOriginal bao = bf.get(testString.getBytes(UTF8), true); - assertEquals(true, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isTrue(); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytes()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), bao.binary.copy().getBytes()); + assertThat(bao.binary.getBytes()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(bao.binary.copy().getBytes()).isEqualTo(testString.getBytes(UTF8)); bao = bf.get(testString.getBytes(UTF8), true); - assertEquals(true, bao.binary.isBackingBytesReused()); + assertThat(bao.binary.isBackingBytesReused()).isTrue(); Binary copy = bao.binary.copy(); - assertNotSame(copy, bao.binary); + assertThat(bao.binary).isNotSameAs(copy); - assertArrayEquals(testString.getBytes(UTF8), copy.getBytes()); - assertArrayEquals(testString.getBytes(UTF8), copy.getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), copy.copy().getBytesUnsafe()); - assertArrayEquals(testString.getBytes(UTF8), copy.copy().getBytes()); + assertThat(copy.getBytes()).isEqualTo(testString.getBytes(UTF8)); + assertThat(copy.getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(copy.copy().getBytesUnsafe()).isEqualTo(testString.getBytes(UTF8)); + assertThat(copy.copy().getBytes()).isEqualTo(testString.getBytes(UTF8)); } private void testSerializable(BinaryFactory bf, boolean reused) throws Exception { @@ -374,8 +371,8 @@ private void testSerializable(BinaryFactory bf, boolean reused) throws Exception ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); Object object = in.readObject(); - assertTrue(object instanceof Binary); - assertEquals(bao.binary, object); + assertThat(object).isInstanceOf(Binary.class); + assertThat(object).isEqualTo(bao.binary); } private void testBinary(BinaryFactory bf, boolean reused) throws Exception { @@ -397,62 +394,53 @@ public void testCompare() { Binary b3 = Binary.fromReusedByteArray("aaaaaaaaaaa".getBytes(), 1, 8); Binary b4 = Binary.fromConstantByteBuffer(ByteBuffer.wrap("aaaaaaac".getBytes())); - assertTrue(b1.compareTo(b2) < 0); - assertTrue(b2.compareTo(b1) > 0); - assertTrue(b3.compareTo(b4) < 0); - assertTrue(b4.compareTo(b3) > 0); - assertTrue(b1.compareTo(b4) < 0); - assertTrue(b4.compareTo(b1) > 0); - assertTrue(b2.compareTo(b4) < 0); - assertTrue(b4.compareTo(b2) > 0); - - assertTrue(b1.compareTo(b3) == 0); - assertTrue(b3.compareTo(b1) == 0); + assertThat(b1).isLessThan(b2); + assertThat(b2).isGreaterThan(b1); + assertThat(b3).isLessThan(b4); + assertThat(b4).isGreaterThan(b3); + assertThat(b1).isLessThan(b4); + assertThat(b4).isGreaterThan(b1); + assertThat(b2).isLessThan(b4); + assertThat(b4).isGreaterThan(b2); + + assertThat(b1).isEqualByComparingTo(b3); + assertThat(b3).isEqualByComparingTo(b1); } @Test public void testGet2BytesLittleEndian() { // ByteBufferBackedBinary: get2BytesLittleEndian Binary b1 = Binary.fromConstantByteBuffer(ByteBuffer.wrap(new byte[] {0x01, 0x02})); - assertEquals((short) 0x0201, b1.get2BytesLittleEndian()); + assertThat(b1.get2BytesLittleEndian()).isEqualTo((short) 0x0201); // ByteArrayBackedBinary: get2BytesLittleEndian Binary b2 = Binary.fromConstantByteArray(new byte[] {0x01, 0x02}); - assertEquals((short) 0x0201, b2.get2BytesLittleEndian()); + assertThat(b2.get2BytesLittleEndian()).isEqualTo((short) 0x0201); // ByteArraySliceBackedBinary: get2BytesLittleEndian Binary b3 = Binary.fromConstantByteArray(new byte[] {0x00, 0x01, 0x02, 0x03}, 1, 2); - assertEquals((short) 0x0201, b3.get2BytesLittleEndian()); + assertThat(b3.get2BytesLittleEndian()).isEqualTo((short) 0x0201); } @Test public void testGet2BytesLittleEndianWrongLength() { // ByteBufferBackedBinary: get2BytesLittleEndian Binary b1 = Binary.fromConstantByteBuffer(ByteBuffer.wrap(new byte[] {0x01, 0x02, 0x03})); - try { - b1.get2BytesLittleEndian(); - fail("Should have thrown an exception"); - } catch (IllegalArgumentException e) { - // expected - } + assertThatThrownBy(() -> b1.get2BytesLittleEndian()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("length must be 2"); // ByteArrayBackedBinary: get2BytesLittleEndian Binary b2 = Binary.fromConstantByteArray(new byte[] {0x01, 0x02, 0x03}); - try { - b2.get2BytesLittleEndian(); - fail("Should have thrown an exception"); - } catch (IllegalArgumentException e) { - // expected - } + assertThatThrownBy(() -> b2.get2BytesLittleEndian()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("length must be 2"); // ByteArraySliceBackedBinary: get2BytesLittleEndian Binary b3 = Binary.fromConstantByteArray(new byte[] {0x00, 0x01, 0x02, 0x03}, 1, 3); - try { - b3.get2BytesLittleEndian(); - fail("Should have thrown an exception"); - } catch (IllegalArgumentException e) { - // expected - } + assertThatThrownBy(() -> b3.get2BytesLittleEndian()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("length must be 2"); } @Test @@ -468,7 +456,7 @@ private static void assertFromCharSequenceEncodesUtf8(String value) { // For valid input the strict encoder must match String#getBytes(UTF_8), so this is a genuine // cross-check, not a circular assertion. Binary binary = Binary.fromCharSequence(new StringBuilder(value)); - assertArrayEquals(value.getBytes(StandardCharsets.UTF_8), binary.getBytes()); + assertThat(binary.getBytes()).isEqualTo(value.getBytes(StandardCharsets.UTF_8)); } @Test @@ -476,14 +464,8 @@ public void testFromCharSequenceRejectsMalformedUtf16() { // An unpaired high surrogate is invalid UTF-16. FromCharSequenceBinary must fail fast // rather than silently substituting a replacement byte (as String#getBytes(UTF_8) would). CharSequence value = new StringBuilder().append('a').append('\uD800').append('b'); - try { - Binary.fromCharSequence(value); - fail("Should have thrown an exception for malformed UTF-16 input"); - } catch (ParquetEncodingException e) { - // Lock in that the cause is a UTF-8 coding error, not an unrelated failure of the same type. - assertTrue( - "expected a CharacterCodingException cause but was " + e.getCause(), - e.getCause() instanceof CharacterCodingException); - } + assertThatThrownBy(() -> Binary.fromCharSequence(value)) + .isInstanceOf(ParquetEncodingException.class) + .hasMessage("Failed to encode CharSequence as UTF-8."); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/parser/TestParquetParser.java b/parquet-column/src/test/java/org/apache/parquet/parser/TestParquetParser.java index 5172e788b5..99a8f3ef25 100644 --- a/parquet-column/src/test/java/org/apache/parquet/parser/TestParquetParser.java +++ b/parquet-column/src/test/java/org/apache/parquet/parser/TestParquetParser.java @@ -52,7 +52,7 @@ import static org.apache.parquet.schema.Type.Repetition.REPEATED; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; import static org.apache.parquet.schema.Types.buildMessage; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.apache.parquet.schema.GroupType; import org.apache.parquet.schema.LogicalTypeAnnotation; @@ -95,11 +95,11 @@ public void testPaperExample() { new PrimitiveType(REQUIRED, BINARY, "Code"), new PrimitiveType(REQUIRED, BINARY, "Country")), new PrimitiveType(OPTIONAL, BINARY, "Url"))); - assertEquals(manuallyMade, parsed); + assertThat(parsed).isEqualTo(manuallyMade); MessageType parsedThenReparsed = parseMessageType(parsed.toString()); - assertEquals(manuallyMade, parsedThenReparsed); + assertThat(parsedThenReparsed).isEqualTo(manuallyMade); parsed = parseMessageType( "message m { required group a {required binary b;} required group c { required int64 d; }}"); @@ -108,11 +108,11 @@ public void testPaperExample() { new GroupType(REQUIRED, "a", new PrimitiveType(REQUIRED, BINARY, "b")), new GroupType(REQUIRED, "c", new PrimitiveType(REQUIRED, INT64, "d"))); - assertEquals(manuallyMade, parsed); + assertThat(parsed).isEqualTo(manuallyMade); parsedThenReparsed = parseMessageType(parsed.toString()); - assertEquals(manuallyMade, parsedThenReparsed); + assertThat(parsedThenReparsed).isEqualTo(manuallyMade); } @Test @@ -139,9 +139,9 @@ public void testEachPrimitiveType() { MessageType parsed = parseMessageType(schema.toString()); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -152,9 +152,9 @@ public void testSTRINGAnnotation() { MessageType expected = buildMessage().required(BINARY).as(stringType()).named("string").named("StringMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -165,9 +165,9 @@ public void testUTF8Annotation() { MessageType expected = buildMessage().required(BINARY).as(UTF8).named("string").named("StringMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -195,9 +195,9 @@ public void testIDs() { .named("s3") .named("Message"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -226,9 +226,9 @@ public void testMAPAnnotations() { .named("aMap") .named("Message"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -249,9 +249,9 @@ public void testLISTAnnotation() { .named("aList") .named("Message"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -269,9 +269,9 @@ public void testDecimalFixedAnnotation() { .named("aDecimal") .named("DecimalMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -287,9 +287,9 @@ public void testDecimalBinaryAnnotation() { .named("aDecimal") .named("DecimalMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -333,9 +333,9 @@ public void testTimeAnnotations() { .named("nanoTimestamp") .named("TimeMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = MessageTypeParser.parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -378,9 +378,9 @@ public void testIntAnnotations() { .named("u64") .named("IntMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = MessageTypeParser.parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -423,9 +423,9 @@ public void testIntegerAnnotations() { .named("u64") .named("IntMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = MessageTypeParser.parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -444,9 +444,9 @@ public void testEmbeddedAnnotations() { .named("bson") .named("EmbeddedMessage"); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = MessageTypeParser.parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } @Test @@ -470,8 +470,8 @@ public void testVARIANTAnnotation() { MessageType parsed = parseMessageType(message); - assertEquals(expected, parsed); + assertThat(parsed).isEqualTo(expected); MessageType reparsed = parseMessageType(parsed.toString()); - assertEquals(expected, reparsed); + assertThat(reparsed).isEqualTo(expected); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestFloat16.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestFloat16.java index 1c3a30f234..aba2cb9e5a 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestFloat16.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestFloat16.java @@ -19,9 +19,8 @@ package org.apache.parquet.schema; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.data.Offset.offset; import org.apache.parquet.io.api.Binary; import org.junit.Test; @@ -47,236 +46,193 @@ public class TestFloat16 { @Test public void testFloat16ToFloat() { // Zeroes - assertEquals(0.0f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {0x00, 0x00})), 0.0f); - assertEquals(-0.0f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x80})), 0.0f); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {0x00, 0x00}))) + .isCloseTo(0.0f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x80}))) + .isCloseTo(-0.0f, offset(0.0f)); // NaN - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xc0, (byte) 0x7f})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x7e})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x7f})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xfe})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xff})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x7f, (byte) 0x7e})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x7f, (byte) 0xfe})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0xfe})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x7f})), 0.0f); - assertEquals( - Float.NaN, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0xff})), 0.0f); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xc0, (byte) 0x7f}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x7e}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x7f}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xfe}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xff}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x7f, (byte) 0x7e}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x7f, (byte) 0xfe}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0xfe}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x7f}))) + .isCloseTo(Float.NaN, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0xff}))) + .isCloseTo(Float.NaN, offset(0.0f)); // infinities - assertEquals( - Float.POSITIVE_INFINITY, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x7c})), - 0.0f); - assertEquals( - Float.NEGATIVE_INFINITY, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xfc})), - 0.0f); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x7c}))) + .isCloseTo(Float.POSITIVE_INFINITY, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xfc}))) + .isCloseTo(Float.NEGATIVE_INFINITY, offset(0.0f)); // subnormals - assertEquals( - 5.9604645E-8f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x00})), - 0.0f); - assertEquals( - -65504.0f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0xfb})), 0.0f); - assertEquals( - +65504.0f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x7b})), 0.0f); - assertEquals( - -6.097555E-5f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x83})), - 0.0f); - assertEquals( - -5.9604645E-8f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x80})), - 0.0f); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x00}))) + .isCloseTo(5.9604645E-8f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0xfb}))) + .isCloseTo(-65504.0f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x7b}))) + .isCloseTo(+65504.0f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x83}))) + .isCloseTo(-6.097555E-5f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x80}))) + .isCloseTo(-5.9604645E-8f, offset(0.0f)); // Known values - assertEquals( - 1.0009765625f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x3c})), - 0.0f); - assertEquals(-2.0f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xc0})), 0.0f); - assertEquals( - 6.1035156e-5f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x04})), - 0.0f); // Inexact - assertEquals( - 65504.0f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x7b})), 0.0f); - assertEquals( - 0.33325195f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x55, (byte) 0x35})), - 0.0f); // Inexact + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x3c}))) + .isCloseTo(1.0009765625f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0xc0}))) + .isCloseTo(-2.0f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x00, (byte) 0x04}))) + .isCloseTo(6.1035156e-5f, offset(0.0f)); // Inexact + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x7b}))) + .isCloseTo(65504.0f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x55, (byte) 0x35}))) + .isCloseTo(0.33325195f, offset(0.0f)); // Inexact // Denormals (flushed to +/-0) - assertEquals( - 6.097555e-5f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x03})), - 0.0f); - assertEquals( - 5.9604645e-8f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x00})), - 0.0f); // Inexact - assertEquals( - -6.097555e-5f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x83})), - 0.0f); - assertEquals( - -5.9604645e-8f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x80})), - 0.0f); // Inexact + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x03}))) + .isCloseTo(6.097555e-5f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x00}))) + .isCloseTo(5.9604645e-8f, offset(0.0f)); // Inexact + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0xff, (byte) 0x83}))) + .isCloseTo(-6.097555e-5f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x01, (byte) 0x80}))) + .isCloseTo(-5.9604645e-8f, offset(0.0f)); // Inexact // Miscellaneous values. In general, they're chosen to test the sign/exponent and // exponent/mantissa boundaries - assertEquals( - +0.00050163269043f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x10})), - 0.0f); - assertEquals( - -0.00050163269043f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x90})), - 0.0f); - assertEquals( - +0.000502109527588f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1d, (byte) 0x10})), - 0.0f); - assertEquals( - -0.000502109527588f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1d, (byte) 0x90})), - 0.0f); - assertEquals( - +0.00074577331543f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x12})), - 0.0f); - assertEquals( - -0.00074577331543f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x92})), - 0.0f); - assertEquals( - +0.00100326538086f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x14})), - 0.0f); - assertEquals( - -0.00100326538086f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x94})), - 0.0f); - assertEquals( - +32.875f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x50})), 0.0f); - assertEquals( - -32.875f, Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0xd0})), 0.0f); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x10}))) + .isCloseTo(+0.00050163269043f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x90}))) + .isCloseTo(-0.00050163269043f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1d, (byte) 0x10}))) + .isCloseTo(+0.000502109527588f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1d, (byte) 0x90}))) + .isCloseTo(-0.000502109527588f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x12}))) + .isCloseTo(+0.00074577331543f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x92}))) + .isCloseTo(-0.00074577331543f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x14}))) + .isCloseTo(+0.00100326538086f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x94}))) + .isCloseTo(-0.00100326538086f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x50}))) + .isCloseTo(+32.875f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0xd0}))) + .isCloseTo(-32.875f, offset(0.0f)); // A few subnormals for good measure - assertEquals( - +1.66893005371e-06f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x00})), - 0.0f); - assertEquals( - -1.66893005371e-06f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x80})), - 0.0f); - assertEquals( - +3.21865081787e-05f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x02})), - 0.0f); - assertEquals( - -3.21865081787e-05f, - Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x82})), - 0.0f); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x00}))) + .isCloseTo(+1.66893005371e-06f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x80}))) + .isCloseTo(-1.66893005371e-06f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x02}))) + .isCloseTo(+3.21865081787e-05f, offset(0.0f)); + assertThat(Float16.toFloat(Binary.fromConstantByteArray(new byte[] {(byte) 0x1c, (byte) 0x82}))) + .isCloseTo(-3.21865081787e-05f, offset(0.0f)); } @Test public void testFloatToFloat16() { // Zeroes, NaN and infinities - assertEquals(POSITIVE_ZERO, Float16.toFloat16(0.0f)); - assertEquals(NEGATIVE_ZERO, Float16.toFloat16(-0.0f)); - assertEquals(NaN, Float16.toFloat16(Float.NaN)); - assertEquals(POSITIVE_INFINITY, Float16.toFloat16(Float.POSITIVE_INFINITY)); - assertEquals(NEGATIVE_INFINITY, Float16.toFloat16(Float.NEGATIVE_INFINITY)); + assertThat(Float16.toFloat16(0.0f)).isEqualTo(POSITIVE_ZERO); + assertThat(Float16.toFloat16(-0.0f)).isEqualTo(NEGATIVE_ZERO); + assertThat(Float16.toFloat16(Float.NaN)).isEqualTo(NaN); + assertThat(Float16.toFloat16(Float.POSITIVE_INFINITY)).isEqualTo(POSITIVE_INFINITY); + assertThat(Float16.toFloat16(Float.NEGATIVE_INFINITY)).isEqualTo(NEGATIVE_INFINITY); // Known values - assertEquals((short) 0x3c01, Float16.toFloat16(1.0009765625f)); - assertEquals((short) 0xc000, Float16.toFloat16(-2.0f)); - assertEquals((short) 0x0400, Float16.toFloat16(6.10352e-5f)); - assertEquals((short) 0x7bff, Float16.toFloat16(65504.0f)); - assertEquals((short) 0x3555, Float16.toFloat16(1.0f / 3.0f)); + assertThat(Float16.toFloat16(1.0009765625f)).isEqualTo((short) 0x3c01); + assertThat(Float16.toFloat16(-2.0f)).isEqualTo((short) 0xc000); + assertThat(Float16.toFloat16(6.10352e-5f)).isEqualTo((short) 0x0400); + assertThat(Float16.toFloat16(65504.0f)).isEqualTo((short) 0x7bff); + assertThat(Float16.toFloat16(1.0f / 3.0f)).isEqualTo((short) 0x3555); // Subnormals - assertEquals((short) 0x03ff, Float16.toFloat16(6.09756e-5f)); - assertEquals(MIN_VALUE, Float16.toFloat16(5.96046e-8f)); - assertEquals((short) 0x83ff, Float16.toFloat16(-6.09756e-5f)); - assertEquals((short) 0x8001, Float16.toFloat16(-5.96046e-8f)); + assertThat(Float16.toFloat16(6.09756e-5f)).isEqualTo((short) 0x03ff); + assertThat(Float16.toFloat16(5.96046e-8f)).isEqualTo(MIN_VALUE); + assertThat(Float16.toFloat16(-6.09756e-5f)).isEqualTo((short) 0x83ff); + assertThat(Float16.toFloat16(-5.96046e-8f)).isEqualTo((short) 0x8001); // Subnormals (flushed to +/-0) - assertEquals(POSITIVE_ZERO, Float16.toFloat16(5.96046e-9f)); - assertEquals(NEGATIVE_ZERO, Float16.toFloat16(-5.96046e-9f)); + assertThat(Float16.toFloat16(5.96046e-9f)).isEqualTo(POSITIVE_ZERO); + assertThat(Float16.toFloat16(-5.96046e-9f)).isEqualTo(NEGATIVE_ZERO); // Test for values that overflow the mantissa bits into exp bits - assertEquals((short) 0x1000, Float16.toFloat16(Float.intBitsToFloat(0x39fff000))); - assertEquals((short) 0x0400, Float16.toFloat16(Float.intBitsToFloat(0x387fe000))); + assertThat(Float16.toFloat16(Float.intBitsToFloat(0x39fff000))).isEqualTo((short) 0x1000); + assertThat(Float16.toFloat16(Float.intBitsToFloat(0x387fe000))).isEqualTo((short) 0x0400); // Floats with absolute value above +/-65519 are rounded to +/-inf // when using round-to-even - assertEquals((short) 0x7bff, Float16.toFloat16(65519.0f)); - assertEquals((short) 0x7bff, Float16.toFloat16(65519.9f)); - assertEquals(POSITIVE_INFINITY, Float16.toFloat16(65520.0f)); - assertEquals(NEGATIVE_INFINITY, Float16.toFloat16(-65520.0f)); + assertThat(Float16.toFloat16(65519.0f)).isEqualTo((short) 0x7bff); + assertThat(Float16.toFloat16(65519.9f)).isEqualTo((short) 0x7bff); + assertThat(Float16.toFloat16(65520.0f)).isEqualTo(POSITIVE_INFINITY); + assertThat(Float16.toFloat16(-65520.0f)).isEqualTo(NEGATIVE_INFINITY); // Check if numbers are rounded to nearest even when they // cannot be accurately represented by Half - assertEquals((short) 0x6800, Float16.toFloat16(2049.0f)); - assertEquals((short) 0x6c00, Float16.toFloat16(4098.0f)); - assertEquals((short) 0x7000, Float16.toFloat16(8196.0f)); - assertEquals((short) 0x7400, Float16.toFloat16(16392.0f)); - assertEquals((short) 0x7800, Float16.toFloat16(32784.0f)); + assertThat(Float16.toFloat16(2049.0f)).isEqualTo((short) 0x6800); + assertThat(Float16.toFloat16(4098.0f)).isEqualTo((short) 0x6c00); + assertThat(Float16.toFloat16(8196.0f)).isEqualTo((short) 0x7000); + assertThat(Float16.toFloat16(16392.0f)).isEqualTo((short) 0x7400); + assertThat(Float16.toFloat16(32784.0f)).isEqualTo((short) 0x7800); // Miscellaneous values. In general, they're chosen to test the sign/exponent and // exponent/mantissa boundaries - assertEquals((short) 0x101c, Float16.toFloat16(+0.00050163269043f)); - assertEquals((short) 0x901c, Float16.toFloat16(-0.00050163269043f)); - assertEquals((short) 0x101d, Float16.toFloat16(+0.000502109527588f)); - assertEquals((short) 0x901d, Float16.toFloat16(-0.000502109527588f)); - assertEquals((short) 0x121c, Float16.toFloat16(+0.00074577331543f)); - assertEquals((short) 0x921c, Float16.toFloat16(-0.00074577331543f)); - assertEquals((short) 0x141c, Float16.toFloat16(+0.00100326538086f)); - assertEquals((short) 0x941c, Float16.toFloat16(-0.00100326538086f)); - assertEquals((short) 0x501c, Float16.toFloat16(+32.875f)); - assertEquals((short) 0xd01c, Float16.toFloat16(-32.875f)); + assertThat(Float16.toFloat16(+0.00050163269043f)).isEqualTo((short) 0x101c); + assertThat(Float16.toFloat16(-0.00050163269043f)).isEqualTo((short) 0x901c); + assertThat(Float16.toFloat16(+0.000502109527588f)).isEqualTo((short) 0x101d); + assertThat(Float16.toFloat16(-0.000502109527588f)).isEqualTo((short) 0x901d); + assertThat(Float16.toFloat16(+0.00074577331543f)).isEqualTo((short) 0x121c); + assertThat(Float16.toFloat16(-0.00074577331543f)).isEqualTo((short) 0x921c); + assertThat(Float16.toFloat16(+0.00100326538086f)).isEqualTo((short) 0x141c); + assertThat(Float16.toFloat16(-0.00100326538086f)).isEqualTo((short) 0x941c); + assertThat(Float16.toFloat16(+32.875f)).isEqualTo((short) 0x501c); + assertThat(Float16.toFloat16(-32.875f)).isEqualTo((short) 0xd01c); // A few subnormals for good measure - assertEquals((short) 0x001c, Float16.toFloat16(+1.66893005371e-06f)); - assertEquals((short) 0x801c, Float16.toFloat16(-1.66893005371e-06f)); - assertEquals((short) 0x021c, Float16.toFloat16(+3.21865081787e-05f)); - assertEquals((short) 0x821c, Float16.toFloat16(-3.21865081787e-05f)); + assertThat(Float16.toFloat16(+1.66893005371e-06f)).isEqualTo((short) 0x001c); + assertThat(Float16.toFloat16(-1.66893005371e-06f)).isEqualTo((short) 0x801c); + assertThat(Float16.toFloat16(+3.21865081787e-05f)).isEqualTo((short) 0x021c); + assertThat(Float16.toFloat16(-3.21865081787e-05f)).isEqualTo((short) 0x821c); } @Test public void testIsNaN() { - assertFalse(Float16.isNaN(POSITIVE_INFINITY)); - assertFalse(Float16.isNaN(NEGATIVE_INFINITY)); - assertFalse(Float16.isNaN(POSITIVE_ZERO)); - assertFalse(Float16.isNaN(NEGATIVE_ZERO)); - assertTrue(Float16.isNaN(NaN)); - assertTrue(Float16.isNaN((short) 0x7c01)); - assertTrue(Float16.isNaN((short) 0x7c18)); - assertTrue(Float16.isNaN((short) 0xfc01)); - assertTrue(Float16.isNaN((short) 0xfc98)); - assertFalse(Float16.isNaN(MAX_VALUE)); - assertFalse(Float16.isNaN(LOWEST_VALUE)); - assertFalse(Float16.isNaN(Float16.toFloat16(-128.3f))); - assertFalse(Float16.isNaN(Float16.toFloat16(128.3f))); + assertThat(Float16.isNaN(POSITIVE_INFINITY)).isFalse(); + assertThat(Float16.isNaN(NEGATIVE_INFINITY)).isFalse(); + assertThat(Float16.isNaN(POSITIVE_ZERO)).isFalse(); + assertThat(Float16.isNaN(NEGATIVE_ZERO)).isFalse(); + assertThat(Float16.isNaN(NaN)).isTrue(); + assertThat(Float16.isNaN((short) 0x7c01)).isTrue(); + assertThat(Float16.isNaN((short) 0x7c18)).isTrue(); + assertThat(Float16.isNaN((short) 0xfc01)).isTrue(); + assertThat(Float16.isNaN((short) 0xfc98)).isTrue(); + assertThat(Float16.isNaN(MAX_VALUE)).isFalse(); + assertThat(Float16.isNaN(LOWEST_VALUE)).isFalse(); + assertThat(Float16.isNaN(Float16.toFloat16(-128.3f))).isFalse(); + assertThat(Float16.isNaN(Float16.toFloat16(128.3f))).isFalse(); } @Test public void testCompare() { - assertEquals(0, Float16.compare(NaN, NaN)); - assertEquals(0, Float16.compare(NaN, (short) 0xfc98)); - assertEquals(1, Float16.compare(NaN, POSITIVE_INFINITY)); - assertEquals(-1, Float16.compare(POSITIVE_INFINITY, NaN)); - assertEquals(0, Float16.compare(POSITIVE_INFINITY, POSITIVE_INFINITY)); - assertEquals(0, Float16.compare(NEGATIVE_INFINITY, NEGATIVE_INFINITY)); - assertEquals(1, Float16.compare(POSITIVE_INFINITY, NEGATIVE_INFINITY)); - assertEquals(-1, Float16.compare(NEGATIVE_INFINITY, POSITIVE_INFINITY)); - assertEquals(0, Float16.compare(POSITIVE_ZERO, POSITIVE_ZERO)); - assertEquals(0, Float16.compare(NEGATIVE_ZERO, NEGATIVE_ZERO)); - assertEquals(1, Float16.compare(POSITIVE_ZERO, NEGATIVE_ZERO)); - assertEquals(-1, Float16.compare(NEGATIVE_ZERO, POSITIVE_ZERO)); - assertEquals(0, Float16.compare(Float16.toFloat16(12.462f), Float16.toFloat16(12.462f))); - assertEquals(0, Float16.compare(Float16.toFloat16(-12.462f), Float16.toFloat16(-12.462f))); - assertEquals(1, Float16.compare(Float16.toFloat16(12.462f), Float16.toFloat16(-12.462f))); - assertEquals(-1, Float16.compare(Float16.toFloat16(-12.462f), Float16.toFloat16(12.462f))); + assertThat(Float16.compare(NaN, NaN)).isZero(); + assertThat(Float16.compare(NaN, (short) 0xfc98)).isZero(); + assertThat(Float16.compare(NaN, POSITIVE_INFINITY)).isPositive(); + assertThat(Float16.compare(POSITIVE_INFINITY, NaN)).isNegative(); + assertThat(Float16.compare(POSITIVE_INFINITY, POSITIVE_INFINITY)).isZero(); + assertThat(Float16.compare(NEGATIVE_INFINITY, NEGATIVE_INFINITY)).isZero(); + assertThat(Float16.compare(POSITIVE_INFINITY, NEGATIVE_INFINITY)).isPositive(); + assertThat(Float16.compare(NEGATIVE_INFINITY, POSITIVE_INFINITY)).isNegative(); + assertThat(Float16.compare(POSITIVE_ZERO, POSITIVE_ZERO)).isZero(); + assertThat(Float16.compare(NEGATIVE_ZERO, NEGATIVE_ZERO)).isZero(); + assertThat(Float16.compare(POSITIVE_ZERO, NEGATIVE_ZERO)).isPositive(); + assertThat(Float16.compare(NEGATIVE_ZERO, POSITIVE_ZERO)).isNegative(); + short twelve = Float16.toFloat16(12.462f); + short minusTwelve = Float16.toFloat16(-12.462f); + assertThat(Float16.compare(twelve, twelve)).isZero(); + assertThat(Float16.compare(minusTwelve, minusTwelve)).isZero(); + assertThat(Float16.compare(twelve, minusTwelve)).isPositive(); + assertThat(Float16.compare(minusTwelve, twelve)).isNegative(); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestMessageType.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestMessageType.java index ac4d099ee3..c1da639cb8 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestMessageType.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestMessageType.java @@ -26,9 +26,8 @@ import static org.apache.parquet.schema.Type.Repetition.OPTIONAL; import static org.apache.parquet.schema.Type.Repetition.REPEATED; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.apache.parquet.example.Paper; import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; @@ -38,21 +37,21 @@ public class TestMessageType { @Test public void test() throws Exception { MessageType schema = MessageTypeParser.parseMessageType(Paper.schema.toString()); - assertEquals(Paper.schema, schema); - assertEquals(schema.toString(), Paper.schema.toString()); + assertThat(schema).isEqualTo(Paper.schema); + assertThat(schema).asString().isEqualTo(Paper.schema.toString()); } @Test public void testNestedTypes() { MessageType schema = MessageTypeParser.parseMessageType(Paper.schema.toString()); Type type = schema.getType("Links", "Backward"); - assertEquals(PrimitiveTypeName.INT64, type.asPrimitiveType().getPrimitiveTypeName()); - assertEquals(0, schema.getMaxRepetitionLevel("DocId")); - assertEquals(1, schema.getMaxRepetitionLevel("Name")); - assertEquals(2, schema.getMaxRepetitionLevel("Name", "Language")); - assertEquals(0, schema.getMaxDefinitionLevel("DocId")); - assertEquals(1, schema.getMaxDefinitionLevel("Links")); - assertEquals(2, schema.getMaxDefinitionLevel("Links", "Backward")); + assertThat(type.asPrimitiveType().getPrimitiveTypeName()).isEqualTo(PrimitiveTypeName.INT64); + assertThat(schema.getMaxRepetitionLevel("DocId")).isEqualTo(0); + assertThat(schema.getMaxRepetitionLevel("Name")).isEqualTo(1); + assertThat(schema.getMaxRepetitionLevel("Name", "Language")).isEqualTo(2); + assertThat(schema.getMaxDefinitionLevel("DocId")).isEqualTo(0); + assertThat(schema.getMaxDefinitionLevel("Links")).isEqualTo(1); + assertThat(schema.getMaxDefinitionLevel("Links", "Backward")).isEqualTo(2); } @Test @@ -61,28 +60,28 @@ public void testMergeSchema() { "root1", new PrimitiveType(REPEATED, BINARY, "a"), new PrimitiveType(OPTIONAL, BINARY, "b")); MessageType t2 = new MessageType("root2", new PrimitiveType(REQUIRED, BINARY, "c")); - assertEquals( - t1.union(t2), - new MessageType( + assertThat(new MessageType( "root1", new PrimitiveType(REPEATED, BINARY, "a"), new PrimitiveType(OPTIONAL, BINARY, "b"), - new PrimitiveType(REQUIRED, BINARY, "c"))); + new PrimitiveType(REQUIRED, BINARY, "c"))) + .isEqualTo(t1.union(t2)); - assertEquals( - t2.union(t1), - new MessageType( + assertThat(new MessageType( "root2", new PrimitiveType(REQUIRED, BINARY, "c"), new PrimitiveType(REPEATED, BINARY, "a"), - new PrimitiveType(OPTIONAL, BINARY, "b"))); + new PrimitiveType(OPTIONAL, BINARY, "b"))) + .isEqualTo(t2.union(t1)); MessageType t3 = new MessageType("root1", new PrimitiveType(OPTIONAL, BINARY, "a")); MessageType t4 = new MessageType("root2", new PrimitiveType(REQUIRED, BINARY, "a")); - assertEquals(t3.union(t4), new MessageType("root1", new PrimitiveType(OPTIONAL, BINARY, "a"))); + assertThat(new MessageType("root1", new PrimitiveType(OPTIONAL, BINARY, "a"))) + .isEqualTo(t3.union(t4)); - assertEquals(t4.union(t3), new MessageType("root2", new PrimitiveType(OPTIONAL, BINARY, "a"))); + assertThat(new MessageType("root2", new PrimitiveType(OPTIONAL, BINARY, "a"))) + .isEqualTo(t4.union(t3)); MessageType t5 = new MessageType( "root1", @@ -97,38 +96,31 @@ public void testMergeSchema() { new GroupType(REQUIRED, "g3", new PrimitiveType(OPTIONAL, BINARY, "c")), new PrimitiveType(OPTIONAL, BINARY, "b"))); - assertEquals( - t5.union(t6), - new MessageType( + assertThat(new MessageType( "root1", new GroupType(REQUIRED, "g1", new PrimitiveType(OPTIONAL, BINARY, "a")), new GroupType( REQUIRED, "g2", new PrimitiveType(OPTIONAL, BINARY, "b"), - new GroupType(REQUIRED, "g3", new PrimitiveType(OPTIONAL, BINARY, "c"))))); + new GroupType(REQUIRED, "g3", new PrimitiveType(OPTIONAL, BINARY, "c"))))) + .isEqualTo(t5.union(t6)); MessageType t7 = new MessageType("root1", new PrimitiveType(OPTIONAL, BINARY, "a")); MessageType t8 = new MessageType("root2", new PrimitiveType(OPTIONAL, INT32, "a")); - try { - t7.union(t8); - fail("moving from BINARY to INT32"); - } catch (IncompatibleSchemaModificationException e) { - assertEquals("can not merge type optional int32 a into optional binary a", e.getMessage()); - } + assertThatThrownBy(() -> t7.union(t8)) + .isInstanceOf(IncompatibleSchemaModificationException.class) + .hasMessage("can not merge type optional int32 a into optional binary a"); MessageType t9 = Types.buildMessage() .addField(Types.optional(BINARY).as(OriginalType.UTF8).named("a")) .named("root1"); MessageType t10 = Types.buildMessage().addField(Types.optional(BINARY).named("a")).named("root1"); - assertEquals(t9.union(t9), t9); - try { - t9.union(t10); - fail("moving from BINARY (UTF8) to BINARY"); - } catch (IncompatibleSchemaModificationException e) { - assertEquals("cannot merge logical type null into STRING", e.getMessage()); - } + assertThat(t9).isEqualTo(t9.union(t9)); + assertThatThrownBy(() -> t9.union(t10)) + .isInstanceOf(IncompatibleSchemaModificationException.class) + .hasMessage("cannot merge logical type null into STRING"); MessageType t11 = Types.buildMessage() .addField(Types.optional(FIXED_LEN_BYTE_ARRAY).length(10).named("a")) @@ -136,14 +128,10 @@ public void testMergeSchema() { MessageType t12 = Types.buildMessage() .addField(Types.optional(FIXED_LEN_BYTE_ARRAY).length(20).named("a")) .named("root2"); - try { - t11.union(t12); - fail("moving from FIXED_LEN_BYTE_ARRAY(10) to FIXED_LEN_BYTE_ARRAY(20)"); - } catch (IncompatibleSchemaModificationException e) { - assertEquals( - "can not merge type optional fixed_len_byte_array(20) a into optional fixed_len_byte_array(10) a", - e.getMessage()); - } + assertThatThrownBy(() -> t11.union(t12)) + .isInstanceOf(IncompatibleSchemaModificationException.class) + .hasMessage( + "can not merge type optional fixed_len_byte_array(20) a into optional fixed_len_byte_array(10) a"); } @Test @@ -162,8 +150,8 @@ public void testMergeSchemaWithOriginalType() throws Exception { new GroupType(REQUIRED, "g3", new PrimitiveType(OPTIONAL, BINARY, "c")), new PrimitiveType(OPTIONAL, BINARY, "b"))); - assertEquals( - new MessageType( + assertThat(t5.union(t6)) + .isEqualTo(new MessageType( "root1", new GroupType(REQUIRED, "g1", LIST, new PrimitiveType(OPTIONAL, BINARY, "a")), new GroupType( @@ -171,8 +159,7 @@ public void testMergeSchemaWithOriginalType() throws Exception { "g2", LIST, new PrimitiveType(OPTIONAL, BINARY, "b"), - new GroupType(REQUIRED, "g3", new PrimitiveType(OPTIONAL, BINARY, "c")))), - t5.union(t6)); + new GroupType(REQUIRED, "g3", new PrimitiveType(OPTIONAL, BINARY, "c"))))); } @Test @@ -201,8 +188,8 @@ public void testMergeSchemaWithColumnOrder() { .named("g")) .named("root"); - assertEquals( - Types.buildMessage() + assertThat(m1.union(m2)) + .isEqualTo(Types.buildMessage() .addFields( Types.requiredList() .element(Types.optional(BINARY) @@ -211,30 +198,21 @@ public void testMergeSchemaWithColumnOrder() { .named("g"), Types.optional(INT96).named("b"), Types.optional(BINARY).named("c")) - .named("root"), - m1.union(m2)); - try { - m1.union(m3); - fail("An IncompatibleSchemaModificationException should have been thrown"); - } catch (Exception e) { - assertTrue( - "The thrown exception should have been IncompatibleSchemaModificationException but was " - + e.getClass(), - e instanceof IncompatibleSchemaModificationException); - assertEquals( - "can not merge type optional binary a with column order TYPE_DEFINED_ORDER into optional binary a with column order UNDEFINED", - e.getMessage()); - } + .named("root")); + assertThatThrownBy(() -> m1.union(m3)) + .isInstanceOf(IncompatibleSchemaModificationException.class) + .hasMessage( + "can not merge type optional binary a with column order TYPE_DEFINED_ORDER into optional binary a with column order UNDEFINED"); } @Test - public void testIDs() throws Exception { + public void testIDs() { MessageType schema = new MessageType( "test", new PrimitiveType(REQUIRED, BINARY, "foo").withId(4), new GroupType(REQUIRED, "bar", new PrimitiveType(REQUIRED, BINARY, "baz").withId(3)).withId(8)); MessageType schema2 = MessageTypeParser.parseMessageType(schema.toString()); - assertEquals(schema, schema2); - assertEquals(schema.toString(), schema2.toString()); + assertThat(schema2).isEqualTo(schema); + assertThat(schema2).asString().isEqualTo(schema.toString()); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveComparator.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveComparator.java index ec7425141e..32943835da 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveComparator.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveComparator.java @@ -31,12 +31,13 @@ import static org.apache.parquet.schema.PrimitiveComparator.UNSIGNED_INT32_COMPARATOR; import static org.apache.parquet.schema.PrimitiveComparator.UNSIGNED_INT64_COMPARATOR; import static org.apache.parquet.schema.PrimitiveComparator.UNSIGNED_LEXICOGRAPHICAL_BINARY_COMPARATOR; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import org.apache.parquet.io.api.Binary; import org.junit.Test; @@ -57,9 +58,10 @@ public void testBooleanComparator() { Boolean vi = valuesInAscendingOrder[i]; Boolean vj = valuesInAscendingOrder[j]; int exp = i - j; - assertSignumEquals(vi, vj, exp, BOOLEAN_COMPARATOR.compare(vi, vj)); + assertOrdering(vi, vj, exp, BOOLEAN_COMPARATOR); if (vi != null && vj != null) { - assertSignumEquals(vi, vj, exp, BOOLEAN_COMPARATOR.compare(vi.booleanValue(), vj.booleanValue())); + assertOrdering( + vi, vj, exp, (a, b) -> BOOLEAN_COMPARATOR.compare(a.booleanValue(), b.booleanValue())); } } } @@ -93,9 +95,9 @@ private void testInt32Comparator(PrimitiveComparator comparator, Intege Integer vi = valuesInAscendingOrder[i]; Integer vj = valuesInAscendingOrder[j]; int exp = i - j; - assertSignumEquals(vi, vj, exp, comparator.compare(vi, vj)); + assertOrdering(vi, vj, exp, comparator); if (vi != null && vj != null) { - assertSignumEquals(vi, vj, exp, comparator.compare(vi.intValue(), vj.intValue())); + assertOrdering(vi, vj, exp, (a, b) -> comparator.compare(a.intValue(), b.intValue())); } } } @@ -117,12 +119,10 @@ public void testUnknownLogicalTypeComparator() { }; for (PrimitiveType.PrimitiveTypeName type : types) { - assertEquals( - new PrimitiveType(Type.Repetition.REQUIRED, type, "vo") - .withLogicalTypeAnnotation(LogicalTypeAnnotation.unknownType()) - .comparator() - .compare(null, null), - 0); + Comparator comparator = new PrimitiveType(Type.Repetition.REQUIRED, type, "vo") + .withLogicalTypeAnnotation(LogicalTypeAnnotation.unknownType()) + .comparator(); + assertThat(comparator.compare(null, null)).isZero(); } } @@ -160,9 +160,9 @@ private void testInt64Comparator(PrimitiveComparator comparator, Long... v Long vi = valuesInAscendingOrder[i]; Long vj = valuesInAscendingOrder[j]; int exp = i - j; - assertSignumEquals(vi, vj, exp, comparator.compare(vi, vj)); + assertOrdering(vi, vj, exp, comparator); if (vi != null && vj != null) { - assertSignumEquals(vi, vj, exp, comparator.compare(vi.longValue(), vj.longValue())); + assertOrdering(vi, vj, exp, (a, b) -> comparator.compare(a.longValue(), b.longValue())); } } } @@ -176,9 +176,9 @@ private void testFloatComparator(PrimitiveComparator comparator, Float... Float vi = valuesInAscendingOrder[i]; Float vj = valuesInAscendingOrder[j]; int exp = i - j; - assertSignumEquals(vi, vj, exp, comparator.compare(vi, vj)); + assertOrdering(vi, vj, exp, comparator); if (vi != null && vj != null) { - assertSignumEquals(vi, vj, exp, comparator.compare(vi.floatValue(), vj.floatValue())); + assertOrdering(vi, vj, exp, (a, b) -> comparator.compare(a.floatValue(), b.floatValue())); } } } @@ -233,9 +233,9 @@ private void testDoubleComparator(PrimitiveComparator comparator, Double Double vi = valuesInAscendingOrder[i]; Double vj = valuesInAscendingOrder[j]; int exp = i - j; - assertSignumEquals(vi, vj, exp, comparator.compare(vi, vj)); + assertOrdering(vi, vj, exp, comparator); if (vi != null && vj != null) { - assertSignumEquals(vi, vj, exp, comparator.compare(vi.doubleValue(), vj.doubleValue())); + assertOrdering(vi, vj, exp, (a, b) -> comparator.compare(a.doubleValue(), b.doubleValue())); } } } @@ -346,10 +346,9 @@ public void testBinaryAsSignedIntegerComparatorWithEquals() { for (Binary v1 : valuesToCompare) { for (Binary v2 : valuesToCompare) { - assertEquals( - String.format("Wrong result of comparison %s and %s", v1, v2), - 0, - BINARY_AS_SIGNED_INTEGER_COMPARATOR.compare(v1, v2)); + assertThat(v1) + .usingComparator(BINARY_AS_SIGNED_INTEGER_COMPARATOR) + .isEqualTo(v2); } } } @@ -371,11 +370,12 @@ public void testFloat16Comparator() { for (int j = 0; j < valuesInAscendingOrder.length; ++j) { Binary bi = valuesInAscendingOrder[i]; Binary bj = valuesInAscendingOrder[j]; - float fi = Float16.toFloat(bi); - float fj = Float16.toFloat(bj); - assertEquals(Float.compare(fi, fj), BINARY_AS_FLOAT16_COMPARATOR.compare(bi, bj)); if (i < j) { - assertEquals(-1, Float.compare(fi, fj)); + assertThat(bi).usingComparator(BINARY_AS_FLOAT16_COMPARATOR).isLessThan(bj); + } else if (i > j) { + assertThat(bi).usingComparator(BINARY_AS_FLOAT16_COMPARATOR).isGreaterThan(bj); + } else { + assertThat(bi).usingComparator(BINARY_AS_FLOAT16_COMPARATOR).isEqualByComparingTo(bj); } } } @@ -404,7 +404,7 @@ public void testBinaryAsFloat16IEEE754TotalOrderComparator() { Binary vi = valuesInAscendingOrder[i]; Binary vj = valuesInAscendingOrder[j]; int exp = i - j; - assertSignumEquals(vi, vj, exp, BINARY_AS_FLOAT16_IEEE_754_TOTAL_ORDER_COMPARATOR.compare(vi, vj)); + assertOrdering(vi, vj, exp, BINARY_AS_FLOAT16_IEEE_754_TOTAL_ORDER_COMPARATOR); } } } @@ -415,57 +415,51 @@ private void testObjectComparator(PrimitiveComparator comparator, T... va T vi = valuesInAscendingOrder[i]; T vj = valuesInAscendingOrder[j]; int exp = i - j; - assertSignumEquals(vi, vj, exp, comparator.compare(vi, vj)); + assertOrdering(vi, vj, exp, comparator); } } checkThrowingUnsupportedException(comparator, null); } - private void assertSignumEquals(T v1, T v2, int expected, int actual) { - String sign = expected < 0 ? " < " : expected > 0 ? " > " : " = "; - assertEquals("expected: " + v1 + sign + v2, signum(expected), signum(actual)); - } - - private int signum(int i) { - return i < 0 ? -1 : i > 0 ? 1 : 0; + private void assertOrdering(T v1, T v2, int expectedSignum, Comparator comparator) { + int compareResult = comparator.compare(v1, v2); + if (expectedSignum < 0) { + assertThat(compareResult).isNegative(); + } else if (expectedSignum > 0) { + assertThat(compareResult).isPositive(); + } else { + assertThat(compareResult).isZero(); + } } private void checkThrowingUnsupportedException(PrimitiveComparator comparator, Class exclude) { if (Integer.TYPE != exclude) { - try { - comparator.compare(0, 0); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> comparator.compare(0, 0)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("compare(int, int) was called on a non-int comparator: " + comparator); } if (Long.TYPE != exclude) { - try { - comparator.compare(0L, 0L); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> comparator.compare(0L, 0L)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("compare(long, long) was called on a non-long comparator: " + comparator); } if (Float.TYPE != exclude) { - try { - comparator.compare(0.0F, 0.0F); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> comparator.compare(0.0F, 0.0F)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("compare(float, float) was called on a non-float comparator: " + comparator); } if (Double.TYPE != exclude) { - try { - comparator.compare(0.0, 0.0); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> comparator.compare(0.0, 0.0)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining( + "compare(double, double) was called on a non-double comparator: " + comparator); } if (Boolean.TYPE != exclude) { - try { - comparator.compare(false, false); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> comparator.compare(false, false)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining( + "compare(boolean, boolean) was called on a non-boolean comparator: " + comparator); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveStringifier.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveStringifier.java index b165b200d2..7a7fd2ecb5 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveStringifier.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestPrimitiveStringifier.java @@ -40,8 +40,8 @@ import static org.apache.parquet.schema.PrimitiveStringifier.TIME_UTC_STRINGIFIER; import static org.apache.parquet.schema.PrimitiveStringifier.UNSIGNED_STRINGIFIER; import static org.apache.parquet.schema.PrimitiveStringifier.UTF8_STRINGIFIER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.math.BigInteger; import java.nio.ByteBuffer; @@ -51,7 +51,6 @@ import java.util.Set; import java.util.TimeZone; import java.util.concurrent.TimeUnit; -import org.apache.parquet.TestUtils; import org.apache.parquet.io.api.Binary; import org.junit.Test; @@ -63,42 +62,42 @@ public class TestPrimitiveStringifier { public void testDefaultStringifier() { PrimitiveStringifier stringifier = DEFAULT_STRINGIFIER; - assertEquals("true", stringifier.stringify(true)); - assertEquals("false", stringifier.stringify(false)); + assertThat(stringifier.stringify(true)).isEqualTo("true"); + assertThat(stringifier.stringify(false)).isEqualTo("false"); - assertEquals("0.0", stringifier.stringify(0.0)); - assertEquals("123456.7891234567", stringifier.stringify(123456.7891234567)); - assertEquals("-98765.43219876543", stringifier.stringify(-98765.43219876543)); + assertThat(stringifier.stringify(0.0)).isEqualTo("0.0"); + assertThat(stringifier.stringify(123456.7891234567)).isEqualTo("123456.7891234567"); + assertThat(stringifier.stringify(-98765.43219876543)).isEqualTo("-98765.43219876543"); - assertEquals("0.0", stringifier.stringify(0.0f)); - assertEquals("987.6543", stringifier.stringify(987.6543f)); - assertEquals("-123.4567", stringifier.stringify(-123.4567f)); + assertThat(stringifier.stringify(0.0f)).isEqualTo("0.0"); + assertThat(stringifier.stringify(987.6543f)).isEqualTo("987.6543"); + assertThat(stringifier.stringify(-123.4567f)).isEqualTo("-123.4567"); - assertEquals("0", stringifier.stringify(0)); - assertEquals("1234567890", stringifier.stringify(1234567890)); - assertEquals("-987654321", stringifier.stringify(-987654321)); + assertThat(stringifier.stringify(0)).isEqualTo("0"); + assertThat(stringifier.stringify(1234567890)).isEqualTo("1234567890"); + assertThat(stringifier.stringify(-987654321)).isEqualTo("-987654321"); - assertEquals("0", stringifier.stringify(0l)); - assertEquals("1234567890123456789", stringifier.stringify(1234567890123456789l)); - assertEquals("-987654321987654321", stringifier.stringify(-987654321987654321l)); + assertThat(stringifier.stringify(0l)).isEqualTo("0"); + assertThat(stringifier.stringify(1234567890123456789l)).isEqualTo("1234567890123456789"); + assertThat(stringifier.stringify(-987654321987654321l)).isEqualTo("-987654321987654321"); - assertEquals("null", stringifier.stringify(null)); - assertEquals("0x", stringifier.stringify(Binary.EMPTY)); - assertEquals( - "0x0123456789ABCDEF", stringifier.stringify(toBinary(0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF))); + assertThat(stringifier.stringify(null)).isEqualTo("null"); + assertThat(stringifier.stringify(Binary.EMPTY)).isEqualTo("0x"); + assertThat(stringifier.stringify(toBinary(0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF))) + .isEqualTo("0x0123456789ABCDEF"); } @Test public void testUnsignedStringifier() { PrimitiveStringifier stringifier = UNSIGNED_STRINGIFIER; - assertEquals("0", stringifier.stringify(0)); - assertEquals("2147483647", stringifier.stringify(2147483647)); - assertEquals("4294967295", stringifier.stringify(0xFFFFFFFF)); + assertThat(stringifier.stringify(0)).isEqualTo("0"); + assertThat(stringifier.stringify(2147483647)).isEqualTo("2147483647"); + assertThat(stringifier.stringify(0xFFFFFFFF)).isEqualTo("4294967295"); - assertEquals("0", stringifier.stringify(0l)); - assertEquals("9223372036854775807", stringifier.stringify(9223372036854775807l)); - assertEquals("18446744073709551615", stringifier.stringify(0xFFFFFFFFFFFFFFFFl)); + assertThat(stringifier.stringify(0l)).isEqualTo("0"); + assertThat(stringifier.stringify(9223372036854775807l)).isEqualTo("9223372036854775807"); + assertThat(stringifier.stringify(0xFFFFFFFFFFFFFFFFl)).isEqualTo("18446744073709551615"); checkThrowingUnsupportedException(stringifier, Integer.TYPE, Long.TYPE); } @@ -107,12 +106,12 @@ public void testUnsignedStringifier() { public void testUTF8Stringifier() { PrimitiveStringifier stringifier = UTF8_STRINGIFIER; - assertEquals("null", stringifier.stringify(null)); - assertEquals("", stringifier.stringify(Binary.EMPTY)); - assertEquals("This is a UTF-8 test", stringifier.stringify(Binary.fromString("This is a UTF-8 test"))); - assertEquals( - "これはUTF-8のテストです", - stringifier.stringify(Binary.fromConstantByteArray("これはUTF-8のテストです".getBytes(UTF_8)))); + assertThat(stringifier.stringify(null)).isEqualTo("null"); + assertThat(stringifier.stringify(Binary.EMPTY)).isEqualTo(""); + assertThat(stringifier.stringify(Binary.fromString("This is a UTF-8 test"))) + .isEqualTo("This is a UTF-8 test"); + assertThat(stringifier.stringify(Binary.fromConstantByteArray("これはUTF-8のテストです".getBytes(UTF_8)))) + .isEqualTo("これはUTF-8のテストです"); checkThrowingUnsupportedException(stringifier, Binary.class); } @@ -121,35 +120,33 @@ public void testUTF8Stringifier() { public void testIntervalStringifier() { PrimitiveStringifier stringifier = INTERVAL_STRINGIFIER; - assertEquals("null", stringifier.stringify(null)); + assertThat(stringifier.stringify(null)).isEqualTo("null"); - assertEquals("", stringifier.stringify(Binary.EMPTY)); - assertEquals( - "", - stringifier.stringify(Binary.fromConstantByteArray(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}))); - assertEquals("", stringifier.stringify(Binary.fromReusedByteArray(new byte[] { - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 - }))); + assertThat(stringifier.stringify(Binary.EMPTY)).isEqualTo(""); + assertThat(stringifier.stringify(Binary.fromConstantByteArray(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}))) + .isEqualTo(""); + assertThat(stringifier.stringify( + Binary.fromReusedByteArray(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}))) + .isEqualTo(""); ByteBuffer buffer = ByteBuffer.allocate(12); - assertEquals( - "interval(0 months, 0 days, 0 millis)", stringifier.stringify(Binary.fromConstantByteBuffer(buffer))); + assertThat(stringifier.stringify(Binary.fromConstantByteBuffer(buffer))) + .isEqualTo("interval(0 months, 0 days, 0 millis)"); buffer.putInt(0x03000000); buffer.putInt(0x06000000); buffer.putInt(0x09000000); buffer.flip(); - assertEquals( - "interval(3 months, 6 days, 9 millis)", stringifier.stringify(Binary.fromConstantByteBuffer(buffer))); + assertThat(stringifier.stringify(Binary.fromConstantByteBuffer(buffer))) + .isEqualTo("interval(3 months, 6 days, 9 millis)"); buffer.clear(); buffer.putInt(0xFFFFFFFF); buffer.putInt(0xFEFFFFFF); buffer.putInt(0xFDFFFFFF); buffer.flip(); - assertEquals( - "interval(4294967295 months, 4294967294 days, 4294967293 millis)", - stringifier.stringify(Binary.fromReusedByteBuffer(buffer))); + assertThat(stringifier.stringify(Binary.fromReusedByteBuffer(buffer))) + .isEqualTo("interval(4294967295 months, 4294967294 days, 4294967293 millis)"); checkThrowingUnsupportedException(stringifier, Binary.class); } @@ -158,16 +155,18 @@ public void testIntervalStringifier() { public void testDateStringifier() { PrimitiveStringifier stringifier = DATE_STRINGIFIER; - assertEquals("1970-01-01", stringifier.stringify(0)); + assertThat(stringifier.stringify(0)).isEqualTo("1970-01-01"); Calendar cal = Calendar.getInstance(UTC); cal.clear(); cal.set(2017, Calendar.DECEMBER, 14); - assertEquals("2017-12-14", stringifier.stringify((int) MILLISECONDS.toDays(cal.getTimeInMillis()))); + assertThat(stringifier.stringify((int) MILLISECONDS.toDays(cal.getTimeInMillis()))) + .isEqualTo("2017-12-14"); cal.clear(); cal.set(1583, Calendar.AUGUST, 3); - assertEquals("1583-08-03", stringifier.stringify((int) MILLISECONDS.toDays(cal.getTimeInMillis()))); + assertThat(stringifier.stringify((int) MILLISECONDS.toDays(cal.getTimeInMillis()))) + .isEqualTo("1583-08-03"); checkThrowingUnsupportedException(stringifier, Integer.TYPE); } @@ -178,22 +177,21 @@ public void testTimestampMillisStringifier() { List.of(TIMESTAMP_MILLIS_STRINGIFIER, TIMESTAMP_MILLIS_UTC_STRINGIFIER)) { String timezoneAmendment = (stringifier == TIMESTAMP_MILLIS_STRINGIFIER ? "" : "+0000"); - assertEquals(withZoneString("1970-01-01T00:00:00.000", timezoneAmendment), stringifier.stringify(0l)); + assertThat(stringifier.stringify(0l)) + .isEqualTo(withZoneString("1970-01-01T00:00:00.000", timezoneAmendment)); Calendar cal = Calendar.getInstance(UTC); cal.clear(); cal.set(2017, Calendar.DECEMBER, 15, 10, 9, 54); cal.set(Calendar.MILLISECOND, 120); - assertEquals( - withZoneString("2017-12-15T10:09:54.120", timezoneAmendment), - stringifier.stringify(cal.getTimeInMillis())); + assertThat(stringifier.stringify(cal.getTimeInMillis())) + .isEqualTo(withZoneString("2017-12-15T10:09:54.120", timezoneAmendment)); cal.clear(); cal.set(1948, Calendar.NOVEMBER, 23, 20, 19, 1); cal.set(Calendar.MILLISECOND, 9); - assertEquals( - withZoneString("1948-11-23T20:19:01.009", timezoneAmendment), - stringifier.stringify(cal.getTimeInMillis())); + assertThat(stringifier.stringify(cal.getTimeInMillis())) + .isEqualTo(withZoneString("1948-11-23T20:19:01.009", timezoneAmendment)); checkThrowingUnsupportedException(stringifier, Long.TYPE); } @@ -205,22 +203,23 @@ public void testTimestampMicrosStringifier() { List.of(TIMESTAMP_MICROS_STRINGIFIER, TIMESTAMP_MICROS_UTC_STRINGIFIER)) { String timezoneAmendment = (stringifier == TIMESTAMP_MICROS_STRINGIFIER ? "" : "+0000"); - assertEquals(withZoneString("1970-01-01T00:00:00.000000", timezoneAmendment), stringifier.stringify(0l)); + assertThat(stringifier.stringify(0l)) + .isEqualTo(withZoneString("1970-01-01T00:00:00.000000", timezoneAmendment)); Calendar cal = Calendar.getInstance(UTC); cal.clear(); cal.set(2053, Calendar.JULY, 10, 22, 13, 24); cal.set(Calendar.MILLISECOND, 84); long micros = cal.getTimeInMillis() * 1000 + 900; - assertEquals( - withZoneString("2053-07-10T22:13:24.084900", timezoneAmendment), stringifier.stringify(micros)); + assertThat(stringifier.stringify(micros)) + .isEqualTo(withZoneString("2053-07-10T22:13:24.084900", timezoneAmendment)); cal.clear(); cal.set(1848, Calendar.MARCH, 15, 9, 23, 59); cal.set(Calendar.MILLISECOND, 765); micros = cal.getTimeInMillis() * 1000 - 1; - assertEquals( - withZoneString("1848-03-15T09:23:59.764999", timezoneAmendment), stringifier.stringify(micros)); + assertThat(stringifier.stringify(micros)) + .isEqualTo(withZoneString("1848-03-15T09:23:59.764999", timezoneAmendment)); checkThrowingUnsupportedException(stringifier, Long.TYPE); } @@ -231,22 +230,23 @@ public void testTimestampNanosStringifier() { for (PrimitiveStringifier stringifier : List.of(TIMESTAMP_NANOS_STRINGIFIER, TIMESTAMP_NANOS_UTC_STRINGIFIER)) { String timezoneAmendment = (stringifier == TIMESTAMP_NANOS_STRINGIFIER ? "" : "+0000"); - assertEquals(withZoneString("1970-01-01T00:00:00.000000000", timezoneAmendment), stringifier.stringify(0l)); + assertThat(stringifier.stringify(0l)) + .isEqualTo(withZoneString("1970-01-01T00:00:00.000000000", timezoneAmendment)); Calendar cal = Calendar.getInstance(UTC); cal.clear(); cal.set(2053, Calendar.JULY, 10, 22, 13, 24); cal.set(Calendar.MILLISECOND, 84); long nanos = cal.getTimeInMillis() * 1_000_000 + 536; - assertEquals( - withZoneString("2053-07-10T22:13:24.084000536", timezoneAmendment), stringifier.stringify(nanos)); + assertThat(stringifier.stringify(nanos)) + .isEqualTo(withZoneString("2053-07-10T22:13:24.084000536", timezoneAmendment)); cal.clear(); cal.set(1848, Calendar.MARCH, 15, 9, 23, 59); cal.set(Calendar.MILLISECOND, 765); nanos = cal.getTimeInMillis() * 1_000_000 - 1; - assertEquals( - withZoneString("1848-03-15T09:23:59.764999999", timezoneAmendment), stringifier.stringify(nanos)); + assertThat(stringifier.stringify(nanos)) + .isEqualTo(withZoneString("1848-03-15T09:23:59.764999999", timezoneAmendment)); checkThrowingUnsupportedException(stringifier, Long.TYPE); } @@ -257,32 +257,28 @@ public void testTimeStringifier() { for (PrimitiveStringifier stringifier : List.of(TIME_STRINGIFIER, TIME_UTC_STRINGIFIER)) { String timezoneAmendment = (stringifier == TIME_STRINGIFIER ? "" : "+0000"); - assertEquals(withZoneString("00:00:00.000", timezoneAmendment), stringifier.stringify(0)); - assertEquals(withZoneString("00:00:00.000000", timezoneAmendment), stringifier.stringify(0l)); - - assertEquals(withZoneString("12:34:56.789", timezoneAmendment), stringifier.stringify((int) - convert(MILLISECONDS, 12, 34, 56, 789))); - assertEquals( - withZoneString("12:34:56.789012", timezoneAmendment), - stringifier.stringify(convert(MICROSECONDS, 12, 34, 56, 789012))); - - assertEquals(withZoneString("-12:34:56.789", timezoneAmendment), stringifier.stringify((int) - convert(MILLISECONDS, -12, -34, -56, -789))); - assertEquals( - withZoneString("-12:34:56.789012", timezoneAmendment), - stringifier.stringify(convert(MICROSECONDS, -12, -34, -56, -789012))); - - assertEquals(withZoneString("123:12:34.567", timezoneAmendment), stringifier.stringify((int) - convert(MILLISECONDS, 123, 12, 34, 567))); - assertEquals( - withZoneString("12345:12:34.056789", timezoneAmendment), - stringifier.stringify(convert(MICROSECONDS, 12345, 12, 34, 56789))); - - assertEquals(withZoneString("-123:12:34.567", timezoneAmendment), stringifier.stringify((int) - convert(MILLISECONDS, -123, -12, -34, -567))); - assertEquals( - withZoneString("-12345:12:34.056789", timezoneAmendment), - stringifier.stringify(convert(MICROSECONDS, -12345, -12, -34, -56789))); + assertThat(stringifier.stringify(0)).isEqualTo(withZoneString("00:00:00.000", timezoneAmendment)); + assertThat(stringifier.stringify(0l)).isEqualTo(withZoneString("00:00:00.000000", timezoneAmendment)); + + assertThat(stringifier.stringify((int) convert(MILLISECONDS, 12, 34, 56, 789))) + .isEqualTo(withZoneString("12:34:56.789", timezoneAmendment)); + assertThat(stringifier.stringify(convert(MICROSECONDS, 12, 34, 56, 789012))) + .isEqualTo(withZoneString("12:34:56.789012", timezoneAmendment)); + + assertThat(stringifier.stringify((int) convert(MILLISECONDS, -12, -34, -56, -789))) + .isEqualTo(withZoneString("-12:34:56.789", timezoneAmendment)); + assertThat(stringifier.stringify(convert(MICROSECONDS, -12, -34, -56, -789012))) + .isEqualTo(withZoneString("-12:34:56.789012", timezoneAmendment)); + + assertThat(stringifier.stringify((int) convert(MILLISECONDS, 123, 12, 34, 567))) + .isEqualTo(withZoneString("123:12:34.567", timezoneAmendment)); + assertThat(stringifier.stringify(convert(MICROSECONDS, 12345, 12, 34, 56789))) + .isEqualTo(withZoneString("12345:12:34.056789", timezoneAmendment)); + + assertThat(stringifier.stringify((int) convert(MILLISECONDS, -123, -12, -34, -567))) + .isEqualTo(withZoneString("-123:12:34.567", timezoneAmendment)); + assertThat(stringifier.stringify(convert(MICROSECONDS, -12345, -12, -34, -56789))) + .isEqualTo(withZoneString("-12345:12:34.056789", timezoneAmendment)); checkThrowingUnsupportedException(stringifier, Integer.TYPE, Long.TYPE); } @@ -293,20 +289,16 @@ public void testTimeNanoStringifier() { for (PrimitiveStringifier stringifier : List.of(TIME_NANOS_STRINGIFIER, TIME_NANOS_UTC_STRINGIFIER)) { String timezoneAmendment = (stringifier == TIME_NANOS_STRINGIFIER ? "" : "+0000"); - assertEquals(withZoneString("00:00:00.000000000", timezoneAmendment), stringifier.stringify(0l)); - - assertEquals( - withZoneString("12:34:56.789012987", timezoneAmendment), - stringifier.stringify(convert(NANOSECONDS, 12, 34, 56, 789012987))); - assertEquals( - withZoneString("-12:34:56.000789012", timezoneAmendment), - stringifier.stringify(convert(NANOSECONDS, -12, -34, -56, -789012))); - assertEquals( - withZoneString("12345:12:34.000056789", timezoneAmendment), - stringifier.stringify(convert(NANOSECONDS, 12345, 12, 34, 56789))); - assertEquals( - withZoneString("-12345:12:34.000056789", timezoneAmendment), - stringifier.stringify(convert(NANOSECONDS, -12345, -12, -34, -56789))); + assertThat(stringifier.stringify(0l)).isEqualTo(withZoneString("00:00:00.000000000", timezoneAmendment)); + + assertThat(stringifier.stringify(convert(NANOSECONDS, 12, 34, 56, 789012987))) + .isEqualTo(withZoneString("12:34:56.789012987", timezoneAmendment)); + assertThat(stringifier.stringify(convert(NANOSECONDS, -12, -34, -56, -789012))) + .isEqualTo(withZoneString("-12:34:56.000789012", timezoneAmendment)); + assertThat(stringifier.stringify(convert(NANOSECONDS, 12345, 12, 34, 56789))) + .isEqualTo(withZoneString("12345:12:34.000056789", timezoneAmendment)); + assertThat(stringifier.stringify(convert(NANOSECONDS, -12345, -12, -34, -56789))) + .isEqualTo(withZoneString("-12345:12:34.000056789", timezoneAmendment)); checkThrowingUnsupportedException(stringifier, Integer.TYPE, Long.TYPE); } @@ -324,25 +316,24 @@ private long convert(TimeUnit unit, long hours, long minutes, long seconds, long public void testDecimalStringifier() { PrimitiveStringifier stringifier = PrimitiveStringifier.createDecimalStringifier(4); - assertEquals("0.0000", stringifier.stringify(0)); - assertEquals("123456.7890", stringifier.stringify(1234567890)); - assertEquals("-98765.4321", stringifier.stringify(-987654321)); - - assertEquals("0.0000", stringifier.stringify(0l)); - assertEquals("123456789012345.6789", stringifier.stringify(1234567890123456789l)); - assertEquals("-98765432109876.5432", stringifier.stringify(-987654321098765432l)); - - assertEquals("null", stringifier.stringify(null)); - assertEquals("", stringifier.stringify(Binary.EMPTY)); - assertEquals("0.0000", stringifier.stringify(Binary.fromReusedByteArray(new byte[] {0}))); - assertEquals( - "9876543210987654321098765432109876543210987654.3210", - stringifier.stringify(Binary.fromConstantByteArray( - new BigInteger("98765432109876543210987654321098765432109876543210").toByteArray()))); - assertEquals( - "-1234567890123456789012345678901234567890123456.7890", - stringifier.stringify(Binary.fromConstantByteArray( - new BigInteger("-12345678901234567890123456789012345678901234567890").toByteArray()))); + assertThat(stringifier.stringify(0)).isEqualTo("0.0000"); + assertThat(stringifier.stringify(1234567890)).isEqualTo("123456.7890"); + assertThat(stringifier.stringify(-987654321)).isEqualTo("-98765.4321"); + + assertThat(stringifier.stringify(0l)).isEqualTo("0.0000"); + assertThat(stringifier.stringify(1234567890123456789l)).isEqualTo("123456789012345.6789"); + assertThat(stringifier.stringify(-987654321098765432l)).isEqualTo("-98765432109876.5432"); + + assertThat(stringifier.stringify(null)).isEqualTo("null"); + assertThat(stringifier.stringify(Binary.EMPTY)).isEqualTo(""); + assertThat(stringifier.stringify(Binary.fromReusedByteArray(new byte[] {0}))) + .isEqualTo("0.0000"); + assertThat(stringifier.stringify(Binary.fromConstantByteArray( + new BigInteger("98765432109876543210987654321098765432109876543210").toByteArray()))) + .isEqualTo("9876543210987654321098765432109876543210987654.3210"); + assertThat(stringifier.stringify(Binary.fromConstantByteArray( + new BigInteger("-12345678901234567890123456789012345678901234567890").toByteArray()))) + .isEqualTo("-1234567890123456789012345678901234567890123456.7890"); checkThrowingUnsupportedException(stringifier, Integer.TYPE, Long.TYPE, Binary.class); } @@ -352,33 +343,33 @@ public void testFloat16Stringifier() { PrimitiveStringifier stringifier = PrimitiveStringifier.FLOAT16_STRINGIFIER; // Zeroes, NaN and infinities - assertEquals("0.0", stringifier.stringify(toBinary(0x00, 0x00))); - assertEquals("-0.0", stringifier.stringify(toBinary(0x00, 0x80))); - assertEquals(Float.toString(Float.NaN), stringifier.stringify(toBinary(0x00, 0x7e))); - assertEquals(Float.toString(Float.POSITIVE_INFINITY), stringifier.stringify(toBinary(0x00, 0x7c))); - assertEquals(Float.toString(Float.NEGATIVE_INFINITY), stringifier.stringify(toBinary(0x00, 0xfc))); + assertThat(stringifier.stringify(toBinary(0x00, 0x00))).isEqualTo("0.0"); + assertThat(stringifier.stringify(toBinary(0x00, 0x80))).isEqualTo("-0.0"); + assertThat(stringifier.stringify(toBinary(0x00, 0x7e))).isEqualTo(Float.toString(Float.NaN)); + assertThat(stringifier.stringify(toBinary(0x00, 0x7c))).isEqualTo(Float.toString(Float.POSITIVE_INFINITY)); + assertThat(stringifier.stringify(toBinary(0x00, 0xfc))).isEqualTo(Float.toString(Float.NEGATIVE_INFINITY)); // Known values - assertEquals("1.0009766", stringifier.stringify(toBinary(0x01, 0x3c))); - assertEquals("-2.0", stringifier.stringify(toBinary(0x00, 0xc0))); - assertEquals("6.1035156E-5", stringifier.stringify(toBinary(0x00, 0x04))); - assertEquals("65504.0", stringifier.stringify(toBinary(0xff, 0x7b))); - assertEquals("0.33325195", stringifier.stringify(toBinary(0x55, 0x35))); + assertThat(stringifier.stringify(toBinary(0x01, 0x3c))).isEqualTo("1.0009766"); + assertThat(stringifier.stringify(toBinary(0x00, 0xc0))).isEqualTo("-2.0"); + assertThat(stringifier.stringify(toBinary(0x00, 0x04))).isEqualTo("6.1035156E-5"); + assertThat(stringifier.stringify(toBinary(0xff, 0x7b))).isEqualTo("65504.0"); + assertThat(stringifier.stringify(toBinary(0x55, 0x35))).isEqualTo("0.33325195"); // Subnormals - assertEquals("6.097555E-5", stringifier.stringify(toBinary(0xff, 0x03))); - assertEquals("5.9604645E-8", stringifier.stringify(toBinary(0x01, 0x00))); - assertEquals("-6.097555E-5", stringifier.stringify(toBinary(0xff, 0x83))); - assertEquals("-5.9604645E-8", stringifier.stringify(toBinary(0x01, 0x80))); + assertThat(stringifier.stringify(toBinary(0xff, 0x03))).isEqualTo("6.097555E-5"); + assertThat(stringifier.stringify(toBinary(0x01, 0x00))).isEqualTo("5.9604645E-8"); + assertThat(stringifier.stringify(toBinary(0xff, 0x83))).isEqualTo("-6.097555E-5"); + assertThat(stringifier.stringify(toBinary(0x01, 0x80))).isEqualTo("-5.9604645E-8"); // Floats with absolute value above +/-65519 are rounded to +/-inf // when using round-to-even - assertEquals("65504.0", stringifier.stringify(toBinary(0xff, 0x7b))); + assertThat(stringifier.stringify(toBinary(0xff, 0x7b))).isEqualTo("65504.0"); // Check if numbers are rounded to nearest even when they // cannot be accurately represented by Half - assertEquals("2048.0", stringifier.stringify(toBinary(0x00, 0x68))); - assertEquals("4096.0", stringifier.stringify(toBinary(0x00, 0x6c))); + assertThat(stringifier.stringify(toBinary(0x00, 0x68))).isEqualTo("2048.0"); + assertThat(stringifier.stringify(toBinary(0x00, 0x6c))).isEqualTo("4096.0"); checkThrowingUnsupportedException(stringifier, Integer.TYPE, Long.TYPE, Binary.class); } @@ -387,40 +378,33 @@ public void testFloat16Stringifier() { public void testUUIDStringifier() { PrimitiveStringifier stringifier = PrimitiveStringifier.UUID_STRINGIFIER; - assertEquals( - "00112233-4455-6677-8899-aabbccddeeff", - stringifier.stringify(toBinary( + assertThat(stringifier.stringify(toBinary( 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, - 0xff))); - assertEquals( - "00000000-0000-0000-0000-000000000000", - stringifier.stringify(toBinary( + 0xff))) + .isEqualTo("00112233-4455-6677-8899-aabbccddeeff"); + assertThat(stringifier.stringify(toBinary( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00))); - assertEquals( - "ffffffff-ffff-ffff-ffff-ffffffffffff", - stringifier.stringify(toBinary( + 0x00))) + .isEqualTo("00000000-0000-0000-0000-000000000000"); + assertThat(stringifier.stringify(toBinary( 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff))); - assertEquals( - "0eb1497c-19b6-42bc-b028-b4b612bed141", - stringifier.stringify(toBinary( + 0xff))) + .isEqualTo("ffffffff-ffff-ffff-ffff-ffffffffffff"); + assertThat(stringifier.stringify(toBinary( 0x0e, 0xb1, 0x49, 0x7c, 0x19, 0xb6, 0x42, 0xbc, 0xb0, 0x28, 0xb4, 0xb6, 0x12, 0xbe, 0xd1, - 0x41))); + 0x41))) + .isEqualTo("0eb1497c-19b6-42bc-b028-b4b612bed141"); // Check that the stringifier does not care about the length, it always takes the first 16 bytes - assertEquals( - "87a09cca-3b1e-4a0a-9c77-591924c3b57b", - stringifier.stringify(toBinary( + assertThat(stringifier.stringify(toBinary( 0x87, 0xa0, 0x9c, 0xca, 0x3b, 0x1e, 0x4a, 0x0a, 0x9c, 0x77, 0x59, 0x19, 0x24, 0xc3, 0xb5, 0x7b, - 0x00, 0x00, 0x00))); + 0x00, 0x00, 0x00))) + .isEqualTo("87a09cca-3b1e-4a0a-9c77-591924c3b57b"); // As there is no validation implemented, if the 16 bytes is not available, the array will be over-indexed - TestUtils.assertThrows( - "Expected exception for over-indexing", - ArrayIndexOutOfBoundsException.class, - () -> stringifier.stringify(toBinary( - 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee))); + assertThatThrownBy(() -> stringifier.stringify(toBinary( + 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee))) + .isInstanceOf(ArrayIndexOutOfBoundsException.class); checkThrowingUnsupportedException(stringifier, Binary.class); } @@ -436,46 +420,34 @@ private Binary toBinary(int... bytes) { private void checkThrowingUnsupportedException(PrimitiveStringifier stringifier, Class... excludes) { Set> set = new HashSet<>(List.of(excludes)); if (!set.contains(Integer.TYPE)) { - try { - stringifier.stringify(0); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> stringifier.stringify(0)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("stringify(int) was called on a non-int stringifier: " + stringifier); } if (!set.contains(Long.TYPE)) { - try { - stringifier.stringify(0l); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> stringifier.stringify(0l)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("stringify(long) was called on a non-long stringifier: " + stringifier); } if (!set.contains(Float.TYPE)) { - try { - stringifier.stringify(0.0f); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> stringifier.stringify(0.0f)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("stringify(float) was called on a non-float stringifier: " + stringifier); } if (!set.contains(Double.TYPE)) { - try { - stringifier.stringify(0.0); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> stringifier.stringify(0.0)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("stringify(double) was called on a non-double stringifier: " + stringifier); } if (!set.contains(Boolean.TYPE)) { - try { - stringifier.stringify(false); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> stringifier.stringify(false)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("stringify(boolean) was called on a non-boolean stringifier: " + stringifier); } if (!set.contains(Binary.class)) { - try { - stringifier.stringify(Binary.EMPTY); - fail("An UnsupportedOperationException should have been thrown"); - } catch (UnsupportedOperationException e) { - } + assertThatThrownBy(() -> stringifier.stringify(Binary.EMPTY)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("stringify(Binary) was called on a non-Binary stringifier: " + stringifier); } } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestRepetitionType.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestRepetitionType.java index f153a03ac7..c722c875f8 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestRepetitionType.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestRepetitionType.java @@ -18,7 +18,7 @@ */ package org.apache.parquet.schema; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -29,9 +29,10 @@ public void testLeastRestrictiveRepetition() { Type.Repetition OPTIONAL = Type.Repetition.OPTIONAL; Type.Repetition REPEATED = Type.Repetition.REPEATED; - assertEquals( - REPEATED, Type.Repetition.leastRestrictive(REQUIRED, OPTIONAL, REPEATED, REQUIRED, OPTIONAL, REPEATED)); - assertEquals(OPTIONAL, Type.Repetition.leastRestrictive(REQUIRED, OPTIONAL, REQUIRED, OPTIONAL)); - assertEquals(REQUIRED, Type.Repetition.leastRestrictive(REQUIRED, REQUIRED)); + assertThat(Type.Repetition.leastRestrictive(REQUIRED, OPTIONAL, REPEATED, REQUIRED, OPTIONAL, REPEATED)) + .isEqualTo(REPEATED); + assertThat(Type.Repetition.leastRestrictive(REQUIRED, OPTIONAL, REQUIRED, OPTIONAL)) + .isEqualTo(OPTIONAL); + assertThat(Type.Repetition.leastRestrictive(REQUIRED, REQUIRED)).isEqualTo(REQUIRED); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuilders.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuilders.java index 5843df982f..6b02309ed7 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuilders.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuilders.java @@ -50,16 +50,14 @@ import static org.apache.parquet.schema.Type.Repetition.OPTIONAL; import static org.apache.parquet.schema.Type.Repetition.REPEATED; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import org.apache.parquet.column.schema.EdgeInterpolationAlgorithm; import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; import org.apache.parquet.schema.Type.Repetition; -import org.junit.Assert; import org.junit.Test; public class TestTypeBuilders { @@ -102,7 +100,7 @@ public void testPaperExample() { .named("Url") .named("Name") .named("Document"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); } @Test @@ -119,7 +117,7 @@ public void testGroupTypeConstruction() { .addFields(f2, f3) .named("g1") .named(name); - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); switch (repetition) { case REQUIRED: @@ -147,7 +145,7 @@ public void testGroupTypeConstruction() { .named(name); break; } - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); } } @@ -155,11 +153,11 @@ public void testGroupTypeConstruction() { public void testPrimitiveTypeConstruction() { PrimitiveTypeName[] types = new PrimitiveTypeName[] {BOOLEAN, INT32, INT64, INT96, FLOAT, DOUBLE, BINARY}; for (PrimitiveTypeName type : types) { - String name = type.toString() + "_"; + String name = type + "_"; for (Type.Repetition repetition : Type.Repetition.values()) { PrimitiveType expected = new PrimitiveType(repetition, type, name); PrimitiveType built = Types.primitive(type, repetition).named(name); - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); switch (repetition) { case REQUIRED: built = Types.required(type).named(name); @@ -171,7 +169,7 @@ public void testPrimitiveTypeConstruction() { built = Types.repeated(type).named(name); break; } - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); } } } @@ -185,7 +183,7 @@ public void testFixedTypeConstruction() { PrimitiveType built = Types.primitive(FIXED_LEN_BYTE_ARRAY, repetition) .length(len) .named(name); - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); switch (repetition) { case REQUIRED: built = Types.required(FIXED_LEN_BYTE_ARRAY).length(len).named(name); @@ -197,34 +195,30 @@ public void testFixedTypeConstruction() { built = Types.repeated(FIXED_LEN_BYTE_ARRAY).length(len).named(name); break; } - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); } } @Test public void testEmptyGroup() { // empty groups are allowed to support selecting 0 columns (counting rows) - Assert.assertEquals( - "Should not complain about an empty required group", - Types.requiredGroup().named("g"), - new GroupType(REQUIRED, "g")); - Assert.assertEquals( - "Should not complain about an empty required group", - Types.optionalGroup().named("g"), - new GroupType(OPTIONAL, "g")); - Assert.assertEquals( - "Should not complain about an empty required group", - Types.repeatedGroup().named("g"), - new GroupType(REPEATED, "g")); + assertThat(new GroupType(REQUIRED, "g")) + .as("Should not complain about an empty required group") + .isEqualTo(Types.requiredGroup().named("g")); + assertThat(new GroupType(OPTIONAL, "g")) + .as("Should not complain about an empty required group") + .isEqualTo(Types.optionalGroup().named("g")); + assertThat(new GroupType(REPEATED, "g")) + .as("Should not complain about an empty required group") + .isEqualTo(Types.repeatedGroup().named("g")); } @Test public void testEmptyMessage() { // empty groups are allowed to support selecting 0 columns (counting rows) - Assert.assertEquals( - "Should not complain about an empty required group", - Types.buildMessage().named("m"), - new MessageType("m")); + assertThat(new MessageType("m")) + .as("Should not complain about an empty required group") + .isEqualTo(Types.buildMessage().named("m")); } @Test @@ -238,14 +232,14 @@ public void testFixedWithoutLength() { public void testFixedWithLength() { PrimitiveType expected = new PrimitiveType(REQUIRED, FIXED_LEN_BYTE_ARRAY, 7, "fixed"); PrimitiveType fixed = Types.required(FIXED_LEN_BYTE_ARRAY).length(7).named("fixed"); - Assert.assertEquals(expected, fixed); + assertThat(fixed).isEqualTo(expected); } @Test public void testFixedLengthEquals() { Type f4 = Types.required(FIXED_LEN_BYTE_ARRAY).length(4).named("f4"); Type f8 = Types.required(FIXED_LEN_BYTE_ARRAY).length(8).named("f8"); - Assert.assertFalse("Types with different lengths should not be equal", f4.equals(f8)); + assertThat(f4).as("Types with different lengths should not be equal").isNotEqualTo(f8); } @Test @@ -261,7 +255,7 @@ public void testDecimalAnnotation() { .scale(2) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); // int64 primitive type expected = new MessageType( "DecimalMessage", @@ -273,7 +267,7 @@ public void testDecimalAnnotation() { .scale(2) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); // binary primitive type expected = new MessageType( "DecimalMessage", @@ -285,7 +279,7 @@ public void testDecimalAnnotation() { .scale(2) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); // fixed primitive type expected = new MessageType( "DecimalMessage", @@ -299,7 +293,7 @@ public void testDecimalAnnotation() { .scale(2) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); } @Test @@ -313,7 +307,7 @@ public void testDecimalAnnotationMissingScale() { .precision(9) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); expected = new MessageType( "DecimalMessage", @@ -324,7 +318,7 @@ public void testDecimalAnnotationMissingScale() { .precision(9) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); expected = new MessageType( "DecimalMessage", @@ -335,7 +329,7 @@ public void testDecimalAnnotationMissingScale() { .precision(9) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); expected = new MessageType( "DecimalMessage", @@ -348,118 +342,132 @@ public void testDecimalAnnotationMissingScale() { .precision(9) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); } @Test public void testDecimalAnnotationMissingPrecision() { - assertThrows( - "Should reject decimal annotation without precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() - .required(INT32) - .as(DECIMAL) - .scale(2) - .named("aDecimal") - .named("DecimalMessage")); - assertThrows( - "Should reject decimal annotation without precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() - .required(INT64) - .as(DECIMAL) - .scale(2) - .named("aDecimal") - .named("DecimalMessage")); - assertThrows( - "Should reject decimal annotation without precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() - .required(BINARY) - .as(DECIMAL) - .scale(2) - .named("aDecimal") - .named("DecimalMessage")); - assertThrows( - "Should reject decimal annotation without precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() - .required(FIXED_LEN_BYTE_ARRAY) - .length(7) - .as(DECIMAL) - .scale(2) - .named("aDecimal") - .named("DecimalMessage")); + assertThatThrownBy(() -> Types.buildMessage() + .required(INT32) + .as(DECIMAL) + .scale(2) + .named("aDecimal") + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL precision: 0"); + assertThatThrownBy(() -> Types.buildMessage() + .required(INT64) + .as(DECIMAL) + .scale(2) + .named("aDecimal") + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL precision: 0"); + assertThatThrownBy(() -> Types.buildMessage() + .required(BINARY) + .as(DECIMAL) + .scale(2) + .named("aDecimal") + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL precision: 0"); + assertThatThrownBy(() -> Types.buildMessage() + .required(FIXED_LEN_BYTE_ARRAY) + .length(7) + .as(DECIMAL) + .scale(2) + .named("aDecimal") + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL precision: 0"); } @Test public void testDecimalAnnotationPrecisionScaleBound() { - assertThrows("Should reject scale greater than precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() + assertThatThrownBy(() -> Types.buildMessage() .required(INT32) .as(DECIMAL) .precision(3) .scale(4) .named("aDecimal") - .named("DecimalMessage")); - assertThrows("Should reject scale greater than precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL scale: 4 cannot be greater than precision: 3"); + assertThatThrownBy(() -> Types.buildMessage() .required(INT64) .as(DECIMAL) .precision(3) .scale(4) .named("aDecimal") - .named("DecimalMessage")); - assertThrows("Should reject scale greater than precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL scale: 4 cannot be greater than precision: 3"); + assertThatThrownBy(() -> Types.buildMessage() .required(BINARY) .as(DECIMAL) .precision(3) .scale(4) .named("aDecimal") - .named("DecimalMessage")); - assertThrows("Should reject scale greater than precision", IllegalArgumentException.class, (Callable) - () -> Types.buildMessage() + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL scale: 4 cannot be greater than precision: 3"); + assertThatThrownBy(() -> Types.buildMessage() .required(FIXED_LEN_BYTE_ARRAY) .length(7) .as(DECIMAL) .precision(3) .scale(4) .named("aDecimal") - .named("DecimalMessage")); + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid DECIMAL scale: 4 cannot be greater than precision: 3"); } @Test public void testDecimalAnnotationLengthCheck() { // maximum precision for 4 bytes is 9 - assertThrows("should reject precision 10 with length 4", IllegalStateException.class, (Callable) - () -> Types.required(FIXED_LEN_BYTE_ARRAY) + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) .length(4) .as(DECIMAL) .precision(10) .scale(2) - .named("aDecimal")); - assertThrows("should reject precision 10 with length 4", IllegalStateException.class, (Callable) - () -> Types.required(INT32).as(DECIMAL).precision(10).scale(2).named("aDecimal")); + .named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FIXED(4) cannot store 10 digits (max 9)"); + assertThatThrownBy(() -> + Types.required(INT32).as(DECIMAL).precision(10).scale(2).named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INT32 cannot store 10 digits (max 9)"); // maximum precision for 8 bytes is 19 - assertThrows("should reject precision 19 with length 8", IllegalStateException.class, (Callable) - () -> Types.required(FIXED_LEN_BYTE_ARRAY) + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) .length(8) .as(DECIMAL) .precision(19) .scale(4) - .named("aDecimal")); - assertThrows("should reject precision 19 with length 8", IllegalStateException.class, (Callable) - () -> Types.required(INT64) + .named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FIXED(8) cannot store 19 digits (max 18)"); + assertThatThrownBy(() -> Types.required(INT64) .length(8) .as(DECIMAL) .precision(19) .scale(4) - .named("aDecimal")); + .named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INT64 cannot store 19 digits (max 18)"); } @Test public void testDECIMALAnnotationRejectsUnsupportedTypes() { PrimitiveTypeName[] unsupported = new PrimitiveTypeName[] {BOOLEAN, INT96, DOUBLE, FLOAT}; for (final PrimitiveTypeName type : unsupported) { - assertThrows("Should reject non-binary type: " + type, IllegalStateException.class, (Callable) - () -> Types.required(type).as(DECIMAL).precision(9).scale(2).named("d")); + assertThatThrownBy(() -> Types.required(type) + .as(DECIMAL) + .precision(9) + .scale(2) + .named("d")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("DECIMAL can only annotate INT32, INT64, BINARY, and FIXED"); } } @@ -469,7 +477,7 @@ public void testBinaryAnnotations() { for (final OriginalType logicalType : types) { PrimitiveType expected = new PrimitiveType(REQUIRED, BINARY, "col", logicalType); PrimitiveType string = Types.required(BINARY).as(logicalType).named("col"); - Assert.assertEquals(expected, string); + assertThat(string).isEqualTo(expected); } } @@ -479,15 +487,18 @@ public void testBinaryAnnotationsRejectsNonBinary() { for (final OriginalType logicalType : types) { PrimitiveTypeName[] nonBinary = new PrimitiveTypeName[] {BOOLEAN, INT32, INT64, INT96, DOUBLE, FLOAT}; for (final PrimitiveTypeName type : nonBinary) { - assertThrows("Should reject non-binary type: " + type, IllegalStateException.class, (Callable) - () -> Types.required(type).as(logicalType).named("col")); + assertThatThrownBy(() -> Types.required(type).as(logicalType).named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(LogicalTypeAnnotation.fromOriginalType(logicalType, null) + + " can only annotate BINARY"); } - assertThrows( - "Should reject non-binary type: FIXED_LEN_BYTE_ARRAY", IllegalStateException.class, (Callable) - () -> Types.required(FIXED_LEN_BYTE_ARRAY) - .length(1) - .as(logicalType) - .named("col")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(1) + .as(logicalType) + .named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + LogicalTypeAnnotation.fromOriginalType(logicalType, null) + " can only annotate BINARY"); } } @@ -497,7 +508,7 @@ public void testInt32Annotations() { for (OriginalType logicalType : types) { PrimitiveType expected = new PrimitiveType(REQUIRED, INT32, "col", logicalType); PrimitiveType date = Types.required(INT32).as(logicalType).named("col"); - Assert.assertEquals(expected, date); + assertThat(date).isEqualTo(expected); } } @@ -507,15 +518,17 @@ public void testInt32AnnotationsRejectNonInt32() { for (final OriginalType logicalType : types) { PrimitiveTypeName[] nonInt32 = new PrimitiveTypeName[] {BOOLEAN, INT64, INT96, DOUBLE, FLOAT, BINARY}; for (final PrimitiveTypeName type : nonInt32) { - assertThrows("Should reject non-int32 type: " + type, IllegalStateException.class, (Callable) - () -> Types.required(type).as(logicalType).named("col")); + assertThatThrownBy(() -> Types.required(type).as(logicalType).named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + LogicalTypeAnnotation.fromOriginalType(logicalType, null) + " can only annotate INT32"); } - assertThrows( - "Should reject non-int32 type: FIXED_LEN_BYTE_ARRAY", IllegalStateException.class, (Callable) - () -> Types.required(FIXED_LEN_BYTE_ARRAY) - .length(1) - .as(logicalType) - .named("col")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(1) + .as(logicalType) + .named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(LogicalTypeAnnotation.fromOriginalType(logicalType, null) + " can only annotate INT32"); } } @@ -525,7 +538,7 @@ public void testInt64Annotations() { for (OriginalType logicalType : types) { PrimitiveType expected = new PrimitiveType(REQUIRED, INT64, "col", logicalType); PrimitiveType date = Types.required(INT64).as(logicalType).named("col"); - Assert.assertEquals(expected, date); + assertThat(date).isEqualTo(expected); } } @@ -535,15 +548,17 @@ public void testInt64AnnotationsRejectNonInt64() { for (final OriginalType logicalType : types) { PrimitiveTypeName[] nonInt64 = new PrimitiveTypeName[] {BOOLEAN, INT32, INT96, DOUBLE, FLOAT, BINARY}; for (final PrimitiveTypeName type : nonInt64) { - assertThrows("Should reject non-int64 type: " + type, IllegalStateException.class, (Callable) - () -> Types.required(type).as(logicalType).named("col")); + assertThatThrownBy(() -> Types.required(type).as(logicalType).named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + LogicalTypeAnnotation.fromOriginalType(logicalType, null) + " can only annotate INT64"); } - assertThrows( - "Should reject non-int64 type: FIXED_LEN_BYTE_ARRAY", IllegalStateException.class, (Callable) - () -> Types.required(FIXED_LEN_BYTE_ARRAY) - .length(1) - .as(logicalType) - .named("col")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(1) + .as(logicalType) + .named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(LogicalTypeAnnotation.fromOriginalType(logicalType, null) + " can only annotate INT64"); } } @@ -552,22 +567,27 @@ public void testIntervalAnnotation() { PrimitiveType expected = new PrimitiveType(REQUIRED, FIXED_LEN_BYTE_ARRAY, 12, "interval", INTERVAL); PrimitiveType string = Types.required(FIXED_LEN_BYTE_ARRAY).length(12).as(INTERVAL).named("interval"); - Assert.assertEquals(expected, string); + assertThat(string).isEqualTo(expected); } @Test public void testIntervalAnnotationRejectsNonFixed() { PrimitiveTypeName[] nonFixed = new PrimitiveTypeName[] {BOOLEAN, INT32, INT64, INT96, DOUBLE, FLOAT, BINARY}; for (final PrimitiveTypeName type : nonFixed) { - assertThrows("Should reject non-fixed type: " + type, IllegalStateException.class, (Callable) - () -> Types.required(type).as(INTERVAL).named("interval")); + assertThatThrownBy(() -> Types.required(type).as(INTERVAL).named("interval")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)"); } } @Test public void testIntervalAnnotationRejectsNonFixed12() { - assertThrows("Should reject fixed with length != 12: " + 11, IllegalStateException.class, (Callable) () -> - Types.required(FIXED_LEN_BYTE_ARRAY).length(11).as(INTERVAL).named("interval")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(11) + .as(INTERVAL) + .named("interval")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)"); } @Test @@ -578,7 +598,7 @@ public void testRequiredMap() { GroupType expected = new GroupType(REQUIRED, "myMap", OriginalType.MAP, new GroupType(REPEATED, "key_value", typeList)); GroupType actual = Types.requiredMap().key(INT64).requiredValue(INT64).named("myMap"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -589,7 +609,7 @@ public void testOptionalMap() { GroupType expected = new GroupType(OPTIONAL, "myMap", OriginalType.MAP, new GroupType(REPEATED, "key_value", typeList)); GroupType actual = Types.optionalMap().key(INT64).requiredValue(INT64).named("myMap"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -606,7 +626,7 @@ public void testMapWithRequiredValue() { .requiredValue(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -623,7 +643,7 @@ public void testMapWithOptionalValue() { .optionalValue(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -655,7 +675,7 @@ public void testMapWithGroupKeyAndOptionalGroupValue() { .optional(INT32) .named("two") .named("myMap"); - Assert.assertEquals(map, actual); + assertThat(actual).isEqualTo(map); } @Test @@ -690,7 +710,7 @@ public void testMapWithGroupKeyAndRequiredGroupValue() { .named("two") .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -718,7 +738,7 @@ public void testMapWithGroupKeyAndOptionalValue() { .optionalValue(DOUBLE) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -746,7 +766,7 @@ public void testMapWithGroupKeyAndRequiredValue() { .requiredValue(DOUBLE) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -777,7 +797,7 @@ public void testMapWithOptionalGroupValue() { .named("two") .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -805,7 +825,7 @@ public void testMapWithRequiredGroupValue() { .named("two") .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -852,7 +872,7 @@ public void testMapWithNestedGroupKeyAndNestedGroupValue() { .named("two") .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -877,7 +897,7 @@ public void testMapWithRequiredListValue() { .optionalElement(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -902,7 +922,7 @@ public void testMapWithOptionalListValue() { .optionalElement(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -929,7 +949,7 @@ public void testMapWithRequiredMapValue() { .requiredValue(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -956,7 +976,7 @@ public void testMapWithOptionalMapValue() { .requiredValue(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -983,7 +1003,7 @@ public void testMapWithGroupKeyAndRequiredListValue() { .optionalElement(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1010,7 +1030,7 @@ public void testMapWithGroupKeyAndOptionalListValue() { .optionalElement(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1039,7 +1059,7 @@ public void testMapWithGroupKeyAndRequiredMapValue() { .requiredValue(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1068,7 +1088,7 @@ public void testMapWithGroupKeyAndOptionalMapValue() { .requiredValue(INT64) .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1082,7 +1102,7 @@ public void testMapWithNullValue() { MessageType expected = new MessageType("mapParent", map); GroupType actual = Types.buildMessage().optionalMap().key(INT64).named("myMap").named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1095,7 +1115,7 @@ public void testMapWithDefaultKeyAndNullValue() { MessageType expected = new MessageType("mapParent", map); GroupType actual = Types.buildMessage().optionalMap().named("myMap").named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1115,7 +1135,7 @@ public void testMapWithPreBuiltKeyAndValueTypes() { .named("myMap") .named("mapParent"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1127,7 +1147,7 @@ public void testListWithRequiredPreBuiltElement() { new GroupType(REPEATED, "list", new PrimitiveType(REQUIRED, INT64, "element"))); Type element = Types.primitive(INT64, REQUIRED).named("element"); Type actual = Types.requiredList().element(element).named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1138,7 +1158,7 @@ public void testRequiredList() { OriginalType.LIST, new GroupType(REPEATED, "list", new PrimitiveType(OPTIONAL, INT64, "element"))); Type actual = Types.requiredList().optionalElement(INT64).named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1149,7 +1169,7 @@ public void testOptionalList() { OriginalType.LIST, new GroupType(REPEATED, "list", new PrimitiveType(OPTIONAL, INT64, "element"))); Type actual = Types.optionalList().optionalElement(INT64).named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1166,7 +1186,7 @@ public void testListOfReqGroup() { .optional(BOOLEAN) .named("field") .named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1183,7 +1203,7 @@ public void testListOfOptionalGroup() { .optional(BOOLEAN) .named("field") .named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1202,7 +1222,7 @@ public void testRequiredNestedList() { .optionalElement(DOUBLE) .named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1221,7 +1241,7 @@ public void testOptionalNestedList() { .optionalElement(DOUBLE) .named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1238,7 +1258,7 @@ public void testRequiredListWithinGroup() { .optionalElement(INT64) .named("element") .named("topGroup"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1255,7 +1275,7 @@ public void testOptionalListWithinGroup() { .optionalElement(INT64) .named("element") .named("topGroup"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1272,7 +1292,7 @@ public void testOptionalListWithinGroupWithReqElement() { .requiredElement(INT64) .named("element") .named("topGroup"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1293,7 +1313,7 @@ public void testRequiredMapWithinList() { .requiredValue(INT32) .named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1314,7 +1334,7 @@ public void testOptionalMapWithinList() { .requiredValue(INT32) .named("myList"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1330,7 +1350,7 @@ public void testTypeConstructionWithUndefinedColumnOrder() { .length(len) .columnOrder(ColumnOrder.undefined()) .named(name); - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); } } @@ -1347,20 +1367,24 @@ public void testTypeConstructionWithTypeDefinedColumnOrder() { .length(len) .columnOrder(ColumnOrder.typeDefined()) .named(name); - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); } } @Test public void testTypeConstructionWithUnsupportedColumnOrder() { - assertThrows(null, IllegalArgumentException.class, (Callable) () -> - Types.optional(INT96).columnOrder(ColumnOrder.typeDefined()).named("int96_unsupported")); - assertThrows(null, IllegalArgumentException.class, (Callable) - () -> Types.optional(FIXED_LEN_BYTE_ARRAY) + assertThatThrownBy(() -> Types.optional(INT96) + .columnOrder(ColumnOrder.typeDefined()) + .named("int96_unsupported")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The column order TYPE_DEFINED_ORDER is not supported by INT96"); + assertThatThrownBy(() -> Types.optional(FIXED_LEN_BYTE_ARRAY) .length(12) .as(INTERVAL) .columnOrder(ColumnOrder.typeDefined()) - .named("interval_unsupported")); + .named("interval_unsupported")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The column order TYPE_DEFINED_ORDER is not supported by FIXED_LEN_BYTE_ARRAY (INTERVAL)"); } @Test @@ -1370,7 +1394,7 @@ public void testDecimalLogicalType() { PrimitiveType actual = Types.required(BINARY) .as(LogicalTypeAnnotation.decimalType(3, 4)) .named("aDecimal"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1381,7 +1405,7 @@ public void testDecimalLogicalTypeWithDeprecatedScale() { .as(LogicalTypeAnnotation.decimalType(3, 4)) .scale(3) .named("aDecimal"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1392,7 +1416,7 @@ public void testDecimalLogicalTypeWithDeprecatedPrecision() { .as(LogicalTypeAnnotation.decimalType(3, 4)) .precision(4) .named("aDecimal"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -1413,10 +1437,10 @@ public void testTimestampLogicalTypeWithUTCParameter() { PrimitiveType nonUtcMicrosActual = Types.required(INT64).as(timestampType(false, MICROS)).named("aTimestamp"); - Assert.assertEquals(utcMillisExpected, utcMillisActual); - Assert.assertEquals(nonUtcMillisExpected, nonUtcMillisActual); - Assert.assertEquals(utcMicrosExpected, utcMicrosActual); - Assert.assertEquals(nonUtcMicrosExpected, nonUtcMicrosActual); + assertThat(utcMillisActual).isEqualTo(utcMillisExpected); + assertThat(nonUtcMillisActual).isEqualTo(nonUtcMillisExpected); + assertThat(utcMicrosActual).isEqualTo(utcMicrosExpected); + assertThat(nonUtcMicrosActual).isEqualTo(nonUtcMicrosExpected); } @Test @@ -1437,7 +1461,7 @@ public void testVariantLogicalType() { .as(LogicalTypeAnnotation.variantType(specVersion)) .named(name); - assertEquals(variantExpected, variantActual); + assertThat(variantActual).isEqualTo(variantExpected); } @Test @@ -1462,7 +1486,7 @@ public void testVariantLogicalTypeWithShredded() { .as(LogicalTypeAnnotation.variantType(specVersion)) .named(name); - assertEquals(variantExpected, variantActual); + assertThat(variantActual).isEqualTo(variantExpected); } @Test @@ -1494,7 +1518,7 @@ public void testGeometryLogicalType() { PrimitiveType defaultCrsActual = Types.required(BINARY) .as(LogicalTypeAnnotation.geometryType("OGC:CRS84")) .named("aGeometry"); - Assert.assertEquals(defaultCrsExpected, defaultCrsActual); + assertThat(defaultCrsActual).isEqualTo(defaultCrsExpected); // Test with custom CRS PrimitiveType customCrsExpected = @@ -1502,7 +1526,7 @@ public void testGeometryLogicalType() { PrimitiveType customCrsActual = Types.required(BINARY) .as(LogicalTypeAnnotation.geometryType("EPSG:4326")) .named("aGeometry"); - Assert.assertEquals(customCrsExpected, customCrsActual); + assertThat(customCrsActual).isEqualTo(customCrsExpected); // Test with optional repetition PrimitiveType optionalGeometryExpected = @@ -1510,7 +1534,7 @@ public void testGeometryLogicalType() { PrimitiveType optionalGeometryActual = Types.optional(BINARY) .as(LogicalTypeAnnotation.geometryType("OGC:CRS84")) .named("aGeometry"); - Assert.assertEquals(optionalGeometryExpected, optionalGeometryActual); + assertThat(optionalGeometryActual).isEqualTo(optionalGeometryExpected); } @Test @@ -1521,7 +1545,7 @@ public void testGeographyLogicalType() { PrimitiveType defaultCrsActual = Types.required(BINARY) .as(LogicalTypeAnnotation.geographyType("OGC:CRS84", null)) .named("aGeography"); - Assert.assertEquals(defaultCrsExpected, defaultCrsActual); + assertThat(defaultCrsActual).isEqualTo(defaultCrsExpected); // Test with custom CRS and no edge algorithm PrimitiveType customCrsExpected = new PrimitiveType( @@ -1529,7 +1553,7 @@ public void testGeographyLogicalType() { PrimitiveType customCrsActual = Types.required(BINARY) .as(LogicalTypeAnnotation.geographyType("EPSG:4326", null)) .named("aGeography"); - Assert.assertEquals(customCrsExpected, customCrsActual); + assertThat(customCrsActual).isEqualTo(customCrsExpected); // Test with custom CRS and edge algorithm EdgeInterpolationAlgorithm greatCircle = EdgeInterpolationAlgorithm.SPHERICAL; @@ -1538,7 +1562,7 @@ public void testGeographyLogicalType() { PrimitiveType customCrsWithEdgeAlgorithmActual = Types.required(BINARY) .as(LogicalTypeAnnotation.geographyType("EPSG:4326", greatCircle)) .named("aGeography"); - Assert.assertEquals(customCrsWithEdgeAlgorithmExpected, customCrsWithEdgeAlgorithmActual); + assertThat(customCrsWithEdgeAlgorithmActual).isEqualTo(customCrsWithEdgeAlgorithmExpected); // Test with optional repetition PrimitiveType optionalGeographyExpected = new PrimitiveType( @@ -1546,7 +1570,7 @@ public void testGeographyLogicalType() { PrimitiveType optionalGeographyActual = Types.optional(BINARY) .as(LogicalTypeAnnotation.geographyType("OGC:CRS84", null)) .named("aGeography"); - Assert.assertEquals(optionalGeographyExpected, optionalGeographyActual); + assertThat(optionalGeographyActual).isEqualTo(optionalGeographyExpected); } @Test @@ -1556,7 +1580,7 @@ public void testGeographyLogicalTypeWithoutEdgeInterpolationAlgorithm() { new PrimitiveType(REQUIRED, BINARY, "aGeography", LogicalTypeAnnotation.geographyType()); PrimitiveType defaultCrsActual = Types.required(BINARY).as(LogicalTypeAnnotation.geographyType()).named("aGeography"); - Assert.assertEquals(defaultCrsExpected, defaultCrsActual); + assertThat(defaultCrsActual).isEqualTo(defaultCrsExpected); // Test with custom CRS and no edge algorithm PrimitiveType customCrsExpected = new PrimitiveType( @@ -1564,7 +1588,7 @@ public void testGeographyLogicalTypeWithoutEdgeInterpolationAlgorithm() { PrimitiveType customCrsActual = Types.required(BINARY) .as(LogicalTypeAnnotation.geographyType("EPSG:4326", null)) .named("aGeography"); - Assert.assertEquals(customCrsExpected, customCrsActual); + assertThat(customCrsActual).isEqualTo(customCrsExpected); // Test with custom CRS and edge algorithm PrimitiveType customCrsWithEdgeAlgorithmExpected = new PrimitiveType( @@ -1572,29 +1596,13 @@ public void testGeographyLogicalTypeWithoutEdgeInterpolationAlgorithm() { PrimitiveType customCrsWithEdgeAlgorithmActual = Types.required(BINARY) .as(LogicalTypeAnnotation.geographyType("EPSG:4326", null)) .named("aGeography"); - Assert.assertEquals(customCrsWithEdgeAlgorithmExpected, customCrsWithEdgeAlgorithmActual); + assertThat(customCrsWithEdgeAlgorithmActual).isEqualTo(customCrsWithEdgeAlgorithmExpected); // Test with optional repetition PrimitiveType optionalGeographyExpected = new PrimitiveType(OPTIONAL, BINARY, "aGeography", LogicalTypeAnnotation.geographyType()); PrimitiveType optionalGeographyActual = Types.optional(BINARY).as(LogicalTypeAnnotation.geographyType()).named("aGeography"); - Assert.assertEquals(optionalGeographyExpected, optionalGeographyActual); - } - - /** - * A convenience method to avoid a large number of @Test(expected=...) tests - * - * @param message A String message to describe this assertion - * @param expected An Exception class that the Runnable should throw - * @param callable A Callable that is expected to throw the exception - */ - public static void assertThrows(String message, Class expected, Callable callable) { - try { - callable.call(); - Assert.fail("No exception was thrown (" + message + "), expected: " + expected.getName()); - } catch (Exception actual) { - Assert.assertEquals(message, expected, actual.getClass()); - } + assertThat(optionalGeographyActual).isEqualTo(optionalGeographyExpected); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuildersWithLogicalTypes.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuildersWithLogicalTypes.java index 7cd4c5e995..996134f147 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuildersWithLogicalTypes.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeBuildersWithLogicalTypes.java @@ -40,15 +40,11 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT64; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT96; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import java.util.concurrent.Callable; import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName; import org.apache.parquet.schema.Type.Repetition; -import org.junit.Assert; import org.junit.Test; public class TestTypeBuildersWithLogicalTypes { @@ -66,7 +62,7 @@ public void testGroupTypeConstruction() { .addFields(f2, f3) .named("g1") .named(name); - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); switch (repetition) { case REQUIRED: @@ -94,7 +90,7 @@ public void testGroupTypeConstruction() { .named(name); break; } - Assert.assertEquals(expected, built); + assertThat(built).isEqualTo(expected); } } @@ -108,7 +104,7 @@ public void testDecimalAnnotation() { .as(decimalType(2, 9)) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); // int64 primitive type expected = new MessageType( "DecimalMessage", new PrimitiveType(REQUIRED, INT64, 0, "aDecimal", decimalType(2, 18), null)); @@ -119,7 +115,7 @@ public void testDecimalAnnotation() { .scale(2) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); // binary primitive type expected = new MessageType( "DecimalMessage", new PrimitiveType(REQUIRED, BINARY, 0, "aDecimal", decimalType(2, 9), null)); @@ -128,7 +124,7 @@ public void testDecimalAnnotation() { .as(decimalType(2, 9)) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); // fixed primitive type expected = new MessageType( "DecimalMessage", @@ -139,70 +135,75 @@ public void testDecimalAnnotation() { .as(decimalType(2, 9)) .named("aDecimal") .named("DecimalMessage"); - Assert.assertEquals(expected, builderType); + assertThat(builderType).isEqualTo(expected); } @Test public void testDecimalAnnotationPrecisionScaleBound() { - assertThrows( - "Should reject scale greater than precision", IllegalArgumentException.class, () -> Types.buildMessage() + String expectedMessage = "Invalid DECIMAL scale: 4 cannot be greater than precision: 3"; + assertThatThrownBy(() -> Types.buildMessage() .required(INT32) .as(decimalType(4, 3)) .named("aDecimal") - .named("DecimalMessage")); - assertThrows( - "Should reject scale greater than precision", IllegalArgumentException.class, () -> Types.buildMessage() + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(expectedMessage); + assertThatThrownBy(() -> Types.buildMessage() .required(INT64) .as(decimalType(4, 3)) .named("aDecimal") - .named("DecimalMessage")); - assertThrows( - "Should reject scale greater than precision", IllegalArgumentException.class, () -> Types.buildMessage() + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(expectedMessage); + assertThatThrownBy(() -> Types.buildMessage() .required(BINARY) .as(decimalType(4, 3)) .named("aDecimal") - .named("DecimalMessage")); - assertThrows( - "Should reject scale greater than precision", IllegalArgumentException.class, () -> Types.buildMessage() + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(expectedMessage); + assertThatThrownBy(() -> Types.buildMessage() .required(FIXED_LEN_BYTE_ARRAY) .length(7) .as(decimalType(4, 3)) .named("aDecimal") - .named("DecimalMessage")); + .named("DecimalMessage")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage(expectedMessage); } @Test public void testDecimalAnnotationLengthCheck() { // maximum precision for 4 bytes is 9 - assertThrows("should reject precision 10 with length 4", IllegalStateException.class, () -> Types.required( - FIXED_LEN_BYTE_ARRAY) - .length(4) - .as(decimalType(2, 10)) - .named("aDecimal")); - assertThrows( - "should reject precision 10 with length 4", - IllegalStateException.class, - () -> Types.required(INT32).as(decimalType(2, 10)).named("aDecimal")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(4) + .as(decimalType(2, 10)) + .named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FIXED(4) cannot store 10 digits (max 9)"); + assertThatThrownBy(() -> Types.required(INT32).as(decimalType(2, 10)).named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INT32 cannot store 10 digits (max 9)"); // maximum precision for 8 bytes is 19 - assertThrows("should reject precision 19 with length 8", IllegalStateException.class, () -> Types.required( - FIXED_LEN_BYTE_ARRAY) - .length(8) - .as(decimalType(4, 19)) - .named("aDecimal")); - assertThrows( - "should reject precision 19 with length 8", - IllegalStateException.class, - () -> Types.required(INT64).length(8).as(decimalType(4, 19)).named("aDecimal")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(8) + .as(decimalType(4, 19)) + .named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FIXED(8) cannot store 19 digits (max 18)"); + assertThatThrownBy(() -> + Types.required(INT64).length(8).as(decimalType(4, 19)).named("aDecimal")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INT64 cannot store 19 digits (max 18)"); } @Test public void testDECIMALAnnotationRejectsUnsupportedTypes() { PrimitiveTypeName[] unsupported = new PrimitiveTypeName[] {BOOLEAN, INT96, DOUBLE, FLOAT}; for (final PrimitiveTypeName type : unsupported) { - assertThrows( - "Should reject non-binary type: " + type, - IllegalStateException.class, - () -> Types.required(type).as(decimalType(2, 9)).named("d")); + assertThatThrownBy(() -> Types.required(type).as(decimalType(2, 9)).named("d")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("DECIMAL can only annotate INT32, INT64, BINARY, and FIXED"); } } @@ -212,7 +213,7 @@ public void testBinaryAnnotations() { for (final LogicalTypeAnnotation logicalType : types) { PrimitiveType expected = new PrimitiveType(REQUIRED, BINARY, "col", logicalType); PrimitiveType string = Types.required(BINARY).as(logicalType).named("col"); - Assert.assertEquals(expected, string); + assertThat(string).isEqualTo(expected); } } @@ -222,7 +223,7 @@ public void testFloat16Annotations() { PrimitiveType expected = new PrimitiveType(REQUIRED, FIXED_LEN_BYTE_ARRAY, 2, "col", type, null); PrimitiveType string = Types.required(FIXED_LEN_BYTE_ARRAY).as(type).length(2).named("col"); - Assert.assertEquals(expected, string); + assertThat(string).isEqualTo(expected); } @Test @@ -232,18 +233,22 @@ public void testBinaryAnnotationsRejectsNonBinary() { for (final LogicalTypeAnnotation logicalType : types) { PrimitiveTypeName[] nonBinary = new PrimitiveTypeName[] {BOOLEAN, INT32, INT64, INT96, DOUBLE, FLOAT}; for (final PrimitiveTypeName type : nonBinary) { - assertThrows( - "Should reject non-binary type: " + type, - IllegalStateException.class, - () -> Types.required(type).as(logicalType).named("col")); + String expectedMessage = logicalType.equals(float16Type()) + ? "FLOAT16 can only annotate FIXED_LEN_BYTE_ARRAY(2)" + : logicalType + " can only annotate BINARY"; + assertThatThrownBy(() -> Types.required(type).as(logicalType).named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(expectedMessage); } - assertThrows( - "Should reject non-binary type: FIXED_LEN_BYTE_ARRAY", - IllegalStateException.class, - () -> Types.required(FIXED_LEN_BYTE_ARRAY) + String fixedMessage = logicalType.equals(float16Type()) + ? "FLOAT16 can only annotate FIXED_LEN_BYTE_ARRAY(2)" + : logicalType + " can only annotate BINARY"; + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) .length(1) .as(logicalType) - .named("col")); + .named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(fixedMessage); } } @@ -257,7 +262,7 @@ public void testInt32Annotations() { for (LogicalTypeAnnotation logicalType : types) { PrimitiveType expected = new PrimitiveType(REQUIRED, INT32, "col", logicalType); PrimitiveType date = Types.required(INT32).as(logicalType).named("col"); - Assert.assertEquals(expected, date); + assertThat(date).isEqualTo(expected); } } @@ -271,18 +276,16 @@ public void testInt32AnnotationsRejectNonInt32() { for (final LogicalTypeAnnotation logicalType : types) { PrimitiveTypeName[] nonInt32 = new PrimitiveTypeName[] {BOOLEAN, INT64, INT96, DOUBLE, FLOAT, BINARY}; for (final PrimitiveTypeName type : nonInt32) { - assertThrows( - "Should reject non-int32 type: " + type, - IllegalStateException.class, - () -> Types.required(type).as(logicalType).named("col")); + assertThatThrownBy(() -> Types.required(type).as(logicalType).named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(logicalType + " can only annotate INT32"); } - assertThrows( - "Should reject non-int32 type: FIXED_LEN_BYTE_ARRAY", - IllegalStateException.class, - () -> Types.required(FIXED_LEN_BYTE_ARRAY) + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) .length(1) .as(logicalType) - .named("col")); + .named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(logicalType + " can only annotate INT32"); } } @@ -299,7 +302,7 @@ public void testInt64Annotations() { for (LogicalTypeAnnotation logicalType : types) { PrimitiveType expected = new PrimitiveType(REQUIRED, INT64, "col", logicalType); PrimitiveType date = Types.required(INT64).as(logicalType).named("col"); - Assert.assertEquals(expected, date); + assertThat(date).isEqualTo(expected); } } @@ -316,15 +319,16 @@ public void testInt64AnnotationsRejectNonInt64() { for (final LogicalTypeAnnotation logicalType : types) { PrimitiveTypeName[] nonInt64 = new PrimitiveTypeName[] {BOOLEAN, INT32, INT96, DOUBLE, FLOAT, BINARY}; for (final PrimitiveTypeName type : nonInt64) { - assertThrows("Should reject non-int64 type: " + type, IllegalStateException.class, (Callable) - () -> Types.required(type).as(logicalType).named("col")); + assertThatThrownBy(() -> Types.required(type).as(logicalType).named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(logicalType + " can only annotate INT64"); } - assertThrows( - "Should reject non-int64 type: FIXED_LEN_BYTE_ARRAY", IllegalStateException.class, (Callable) - () -> Types.required(FIXED_LEN_BYTE_ARRAY) - .length(1) - .as(logicalType) - .named("col")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(1) + .as(logicalType) + .named("col")) + .isInstanceOf(IllegalStateException.class) + .hasMessage(logicalType + " can only annotate INT64"); } } @@ -332,32 +336,38 @@ public void testInt64AnnotationsRejectNonInt64() { public void testIntervalAnnotationRejectsNonFixed() { PrimitiveTypeName[] nonFixed = new PrimitiveTypeName[] {BOOLEAN, INT32, INT64, INT96, DOUBLE, FLOAT, BINARY}; for (final PrimitiveTypeName type : nonFixed) { - assertThrows( - "Should reject non-fixed type: " + type, IllegalStateException.class, () -> Types.required(type) + assertThatThrownBy(() -> Types.required(type) .as(LogicalTypeAnnotation.IntervalLogicalTypeAnnotation.getInstance()) - .named("interval")); + .named("interval")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)"); } } @Test public void testIntervalAnnotationRejectsNonFixed12() { - assertThrows("Should reject fixed with length != 12: " + 11, IllegalStateException.class, () -> Types.required( - FIXED_LEN_BYTE_ARRAY) - .length(11) - .as(LogicalTypeAnnotation.IntervalLogicalTypeAnnotation.getInstance()) - .named("interval")); + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(11) + .as(LogicalTypeAnnotation.IntervalLogicalTypeAnnotation.getInstance()) + .named("interval")) + .isInstanceOf(IllegalStateException.class) + .hasMessage("INTERVAL can only annotate FIXED_LEN_BYTE_ARRAY(12)"); } @Test public void testTypeConstructionWithUnsupportedColumnOrder() { - assertThrows(null, IllegalArgumentException.class, () -> Types.optional(INT96) - .columnOrder(ColumnOrder.typeDefined()) - .named("int96_unsupported")); - assertThrows(null, IllegalArgumentException.class, () -> Types.optional(PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY) - .length(12) - .as(LogicalTypeAnnotation.IntervalLogicalTypeAnnotation.getInstance()) - .columnOrder(ColumnOrder.typeDefined()) - .named("interval_unsupported")); + assertThatThrownBy(() -> Types.optional(INT96) + .columnOrder(ColumnOrder.typeDefined()) + .named("int96_unsupported")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The column order TYPE_DEFINED_ORDER is not supported by INT96"); + assertThatThrownBy(() -> Types.optional(PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY) + .length(12) + .as(LogicalTypeAnnotation.IntervalLogicalTypeAnnotation.getInstance()) + .columnOrder(ColumnOrder.typeDefined()) + .named("interval_unsupported")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The column order TYPE_DEFINED_ORDER is not supported by FIXED_LEN_BYTE_ARRAY (INTERVAL)"); } @Test @@ -367,7 +377,7 @@ public void testDecimalLogicalType() { PrimitiveType actual = Types.required(BINARY) .as(LogicalTypeAnnotation.decimalType(3, 4)) .named("aDecimal"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -378,7 +388,7 @@ public void testDecimalLogicalTypeWithDeprecatedScale() { .as(LogicalTypeAnnotation.decimalType(3, 4)) .scale(3) .named("aDecimal"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -389,7 +399,7 @@ public void testDecimalLogicalTypeWithDeprecatedPrecision() { .as(LogicalTypeAnnotation.decimalType(3, 4)) .precision(4) .named("aDecimal"); - Assert.assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test @@ -410,10 +420,10 @@ public void testTimestampLogicalTypeWithUTCParameter() { PrimitiveType nonUtcMicrosActual = Types.required(INT64).as(timestampType(false, MICROS)).named("aTimestamp"); - Assert.assertEquals(utcMillisExpected, utcMillisActual); - Assert.assertEquals(nonUtcMillisExpected, nonUtcMillisActual); - Assert.assertEquals(utcMicrosExpected, utcMicrosActual); - Assert.assertEquals(nonUtcMicrosExpected, nonUtcMicrosActual); + assertThat(utcMillisActual).isEqualTo(utcMillisExpected); + assertThat(nonUtcMillisActual).isEqualTo(nonUtcMillisExpected); + assertThat(utcMicrosActual).isEqualTo(utcMicrosExpected); + assertThat(nonUtcMicrosActual).isEqualTo(nonUtcMicrosExpected); } @Test @@ -439,46 +449,50 @@ public void testDecimalLogicalTypeWithDeprecatedPrecisionMismatch() { @Test public void testUUIDLogicalType() { - assertEquals( - "required fixed_len_byte_array(16) uuid_field (UUID)", - Types.required(FIXED_LEN_BYTE_ARRAY) + assertThat(Types.required(FIXED_LEN_BYTE_ARRAY) .length(16) + .as(uuidType()) + .named("uuid_field")) + .asString() + .isEqualTo("required fixed_len_byte_array(16) uuid_field (UUID)"); + + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(10) + .as(uuidType()) + .named("uuid_field") + .toString()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("UUID can only annotate FIXED_LEN_BYTE_ARRAY(16)"); + assertThatThrownBy(() -> Types.required(BINARY) .as(uuidType()) .named("uuid_field") - .toString()); - - assertThrows("Should fail with invalid length", IllegalStateException.class, () -> Types.required( - FIXED_LEN_BYTE_ARRAY) - .length(10) - .as(uuidType()) - .named("uuid_field") - .toString()); - assertThrows( - "Should fail with invalid type", - IllegalStateException.class, - () -> Types.required(BINARY).as(uuidType()).named("uuid_field").toString()); + .toString()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("UUID can only annotate FIXED_LEN_BYTE_ARRAY(16)"); } @Test public void testFloat16LogicalType() { - assertEquals( - "required fixed_len_byte_array(2) float16_field (FLOAT16)", - Types.required(FIXED_LEN_BYTE_ARRAY) + assertThat(Types.required(FIXED_LEN_BYTE_ARRAY) .length(2) .as(float16Type()) + .named("float16_field")) + .asString() + .isEqualTo("required fixed_len_byte_array(2) float16_field (FLOAT16)"); + + assertThatThrownBy(() -> Types.required(FIXED_LEN_BYTE_ARRAY) + .length(10) + .as(float16Type()) .named("float16_field") - .toString()); - - assertThrows("Should fail with invalid length", IllegalStateException.class, () -> Types.required( - FIXED_LEN_BYTE_ARRAY) - .length(10) - .as(float16Type()) - .named("float16_field") - .toString()); - assertThrows("Should fail with invalid type", IllegalStateException.class, () -> Types.required(BINARY) - .as(float16Type()) - .named("float16_field") - .toString()); + .toString()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FLOAT16 can only annotate FIXED_LEN_BYTE_ARRAY(2)"); + assertThatThrownBy(() -> Types.required(BINARY) + .as(float16Type()) + .named("float16_field") + .toString()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("FLOAT16 can only annotate FIXED_LEN_BYTE_ARRAY(2)"); } @Test @@ -492,18 +506,19 @@ public void testVariantLogicalType() { Types.required(BINARY).named("metadata"), Types.required(BINARY).named("value")); - assertEquals( - "required group variant_field (VARIANT(1)) {\n" + assertThat(variant) + .asString() + .isEqualTo("required group variant_field (VARIANT(1)) {\n" + " required binary metadata;\n" + " required binary value;\n" - + "}", - variant.toString()); + + "}"); LogicalTypeAnnotation annotation = variant.getLogicalTypeAnnotation(); - assertEquals(LogicalTypeAnnotation.LogicalTypeToken.VARIANT, annotation.getType()); - assertNull(annotation.toOriginalType()); - assertTrue(annotation instanceof LogicalTypeAnnotation.VariantLogicalTypeAnnotation); - assertEquals(specVersion, ((LogicalTypeAnnotation.VariantLogicalTypeAnnotation) annotation).getSpecVersion()); + assertThat(annotation.getType()).isEqualTo(LogicalTypeAnnotation.LogicalTypeToken.VARIANT); + assertThat(annotation.toOriginalType()).isNull(); + assertThat(annotation).isInstanceOf(LogicalTypeAnnotation.VariantLogicalTypeAnnotation.class); + assertThat(((LogicalTypeAnnotation.VariantLogicalTypeAnnotation) annotation).getSpecVersion()) + .isEqualTo(specVersion); } @Test @@ -519,34 +534,19 @@ public void testVariantLogicalTypeWithShredded() { Types.optional(BINARY).named("value"), Types.optional(BINARY).as(LogicalTypeAnnotation.stringType()).named("typed_value")); - assertEquals( - "required group variant_field (VARIANT(1)) {\n" + assertThat(variant) + .asString() + .isEqualTo("required group variant_field (VARIANT(1)) {\n" + " required binary metadata;\n" + " optional binary value;\n" + " optional binary typed_value (STRING);\n" - + "}", - variant.toString()); + + "}"); LogicalTypeAnnotation annotation = variant.getLogicalTypeAnnotation(); - assertEquals(LogicalTypeAnnotation.LogicalTypeToken.VARIANT, annotation.getType()); - assertNull(annotation.toOriginalType()); - assertTrue(annotation instanceof LogicalTypeAnnotation.VariantLogicalTypeAnnotation); - assertEquals(specVersion, ((LogicalTypeAnnotation.VariantLogicalTypeAnnotation) annotation).getSpecVersion()); - } - - /** - * A convenience method to avoid a large number of @Test(expected=...) tests - * - * @param message A String message to describe this assertion - * @param expected An Exception class that the Runnable should throw - * @param callable A Callable that is expected to throw the exception - */ - public static void assertThrows(String message, Class expected, Callable callable) { - try { - callable.call(); - Assert.fail("No exception was thrown (" + message + "), expected: " + expected.getName()); - } catch (Exception actual) { - Assert.assertEquals(message, expected, actual.getClass()); - } + assertThat(annotation.getType()).isEqualTo(LogicalTypeAnnotation.LogicalTypeToken.VARIANT); + assertThat(annotation.toOriginalType()).isNull(); + assertThat(annotation).isInstanceOf(LogicalTypeAnnotation.VariantLogicalTypeAnnotation.class); + assertThat(((LogicalTypeAnnotation.VariantLogicalTypeAnnotation) annotation).getSpecVersion()) + .isEqualTo(specVersion); } } diff --git a/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeUtil.java b/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeUtil.java index aa12ef7f35..60df2809bc 100644 --- a/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeUtil.java +++ b/parquet-column/src/test/java/org/apache/parquet/schema/TestTypeUtil.java @@ -22,8 +22,8 @@ import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.BINARY; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.apache.parquet.schema.Type.Repetition.REPEATED; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -import java.util.concurrent.Callable; import org.junit.Test; public class TestTypeUtil { @@ -37,11 +37,10 @@ public void testWriteCheckMessageType() { .named("b") .named("valid_schema")); - TestTypeBuilders.assertThrows( - "Should complain about empty MessageType", InvalidSchemaException.class, (Callable) () -> { - TypeUtil.checkValidWriteSchema(new MessageType("invalid_schema")); - return null; - }); + MessageType invalidSchema = new MessageType("invalid_schema"); + assertThatThrownBy(() -> TypeUtil.checkValidWriteSchema(invalidSchema)) + .isInstanceOf(InvalidSchemaException.class) + .hasMessage("Cannot write a schema with an empty group: " + invalidSchema); } @Test @@ -54,11 +53,10 @@ public void testWriteCheckGroupType() { .named("b") .named("valid_group")); - TestTypeBuilders.assertThrows( - "Should complain about empty GroupType", InvalidSchemaException.class, (Callable) () -> { - TypeUtil.checkValidWriteSchema(new GroupType(REPEATED, "invalid_group")); - return null; - }); + GroupType invalidGroup = new GroupType(REPEATED, "invalid_group"); + assertThatThrownBy(() -> TypeUtil.checkValidWriteSchema(invalidGroup)) + .isInstanceOf(InvalidSchemaException.class) + .hasMessage("Cannot write a schema with an empty group: " + invalidGroup); } @Test @@ -73,12 +71,11 @@ public void testWriteCheckNestedGroupType() { .named("valid_group") .named("valid_message")); - TestTypeBuilders.assertThrows( - "Should complain about empty GroupType", InvalidSchemaException.class, (Callable) () -> { - TypeUtil.checkValidWriteSchema(Types.buildMessage() - .addField(new GroupType(REPEATED, "invalid_group")) - .named("invalid_message")); - return null; - }); + MessageType invalidMessage = Types.buildMessage() + .addField(new GroupType(REPEATED, "invalid_group")) + .named("invalid_message"); + assertThatThrownBy(() -> TypeUtil.checkValidWriteSchema(invalidMessage)) + .isInstanceOf(InvalidSchemaException.class) + .hasMessage("Cannot write a schema with an empty group: " + invalidMessage.getType("invalid_group")); } }