From 9d93287298ac85632752497aed0c7604e8f7777f Mon Sep 17 00:00:00 2001 From: Hyunseok Seo Date: Wed, 19 Jun 2024 09:17:03 +0900 Subject: [PATCH] GH-42045: [Java] Update Unit Tests for Flight Module (#42158) ### Rationale for this change Update package from JUnit 4(`org.junit`) to JUnit 5(`org.junit.jupiter`). ### What changes are included in this PR? - **common** for all module - Step 1. Replacing `org.junit` with `org.junit.jupiter.api` - Step 2. Updating `Assertions.assertXXX` to `assertXXX` using static imports - `flight-core` - [x] Updating common - [x] Updating annotations - [x] Doing self review - `flight-integration-tests` - nothing to change - `flight-sql` - [x] Updating common - [x] Doing self review - `flight-sql-jdbc-core` - [x] Updating common - [x] Updating annotations - Adding annotations different from before: - `ErrorCollection` - `TestRule` for `FlightServerTestExtension` and `RootAllocatorExtension` - `ExpectedException` - [x] Doing self review - `flight-sql-jdbc-driver` - [x] Updating common - [x] Updating annotations - [x] Doing self review ### Are these changes tested? Yes, existing tests have passed. ### Are there any user-facing changes? No. * GitHub Issue: #42045 Authored-by: Hyunseok Seo Signed-off-by: David Li --- .../apache/arrow/flight/FlightTestUtil.java | 8 +- .../arrow/flight/TestApplicationMetadata.java | 24 +- .../org/apache/arrow/flight/TestAuth.java | 6 +- .../apache/arrow/flight/TestBackPressure.java | 4 +- .../arrow/flight/TestBasicOperation.java | 109 +++--- .../apache/arrow/flight/TestCallOptions.java | 23 +- .../arrow/flight/TestClientMiddleware.java | 23 +- .../arrow/flight/TestErrorMetadata.java | 30 +- .../apache/arrow/flight/TestFlightClient.java | 41 +-- .../arrow/flight/TestFlightGrpcUtils.java | 50 +-- .../arrow/flight/TestFlightService.java | 15 +- .../apache/arrow/flight/TestLargeMessage.java | 4 +- .../arrow/flight/TestServerMiddleware.java | 80 ++--- .../arrow/flight/TestServerOptions.java | 20 +- .../java/org/apache/arrow/flight/TestTls.java | 11 +- .../arrow/flight/auth/TestBasicAuth.java | 11 +- .../arrow/flight/auth2/TestBasicAuth2.java | 25 +- .../arrow/flight/client/CustomHeaderTest.java | 16 +- .../flight/client/TestCookieHandling.java | 37 ++- .../arrow/flight/grpc/TestStatusUtils.java | 26 +- .../jdbc/ArrowDatabaseMetadataTest.java | 310 +++++++++--------- .../driver/jdbc/ArrowFlightJdbcArrayTest.java | 74 +++-- .../ArrowFlightJdbcConnectionCookieTest.java | 25 +- ...lightJdbcConnectionPoolDataSourceTest.java | 75 +++-- .../jdbc/ArrowFlightJdbcCursorTest.java | 8 +- .../jdbc/ArrowFlightJdbcDriverTest.java | 39 ++- .../jdbc/ArrowFlightJdbcFactoryTest.java | 20 +- .../driver/jdbc/ArrowFlightJdbcTimeTest.java | 34 +- .../ArrowFlightPreparedStatementTest.java | 52 +-- .../jdbc/ArrowFlightStatementExecuteTest.java | 64 ++-- ...ArrowFlightStatementExecuteUpdateTest.java | 96 +++--- .../driver/jdbc/ConnectionMutualTlsTest.java | 81 ++--- .../arrow/driver/jdbc/ConnectionTest.java | 145 ++++---- .../jdbc/ConnectionTlsRootCertsTest.java | 69 ++-- .../arrow/driver/jdbc/ConnectionTlsTest.java | 141 ++++---- ...le.java => FlightServerTestExtension.java} | 66 ++-- .../driver/jdbc/ResultSetMetadataTest.java | 136 ++++---- .../arrow/driver/jdbc/ResultSetTest.java | 104 +++--- .../driver/jdbc/TokenAuthenticationTest.java | 29 +- .../ArrowFlightJdbcAccessorFactoryTest.java | 158 ++++----- .../accessor/ArrowFlightJdbcAccessorTest.java | 150 ++++----- ...ArrowFlightJdbcNullVectorAccessorTest.java | 10 +- ...rowFlightJdbcBinaryVectorAccessorTest.java | 201 ++++++------ ...ArrowFlightJdbcDateVectorAccessorTest.java | 168 +++++----- ...wFlightJdbcDurationVectorAccessorTest.java | 27 +- ...wFlightJdbcIntervalVectorAccessorTest.java | 205 ++++++------ ...FlightJdbcTimeStampVectorAccessorTest.java | 295 +++++++++-------- ...ArrowFlightJdbcTimeVectorAccessorTest.java | 175 +++++----- ...stractArrowFlightJdbcListAccessorTest.java | 125 +++---- ...rrowFlightJdbcUnionVectorAccessorTest.java | 12 +- ...lightJdbcDenseUnionVectorAccessorTest.java | 30 +- .../ArrowFlightJdbcMapVectorAccessorTest.java | 118 +++---- ...rowFlightJdbcStructVectorAccessorTest.java | 38 +-- ...rrowFlightJdbcUnionVectorAccessorTest.java | 30 +- ...owFlightJdbcBaseIntVectorAccessorTest.java | 145 ++++---- ...ightJdbcBaseIntVectorAccessorUnitTest.java | 48 +-- .../ArrowFlightJdbcBitVectorAccessorTest.java | 29 +- ...owFlightJdbcDecimalVectorAccessorTest.java | 217 +++++++----- ...rowFlightJdbcFloat4VectorAccessorTest.java | 54 ++- ...rowFlightJdbcFloat8VectorAccessorTest.java | 48 ++- ...owFlightJdbcVarCharVectorAccessorTest.java | 263 +++++++-------- ...rrowFlightSqlClientHandlerBuilderTest.java | 58 ++-- .../utils/ClientAuthenticationUtilsTest.java | 28 +- .../driver/jdbc/utils/AccessorTestUtils.java | 10 +- .../ArrowFlightConnectionConfigImplTest.java | 90 +++-- .../ArrowFlightConnectionPropertyTest.java | 57 ++-- .../jdbc/utils/ConnectionWrapperTest.java | 101 +++--- .../driver/jdbc/utils/ConvertUtilsTest.java | 55 ++-- .../jdbc/utils/CoreMockedSqlProducers.java | 26 +- .../driver/jdbc/utils/DateTimeUtilsTest.java | 14 +- .../utils/FlightEndpointDataQueueTest.java | 25 +- .../driver/jdbc/utils/ResultSetTestUtils.java | 115 +------ ...e.java => RootAllocatorTestExtension.java} | 31 +- .../arrow/driver/jdbc/utils/SqlTypesTest.java | 4 +- .../VectorSchemaRootTransformerTest.java | 37 ++- .../driver/jdbc/ITDriverJarValidation.java | 22 +- .../arrow/flight/sql/test/TestFlightSql.java | 56 ++-- .../sql/test/TestFlightSqlStateless.java | 6 +- .../flight/sql/test/TestFlightSqlStreams.java | 10 +- ...qlInfoOptionsUtilsBitmaskCreationTest.java | 4 +- ...SqlInfoOptionsUtilsBitmaskParsingTest.java | 4 +- 81 files changed, 2729 insertions(+), 2701 deletions(-) rename java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/{FlightServerTestRule.java => FlightServerTestExtension.java} (85%) rename java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/{RootAllocatorTestRule.java => RootAllocatorTestExtension.java} (98%) diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/FlightTestUtil.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/FlightTestUtil.java index b6d5626154aa9..767687a51785e 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/FlightTestUtil.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/FlightTestUtil.java @@ -16,6 +16,9 @@ */ package org.apache.arrow.flight; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.io.File; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; @@ -23,7 +26,6 @@ import java.util.Arrays; import java.util.List; import org.apache.arrow.vector.test.util.ArrowTestDataUtil; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.function.Executable; /** Utility methods and constants for testing flight servers. */ @@ -88,8 +90,8 @@ static boolean isNativeTransportAvailable() { * @return The thrown status. */ public static CallStatus assertCode(FlightStatusCode code, Executable r) { - final FlightRuntimeException ex = Assertions.assertThrows(FlightRuntimeException.class, r); - Assertions.assertEquals(code, ex.status().code()); + final FlightRuntimeException ex = assertThrows(FlightRuntimeException.class, r); + assertEquals(code, ex.status().code()); return ex.status(); } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestApplicationMetadata.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestApplicationMetadata.java index 475b4c74ee703..d8b1f6f05f880 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestApplicationMetadata.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestApplicationMetadata.java @@ -18,6 +18,9 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -34,7 +37,6 @@ import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -57,9 +59,9 @@ public void retrieveMetadata() { byte i = 0; while (stream.next()) { final IntVector vector = (IntVector) stream.getRoot().getVector("a"); - Assertions.assertEquals(1, vector.getValueCount()); - Assertions.assertEquals(10, vector.get(0)); - Assertions.assertEquals(i, stream.getLatestMetadata().getByte(0)); + assertEquals(1, vector.getValueCount()); + assertEquals(10, vector.get(0)); + assertEquals(i, stream.getLatestMetadata().getByte(0)); i++; } } catch (Exception e) { @@ -86,7 +88,7 @@ public void arrow6136() { // Must attempt to retrieve the result to get any server-side errors. final CallStatus status = FlightTestUtil.assertCode(FlightStatusCode.INTERNAL, writer::getResult); - Assertions.assertEquals(MESSAGE_ARROW_6136, status.description()); + assertEquals(MESSAGE_ARROW_6136, status.description()); } catch (Exception e) { throw new RuntimeException(e); } @@ -110,8 +112,8 @@ public void uploadMetadataAsync() { @Override public void onNext(PutResult val) { - Assertions.assertNotNull(val); - Assertions.assertEquals(counter, val.getApplicationMetadata().getByte(0)); + assertNotNull(val); + assertEquals(counter, val.getApplicationMetadata().getByte(0)); counter++; } }; @@ -161,8 +163,8 @@ public void uploadMetadataSync() { root.setRowCount(1); writer.putNext(metadata); try (final PutResult message = listener.poll(5000, TimeUnit.SECONDS)) { - Assertions.assertNotNull(message); - Assertions.assertEquals(i, message.getApplicationMetadata().getByte(0)); + assertNotNull(message); + assertEquals(i, message.getApplicationMetadata().getByte(0)); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } @@ -229,10 +231,10 @@ public void testMetadataEndianness() throws Exception { final FlightClient.ClientStreamListener writer = client.startPut(descriptor, root, reader); writer.completed(); try (final PutResult metadata = reader.read()) { - Assertions.assertEquals(16, metadata.getApplicationMetadata().readableBytes()); + assertEquals(16, metadata.getApplicationMetadata().readableBytes()); byte[] bytes = new byte[16]; metadata.getApplicationMetadata().readBytes(bytes); - Assertions.assertArrayEquals(EndianFlightProducer.EXPECTED_BYTES, bytes); + assertArrayEquals(EndianFlightProducer.EXPECTED_BYTES, bytes); } writer.getResult(); } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestAuth.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestAuth.java index 105a1268c689e..bd582e29a4332 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestAuth.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestAuth.java @@ -18,6 +18,7 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Iterator; import java.util.Optional; @@ -25,7 +26,6 @@ import org.apache.arrow.flight.auth.ServerAuthHandler; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestAuth { @@ -33,7 +33,7 @@ public class TestAuth { /** An auth handler that does not send messages should not block the server forever. */ @Test public void noMessages() throws Exception { - Assertions.assertThrows( + assertThrows( RuntimeException.class, () -> { try (final BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE); @@ -62,7 +62,7 @@ public byte[] getCallToken() { /** An auth handler that sends an error should not block the server forever. */ @Test public void clientError() throws Exception { - Assertions.assertThrows( + assertThrows( RuntimeException.class, () -> { try (final BufferAllocator allocator = new RootAllocator(Integer.MAX_VALUE); diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBackPressure.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBackPressure.java index d03a8c3609429..52891dd9e7175 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBackPressure.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBackPressure.java @@ -18,6 +18,7 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableList; import java.util.concurrent.ExecutorService; @@ -33,7 +34,6 @@ import org.apache.arrow.vector.types.Types.MinorType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -181,7 +181,7 @@ public void getStream( root.clear(); } long expected = wait - epsilon; - Assertions.assertTrue( + assertTrue( bpStrategy.getSleepTime() > expected, String.format( "Expected a sleep of at least %dms but only slept for %d", diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBasicOperation.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBasicOperation.java index 30423d67ec75c..5e818e6f5d02e 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBasicOperation.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestBasicOperation.java @@ -18,6 +18,12 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.base.Charsets; import com.google.protobuf.ByteString; @@ -58,7 +64,6 @@ import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; @@ -68,13 +73,13 @@ public class TestBasicOperation { @Test public void fastPathDefaults() { - Assertions.assertTrue(ArrowMessage.ENABLE_ZERO_COPY_READ); - Assertions.assertFalse(ArrowMessage.ENABLE_ZERO_COPY_WRITE); + assertTrue(ArrowMessage.ENABLE_ZERO_COPY_READ); + assertFalse(ArrowMessage.ENABLE_ZERO_COPY_WRITE); } @Test public void fallbackLocation() { - Assertions.assertEquals( + assertEquals( "arrow-flight-reuse-connection://?", Location.reuseConnection().getUri().toString()); } @@ -82,7 +87,7 @@ public void fallbackLocation() { @Test public void unknownScheme() throws URISyntaxException { final Location location = new Location("s3://unknown"); - Assertions.assertEquals("s3", location.getUri().getScheme()); + assertEquals("s3", location.getUri().getScheme()); } @Test @@ -91,7 +96,7 @@ public void unknownSchemeRemote() throws Exception { c -> { try { final FlightInfo info = c.getInfo(FlightDescriptor.path("test")); - Assertions.assertEquals( + assertEquals( new URI("https://example.com"), info.getEndpoints().get(0).getLocations().get(0).getUri()); } catch (URISyntaxException e) { @@ -103,7 +108,7 @@ public void unknownSchemeRemote() throws Exception { @Test public void roundTripTicket() throws Exception { final Ticket ticket = new Ticket(new byte[] {0, 1, 2, 3, 4, 5}); - Assertions.assertEquals(ticket, Ticket.deserialize(ticket.serialize())); + assertEquals(ticket, Ticket.deserialize(ticket.serialize())); } @Test @@ -160,26 +165,26 @@ public void roundTripInfo() throws Exception { true, IpcOption.DEFAULT); - Assertions.assertEquals(info1, FlightInfo.deserialize(info1.serialize())); - Assertions.assertEquals(info2, FlightInfo.deserialize(info2.serialize())); - Assertions.assertEquals(info3, FlightInfo.deserialize(info3.serialize())); - Assertions.assertEquals(info4, FlightInfo.deserialize(info4.serialize())); + assertEquals(info1, FlightInfo.deserialize(info1.serialize())); + assertEquals(info2, FlightInfo.deserialize(info2.serialize())); + assertEquals(info3, FlightInfo.deserialize(info3.serialize())); + assertEquals(info4, FlightInfo.deserialize(info4.serialize())); - Assertions.assertNotEquals(info3, info4); + assertNotEquals(info3, info4); - Assertions.assertFalse(info1.getOrdered()); - Assertions.assertFalse(info2.getOrdered()); - Assertions.assertFalse(info3.getOrdered()); - Assertions.assertTrue(info4.getOrdered()); + assertFalse(info1.getOrdered()); + assertFalse(info2.getOrdered()); + assertFalse(info3.getOrdered()); + assertTrue(info4.getOrdered()); } @Test public void roundTripDescriptor() throws Exception { final FlightDescriptor cmd = FlightDescriptor.command("test command".getBytes(StandardCharsets.UTF_8)); - Assertions.assertEquals(cmd, FlightDescriptor.deserialize(cmd.serialize())); + assertEquals(cmd, FlightDescriptor.deserialize(cmd.serialize())); final FlightDescriptor path = FlightDescriptor.path("foo", "bar", "test.arrow"); - Assertions.assertEquals(path, FlightDescriptor.deserialize(path.serialize())); + assertEquals(path, FlightDescriptor.deserialize(path.serialize())); } @Test @@ -190,7 +195,7 @@ public void getDescriptors() throws Exception { for (FlightInfo unused : c.listFlights(Criteria.ALL)) { count += 1; } - Assertions.assertEquals(1, count); + assertEquals(1, count); }); } @@ -203,7 +208,7 @@ public void getDescriptorsWithCriteria() throws Exception { count += 1; } - Assertions.assertEquals(0, count); + assertEquals(0, count); }); } @@ -239,22 +244,22 @@ public void doAction() throws Exception { c -> { Iterator stream = c.doAction(new Action("hello")); - Assertions.assertTrue(stream.hasNext()); + assertTrue(stream.hasNext()); Result r = stream.next(); - Assertions.assertArrayEquals("world".getBytes(Charsets.UTF_8), r.getBody()); + assertArrayEquals("world".getBytes(Charsets.UTF_8), r.getBody()); }); test( c -> { Iterator stream = c.doAction(new Action("hellooo")); - Assertions.assertTrue(stream.hasNext()); + assertTrue(stream.hasNext()); Result r = stream.next(); - Assertions.assertArrayEquals("world".getBytes(Charsets.UTF_8), r.getBody()); + assertArrayEquals("world".getBytes(Charsets.UTF_8), r.getBody()); - Assertions.assertTrue(stream.hasNext()); + assertTrue(stream.hasNext()); r = stream.next(); - Assertions.assertArrayEquals("!".getBytes(Charsets.UTF_8), r.getBody()); - Assertions.assertFalse(stream.hasNext()); + assertArrayEquals("!".getBytes(Charsets.UTF_8), r.getBody()); + assertFalse(stream.hasNext()); }); } @@ -304,9 +309,7 @@ public void propagateErrors() throws Exception { FlightTestUtil.assertCode( FlightStatusCode.UNIMPLEMENTED, () -> { - client - .doAction(new Action("invalid-action")) - .forEachRemaining(action -> Assertions.fail()); + client.doAction(new Action("invalid-action")).forEachRemaining(action -> fail()); }); }); } @@ -321,7 +324,7 @@ public void getStream() throws Exception { int value = 0; while (stream.next()) { for (int i = 0; i < root.getRowCount(); i++) { - Assertions.assertEquals(value, iv.get(i)); + assertEquals(value, iv.get(i)); value++; } } @@ -340,12 +343,12 @@ public void getStreamLargeBatch() throws Exception { test( c -> { try (final FlightStream stream = c.getStream(new Ticket(Producer.TICKET_LARGE_BATCH))) { - Assertions.assertEquals(128, stream.getRoot().getFieldVectors().size()); - Assertions.assertTrue(stream.next()); - Assertions.assertEquals(65536, stream.getRoot().getRowCount()); - Assertions.assertTrue(stream.next()); - Assertions.assertEquals(65536, stream.getRoot().getRowCount()); - Assertions.assertFalse(stream.next()); + assertEquals(128, stream.getRoot().getFieldVectors().size()); + assertTrue(stream.next()); + assertEquals(65536, stream.getRoot().getRowCount()); + assertTrue(stream.next()); + assertEquals(65536, stream.getRoot().getRowCount()); + assertFalse(stream.next()); } catch (Exception e) { throw new RuntimeException(e); } @@ -440,29 +443,29 @@ public void testProtobufRecordBatchCompatibility() throws Exception { null, /* tryZeroCopy */ false, IpcOption.DEFAULT)) { - Assertions.assertEquals(ArrowMessage.HeaderType.RECORD_BATCH, message.getMessageType()); + assertEquals(ArrowMessage.HeaderType.RECORD_BATCH, message.getMessageType()); // Should have at least one empty body buffer (there may be multiple for e.g. data and // validity) Iterator iterator = message.getBufs().iterator(); - Assertions.assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); while (iterator.hasNext()) { - Assertions.assertEquals(0, iterator.next().capacity()); + assertEquals(0, iterator.next().capacity()); } final Flight.FlightData protobufData = arrowMessageToProtobuf(marshaller, message).toBuilder().clearDataBody().build(); - Assertions.assertEquals(0, protobufData.getDataBody().size()); + assertEquals(0, protobufData.getDataBody().size()); ArrowMessage parsedMessage = marshaller.parse(new ByteArrayInputStream(protobufData.toByteArray())); // Should have an empty body buffer Iterator parsedIterator = parsedMessage.getBufs().iterator(); - Assertions.assertTrue(parsedIterator.hasNext()); - Assertions.assertEquals(0, parsedIterator.next().capacity()); + assertTrue(parsedIterator.hasNext()); + assertEquals(0, parsedIterator.next().capacity()); // Should have only one (the parser synthesizes exactly one); in the case of empty buffers, // this is equivalent - Assertions.assertFalse(parsedIterator.hasNext()); + assertFalse(parsedIterator.hasNext()); // Should not throw final ArrowRecordBatch rb = parsedMessage.asRecordBatch(); - Assertions.assertEquals(rb.computeBodyLength(), 0); + assertEquals(rb.computeBodyLength(), 0); } } } @@ -479,19 +482,19 @@ public void testProtobufSchemaCompatibility() throws Exception { ArrowMessage.createMarshaller(allocator); Flight.FlightDescriptor descriptor = FlightDescriptor.command(new byte[0]).toProtocol(); try (final ArrowMessage message = new ArrowMessage(descriptor, schema, IpcOption.DEFAULT)) { - Assertions.assertEquals(ArrowMessage.HeaderType.SCHEMA, message.getMessageType()); + assertEquals(ArrowMessage.HeaderType.SCHEMA, message.getMessageType()); // Should have no body buffers - Assertions.assertFalse(message.getBufs().iterator().hasNext()); + assertFalse(message.getBufs().iterator().hasNext()); final Flight.FlightData protobufData = arrowMessageToProtobuf(marshaller, message) .toBuilder() .setDataBody(ByteString.EMPTY) .build(); - Assertions.assertEquals(0, protobufData.getDataBody().size()); + assertEquals(0, protobufData.getDataBody().size()); final ArrowMessage parsedMessage = marshaller.parse(new ByteArrayInputStream(protobufData.toByteArray())); // Should have no body buffers - Assertions.assertFalse(parsedMessage.getBufs().iterator().hasNext()); + assertFalse(parsedMessage.getBufs().iterator().hasNext()); // Should not throw parsedMessage.asSchema(); } @@ -501,19 +504,19 @@ public void testProtobufSchemaCompatibility() throws Exception { @Test public void testGrpcInsecureLocation() throws Exception { Location location = Location.forGrpcInsecure(LOCALHOST, 9000); - Assertions.assertEquals( + assertEquals( new URI(LocationSchemes.GRPC_INSECURE, null, LOCALHOST, 9000, null, null, null), location.getUri()); - Assertions.assertEquals(new InetSocketAddress(LOCALHOST, 9000), location.toSocketAddress()); + assertEquals(new InetSocketAddress(LOCALHOST, 9000), location.toSocketAddress()); } @Test public void testGrpcTlsLocation() throws Exception { Location location = Location.forGrpcTls(LOCALHOST, 9000); - Assertions.assertEquals( + assertEquals( new URI(LocationSchemes.GRPC_TLS, null, LOCALHOST, 9000, null, null, null), location.getUri()); - Assertions.assertEquals(new InetSocketAddress(LOCALHOST, 9000), location.toSocketAddress()); + assertEquals(new InetSocketAddress(LOCALHOST, 9000), location.toSocketAddress()); } /** An example FlightProducer for test purposes. */ diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestCallOptions.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestCallOptions.java index a953739ac00ae..a54ce69812c8b 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestCallOptions.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestCallOptions.java @@ -18,6 +18,11 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import io.grpc.Metadata; import java.io.IOException; @@ -29,7 +34,6 @@ import java.util.function.Consumer; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -46,12 +50,12 @@ public void timeoutFires() { client.doAction(new Action("hang"), CallOptions.timeout(1, TimeUnit.SECONDS)); try { results.next(); - Assertions.fail("Call should have failed"); + fail("Call should have failed"); } catch (RuntimeException e) { - Assertions.assertTrue(e.getMessage().contains("deadline exceeded"), e.getMessage()); + assertTrue(e.getMessage().contains("deadline exceeded"), e.getMessage()); } Instant end = Instant.now(); - Assertions.assertTrue( + assertTrue( Duration.between(start, end).toMillis() < 1500, "Call took over 1500 ms despite timeout"); }); @@ -67,9 +71,9 @@ public void underTimeout() { // This shouldn't fail and it should complete within the timeout Iterator results = client.doAction(new Action("fast"), CallOptions.timeout(2, TimeUnit.SECONDS)); - Assertions.assertArrayEquals(new byte[] {42, 42}, results.next().getBody()); + assertArrayEquals(new byte[] {42, 42}, results.next().getBody()); Instant end = Instant.now(); - Assertions.assertTrue( + assertTrue( Duration.between(start, end).toMillis() < 2500, "Call took over 2500 ms despite timeout"); }); @@ -112,14 +116,13 @@ private void testHeaders(CallHeaders headers) { FlightServer s = FlightServer.builder(a, forGrpcInsecure(LOCALHOST, 0), producer).build().start(); FlightClient client = FlightClient.builder(a, s.getLocation()).build()) { - Assertions.assertFalse( - client.doAction(new Action(""), new HeaderCallOption(headers)).hasNext()); + assertFalse(client.doAction(new Action(""), new HeaderCallOption(headers)).hasNext()); final CallHeaders incomingHeaders = producer.headers(); for (String key : headers.keys()) { if (key.endsWith(Metadata.BINARY_HEADER_SUFFIX)) { - Assertions.assertArrayEquals(headers.getByte(key), incomingHeaders.getByte(key)); + assertArrayEquals(headers.getByte(key), incomingHeaders.getByte(key)); } else { - Assertions.assertEquals(headers.get(key), incomingHeaders.get(key)); + assertEquals(headers.get(key), incomingHeaders.get(key)); } } } catch (InterruptedException | IOException e) { diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestClientMiddleware.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestClientMiddleware.java index 5c33bd38c0ead..a49406b121084 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestClientMiddleware.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestClientMiddleware.java @@ -18,6 +18,10 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.ArrayList; @@ -29,7 +33,6 @@ import java.util.function.BiConsumer; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** A basic test of client middleware using a simplified OpenTracing-like example. */ @@ -66,9 +69,9 @@ public void middleware_propagateHeader() { FlightTestUtil.assertCode( FlightStatusCode.UNIMPLEMENTED, () -> client.listActions().forEach(actionType -> {})); }); - Assertions.assertEquals(context.outgoingSpanId, context.incomingSpanId); - Assertions.assertNotNull(context.finalStatus); - Assertions.assertEquals(FlightStatusCode.UNIMPLEMENTED, context.finalStatus.code()); + assertEquals(context.outgoingSpanId, context.incomingSpanId); + assertNotNull(context.finalStatus); + assertEquals(FlightStatusCode.UNIMPLEMENTED, context.finalStatus.code()); } /** @@ -94,17 +97,17 @@ public void testMultiValuedHeaders() { for (final Map.Entry> entry : EXPECTED_BINARY_HEADERS.entrySet()) { // Compare header values entry-by-entry because byte arrays don't compare via equals final List receivedValues = clientFactory.lastBinaryHeaders.get(entry.getKey()); - Assertions.assertNotNull(receivedValues, "Missing for header: " + entry.getKey()); - Assertions.assertEquals( + assertNotNull(receivedValues, "Missing for header: " + entry.getKey()); + assertEquals( entry.getValue().size(), receivedValues.size(), "Missing or wrong value for header: " + entry.getKey()); for (int i = 0; i < entry.getValue().size(); i++) { - Assertions.assertArrayEquals(entry.getValue().get(i), receivedValues.get(i)); + assertArrayEquals(entry.getValue().get(i), receivedValues.get(i)); } } for (final Map.Entry> entry : EXPECTED_TEXT_HEADERS.entrySet()) { - Assertions.assertEquals( + assertEquals( entry.getValue(), clientFactory.lastTextHeaders.get(entry.getKey()), "Missing or wrong value for header: " + entry.getKey()); @@ -335,11 +338,11 @@ public MultiHeaderClientMiddleware(MultiHeaderClientMiddlewareFactory factory) { public void onBeforeSendingHeaders(CallHeaders outgoingHeaders) { for (final Map.Entry> entry : EXPECTED_BINARY_HEADERS.entrySet()) { entry.getValue().forEach((value) -> outgoingHeaders.insert(entry.getKey(), value)); - Assertions.assertTrue(outgoingHeaders.containsKey(entry.getKey())); + assertTrue(outgoingHeaders.containsKey(entry.getKey())); } for (final Map.Entry> entry : EXPECTED_TEXT_HEADERS.entrySet()) { entry.getValue().forEach((value) -> outgoingHeaders.insert(entry.getKey(), value)); - Assertions.assertTrue(outgoingHeaders.containsKey(entry.getKey())); + assertTrue(outgoingHeaders.containsKey(entry.getKey())); } } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestErrorMetadata.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestErrorMetadata.java index 9a1332825f6ed..a9a3e355bc37f 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestErrorMetadata.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestErrorMetadata.java @@ -18,6 +18,11 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; @@ -30,7 +35,6 @@ import org.apache.arrow.flight.perf.impl.PerfOuterClass; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestErrorMetadata { @@ -63,21 +67,21 @@ public void testGrpcMetadata() throws Exception { }); PerfOuterClass.Perf newPerf = null; ErrorFlightMetadata metadata = flightStatus.metadata(); - Assertions.assertNotNull(metadata); - Assertions.assertEquals(2, metadata.keys().size()); - Assertions.assertTrue(metadata.containsKey("grpc-status-details-bin")); + assertNotNull(metadata); + assertEquals(2, metadata.keys().size()); + assertTrue(metadata.containsKey("grpc-status-details-bin")); Status status = marshaller.parseBytes(metadata.getByte("grpc-status-details-bin")); for (Any details : status.getDetailsList()) { if (details.is(PerfOuterClass.Perf.class)) { try { newPerf = details.unpack(PerfOuterClass.Perf.class); } catch (InvalidProtocolBufferException e) { - Assertions.fail(); + fail(); } } } - Assertions.assertNotNull(newPerf); - Assertions.assertEquals(perf, newPerf); + assertNotNull(newPerf); + assertEquals(perf, newPerf); } } @@ -98,9 +102,9 @@ public void testFlightMetadata() throws Exception { stream.next(); }); ErrorFlightMetadata metadata = flightStatus.metadata(); - Assertions.assertNotNull(metadata); - Assertions.assertEquals("foo", metadata.get("x-foo")); - Assertions.assertArrayEquals(new byte[] {1}, metadata.getByte("x-bar-bin")); + assertNotNull(metadata); + assertEquals("foo", metadata.get("x-foo")); + assertArrayEquals(new byte[] {1}, metadata.getByte("x-bar-bin")); flightStatus = FlightTestUtil.assertCode( @@ -109,9 +113,9 @@ public void testFlightMetadata() throws Exception { client.getInfo(FlightDescriptor.command(new byte[0])); }); metadata = flightStatus.metadata(); - Assertions.assertNotNull(metadata); - Assertions.assertEquals("foo", metadata.get("x-foo")); - Assertions.assertArrayEquals(new byte[] {1}, metadata.getByte("x-bar-bin")); + assertNotNull(metadata); + assertEquals("foo", metadata.get("x-foo")); + assertArrayEquals(new byte[] {1}, metadata.getByte("x-bar-bin")); } } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightClient.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightClient.java index 536f9f383b744..86e7f2f19097c 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightClient.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightClient.java @@ -18,6 +18,12 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.util.Collections; @@ -41,7 +47,6 @@ import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -64,9 +69,7 @@ public void independentShutdown() throws Exception { client1.startPut(FlightDescriptor.path("test"), root, new AsyncPutListener()); try (final FlightClient client2 = FlightClient.builder(allocator, server.getLocation()).build()) { - client2 - .listActions() - .forEach(actionType -> Assertions.assertNotNull(actionType.getType())); + client2.listActions().forEach(actionType -> assertNotNull(actionType.getType())); } listener.completed(); listener.getResult(); @@ -101,20 +104,20 @@ public void freeDictionaries() throws Exception { try (final FlightClient client = FlightClient.builder(allocator, server.getLocation()).build()) { try (final FlightStream stream = client.getStream(new Ticket(new byte[0]))) { - Assertions.assertTrue(stream.next()); - Assertions.assertNotNull(stream.getDictionaryProvider().lookup(1)); + assertTrue(stream.next()); + assertNotNull(stream.getDictionaryProvider().lookup(1)); final VectorSchemaRoot root = stream.getRoot(); - Assertions.assertEquals(expectedSchema, root.getSchema()); - Assertions.assertEquals(6, root.getVector("encoded").getValueCount()); + assertEquals(expectedSchema, root.getSchema()); + assertEquals(6, root.getVector("encoded").getValueCount()); try (final ValueVector decoded = DictionaryEncoder.decode( root.getVector("encoded"), stream.getDictionaryProvider().lookup(1))) { - Assertions.assertFalse(decoded.isNull(1)); - Assertions.assertTrue(decoded instanceof VarCharVector); - Assertions.assertArrayEquals( + assertFalse(decoded.isNull(1)); + assertTrue(decoded instanceof VarCharVector); + assertArrayEquals( "one".getBytes(StandardCharsets.UTF_8), ((VarCharVector) decoded).get(1)); } - Assertions.assertFalse(stream.next()); + assertFalse(stream.next()); } // Closing stream fails if it doesn't free dictionaries; closing dictionaries fails // (refcount goes negative) @@ -140,11 +143,11 @@ public void ownDictionaries() throws Exception { try (final FlightClient client = FlightClient.builder(allocator, server.getLocation()).build()) { try (final FlightStream stream = client.getStream(new Ticket(new byte[0]))) { - Assertions.assertTrue(stream.next()); - Assertions.assertFalse(stream.next()); + assertTrue(stream.next()); + assertFalse(stream.next()); final DictionaryProvider provider = stream.takeDictionaryOwnership(); - Assertions.assertThrows(IllegalStateException.class, stream::takeDictionaryOwnership); - Assertions.assertThrows(IllegalStateException.class, stream::getDictionaryProvider); + assertThrows(IllegalStateException.class, stream::takeDictionaryOwnership); + assertThrows(IllegalStateException.class, stream::getDictionaryProvider); DictionaryUtils.closeDictionaries(stream.getSchema(), provider); } } @@ -182,9 +185,9 @@ public void useDictionariesAfterClose() throws Exception { } try (final ValueVector decoded = DictionaryEncoder.decode(root.getVector("encoded"), provider.lookup(1))) { - Assertions.assertFalse(decoded.isNull(1)); - Assertions.assertTrue(decoded instanceof VarCharVector); - Assertions.assertArrayEquals( + assertFalse(decoded.isNull(1)); + assertTrue(decoded instanceof VarCharVector); + assertArrayEquals( "one".getBytes(StandardCharsets.UTF_8), ((VarCharVector) decoded).get(1)); } root.close(); diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightGrpcUtils.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightGrpcUtils.java index c7f5f2c7d80be..b82e9ee26b15d 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightGrpcUtils.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightGrpcUtils.java @@ -16,7 +16,11 @@ */ package org.apache.arrow.flight; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.protobuf.Empty; import io.grpc.BindableService; @@ -33,7 +37,6 @@ import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -94,8 +97,7 @@ public void testMultipleGrpcServices() throws IOException { // protobuf object final TestServiceGrpc.TestServiceBlockingStub blockingStub = TestServiceGrpc.newBlockingStub(managedChannel); - Assertions.assertEquals( - Empty.newBuilder().build(), blockingStub.test(Empty.newBuilder().build())); + assertEquals(Empty.newBuilder().build(), blockingStub.test(Empty.newBuilder().build())); } @Test @@ -112,9 +114,9 @@ public void testShutdown() throws IOException, InterruptedException { // Should be a no-op. flightClient.close(); - Assertions.assertFalse(managedChannel.isShutdown()); - Assertions.assertFalse(managedChannel.isTerminated()); - Assertions.assertEquals(ConnectivityState.IDLE, managedChannel.getState(false)); + assertFalse(managedChannel.isShutdown()); + assertFalse(managedChannel.isTerminated()); + assertEquals(ConnectivityState.IDLE, managedChannel.getState(false)); managedChannel.shutdownNow(); } @@ -126,22 +128,22 @@ public void testProxyChannel() throws IOException, InterruptedException { final FlightGrpcUtils.NonClosingProxyManagedChannel proxyChannel = new FlightGrpcUtils.NonClosingProxyManagedChannel(managedChannel); - Assertions.assertFalse(proxyChannel.isShutdown()); - Assertions.assertFalse(proxyChannel.isTerminated()); + assertFalse(proxyChannel.isShutdown()); + assertFalse(proxyChannel.isTerminated()); proxyChannel.shutdown(); - Assertions.assertTrue(proxyChannel.isShutdown()); - Assertions.assertTrue(proxyChannel.isTerminated()); - Assertions.assertEquals(ConnectivityState.SHUTDOWN, proxyChannel.getState(false)); + assertTrue(proxyChannel.isShutdown()); + assertTrue(proxyChannel.isTerminated()); + assertEquals(ConnectivityState.SHUTDOWN, proxyChannel.getState(false)); try { proxyChannel.newCall(null, null); - Assertions.fail(); + fail(); } catch (IllegalStateException e) { // This is expected, since the proxy channel is shut down. } - Assertions.assertFalse(managedChannel.isShutdown()); - Assertions.assertFalse(managedChannel.isTerminated()); - Assertions.assertEquals(ConnectivityState.IDLE, managedChannel.getState(false)); + assertFalse(managedChannel.isShutdown()); + assertFalse(managedChannel.isTerminated()); + assertEquals(ConnectivityState.IDLE, managedChannel.getState(false)); managedChannel.shutdownNow(); } @@ -154,22 +156,22 @@ public void testProxyChannelWithClosedChannel() throws IOException, InterruptedE final FlightGrpcUtils.NonClosingProxyManagedChannel proxyChannel = new FlightGrpcUtils.NonClosingProxyManagedChannel(managedChannel); - Assertions.assertFalse(proxyChannel.isShutdown()); - Assertions.assertFalse(proxyChannel.isTerminated()); + assertFalse(proxyChannel.isShutdown()); + assertFalse(proxyChannel.isTerminated()); managedChannel.shutdownNow(); - Assertions.assertTrue(proxyChannel.isShutdown()); - Assertions.assertTrue(proxyChannel.isTerminated()); - Assertions.assertEquals(ConnectivityState.SHUTDOWN, proxyChannel.getState(false)); + assertTrue(proxyChannel.isShutdown()); + assertTrue(proxyChannel.isTerminated()); + assertEquals(ConnectivityState.SHUTDOWN, proxyChannel.getState(false)); try { proxyChannel.newCall(null, null); - Assertions.fail(); + fail(); } catch (IllegalStateException e) { // This is expected, since the proxy channel is shut down. } - Assertions.assertTrue(managedChannel.isShutdown()); - Assertions.assertTrue(managedChannel.isTerminated()); - Assertions.assertEquals(ConnectivityState.SHUTDOWN, managedChannel.getState(false)); + assertTrue(managedChannel.isShutdown()); + assertTrue(managedChannel.isTerminated()); + assertEquals(ConnectivityState.SHUTDOWN, managedChannel.getState(false)); } /** Private class used for testing purposes that overrides service behavior. */ diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightService.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightService.java index 5d28c1f7374e6..5ebeb44c1d36e 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightService.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestFlightService.java @@ -18,6 +18,9 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import io.grpc.stub.ServerCallStreamObserver; @@ -31,7 +34,6 @@ import org.apache.arrow.vector.ipc.message.IpcOption; import org.apache.arrow.vector.types.pojo.Schema; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -140,15 +142,14 @@ public FlightInfo getFlightInfo(CallContext context, FlightDescriptor descriptor .start(); final FlightClient client = FlightClient.builder(allocator, s.getLocation()).build()) { FlightInfo flightInfo = client.getInfo(FlightDescriptor.path("test")); - Assertions.assertEquals(Optional.empty(), flightInfo.getSchemaOptional()); - Assertions.assertEquals(new Schema(Collections.emptyList()), flightInfo.getSchema()); - Assertions.assertArrayEquals( - flightInfo.getAppMetadata(), "foo".getBytes(StandardCharsets.UTF_8)); + assertEquals(Optional.empty(), flightInfo.getSchemaOptional()); + assertEquals(new Schema(Collections.emptyList()), flightInfo.getSchema()); + assertArrayEquals(flightInfo.getAppMetadata(), "foo".getBytes(StandardCharsets.UTF_8)); Exception e = - Assertions.assertThrows( + assertThrows( FlightRuntimeException.class, () -> client.getSchema(FlightDescriptor.path("test"))); - Assertions.assertEquals("No schema is present in FlightInfo", e.getMessage()); + assertEquals("No schema is present in FlightInfo", e.getMessage()); } } } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestLargeMessage.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestLargeMessage.java index f71691bd4f14e..9362e1f55258b 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestLargeMessage.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestLargeMessage.java @@ -19,6 +19,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; @@ -31,7 +32,6 @@ import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestLargeMessage { @@ -51,7 +51,7 @@ public void getLargeMessage() throws Exception { int value = 0; final IntVector iv = (IntVector) root.getVector(field.getName()); for (int i = 0; i < root.getRowCount(); i++) { - Assertions.assertEquals(value, iv.get(i)); + assertEquals(value, iv.get(i)); value++; } } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerMiddleware.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerMiddleware.java index d124088680f2b..c60843d2a279c 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerMiddleware.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerMiddleware.java @@ -18,6 +18,10 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Collections; @@ -29,7 +33,6 @@ import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.VectorSchemaRoot; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestServerMiddleware { @@ -51,9 +54,9 @@ public void doPutErrors() { }, (recorder) -> { final CallStatus status = recorder.statusFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertNotNull(status.cause()); - Assertions.assertEquals(FlightStatusCode.INTERNAL, status.code()); + assertNotNull(status); + assertNotNull(status.cause()); + assertEquals(FlightStatusCode.INTERNAL, status.code()); }); // Check the status after server shutdown (to make sure gRPC finishes pending calls on the // server side) @@ -77,10 +80,10 @@ public void doPutCustomCode() { }, (recorder) -> { final CallStatus status = recorder.statusFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertNull(status.cause()); - Assertions.assertEquals(FlightStatusCode.UNAVAILABLE, status.code()); - Assertions.assertEquals("description", status.description()); + assertNotNull(status); + assertNull(status.cause()); + assertEquals(FlightStatusCode.UNAVAILABLE, status.code()); + assertEquals("description", status.description()); }); } @@ -102,11 +105,11 @@ public void doPutUncaught() { (recorder) -> { final CallStatus status = recorder.statusFuture.get(); final Throwable err = recorder.errFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertEquals(FlightStatusCode.OK, status.code()); - Assertions.assertNull(status.cause()); - Assertions.assertNotNull(err); - Assertions.assertEquals("test", err.getMessage()); + assertNotNull(status); + assertEquals(FlightStatusCode.OK, status.code()); + assertNull(status.cause()); + assertNotNull(err); + assertEquals("test", err.getMessage()); }); } @@ -119,11 +122,11 @@ public void listFlightsUncaught() { (recorder) -> { final CallStatus status = recorder.statusFuture.get(); final Throwable err = recorder.errFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertEquals(FlightStatusCode.OK, status.code()); - Assertions.assertNull(status.cause()); - Assertions.assertNotNull(err); - Assertions.assertEquals("test", err.getMessage()); + assertNotNull(status); + assertEquals(FlightStatusCode.OK, status.code()); + assertNull(status.cause()); + assertNotNull(err); + assertEquals("test", err.getMessage()); }); } @@ -135,11 +138,11 @@ public void doActionUncaught() { (recorder) -> { final CallStatus status = recorder.statusFuture.get(); final Throwable err = recorder.errFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertEquals(FlightStatusCode.OK, status.code()); - Assertions.assertNull(status.cause()); - Assertions.assertNotNull(err); - Assertions.assertEquals("test", err.getMessage()); + assertNotNull(status); + assertEquals(FlightStatusCode.OK, status.code()); + assertNull(status.cause()); + assertNotNull(err); + assertEquals("test", err.getMessage()); }); } @@ -151,11 +154,11 @@ public void listActionsUncaught() { (recorder) -> { final CallStatus status = recorder.statusFuture.get(); final Throwable err = recorder.errFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertEquals(FlightStatusCode.OK, status.code()); - Assertions.assertNull(status.cause()); - Assertions.assertNotNull(err); - Assertions.assertEquals("test", err.getMessage()); + assertNotNull(status); + assertEquals(FlightStatusCode.OK, status.code()); + assertNull(status.cause()); + assertNotNull(err); + assertEquals("test", err.getMessage()); }); } @@ -169,11 +172,10 @@ public void getFlightInfoUncaught() { }, (recorder) -> { final CallStatus status = recorder.statusFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertEquals(FlightStatusCode.INTERNAL, status.code()); - Assertions.assertNotNull(status.cause()); - Assertions.assertEquals( - new RuntimeException("test").getMessage(), status.cause().getMessage()); + assertNotNull(status); + assertEquals(FlightStatusCode.INTERNAL, status.code()); + assertNotNull(status.cause()); + assertEquals(new RuntimeException("test").getMessage(), status.cause().getMessage()); }); } @@ -185,17 +187,17 @@ public void doGetUncaught() { try (final FlightStream stream = client.getStream(new Ticket(new byte[0]))) { while (stream.next()) {} } catch (Exception e) { - Assertions.fail(e.toString()); + fail(e.toString()); } }, (recorder) -> { final CallStatus status = recorder.statusFuture.get(); final Throwable err = recorder.errFuture.get(); - Assertions.assertNotNull(status); - Assertions.assertEquals(FlightStatusCode.OK, status.code()); - Assertions.assertNull(status.cause()); - Assertions.assertNotNull(err); - Assertions.assertEquals("test", err.getMessage()); + assertNotNull(status); + assertEquals(FlightStatusCode.OK, status.code()); + assertNull(status.cause()); + assertNotNull(err); + assertEquals("test", err.getMessage()); }); } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerOptions.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerOptions.java index 9dc85ffb5047d..c39ac922cfaad 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerOptions.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestServerOptions.java @@ -19,7 +19,10 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Channel; import io.grpc.MethodDescriptor; @@ -44,7 +47,6 @@ import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.VectorSchemaRoot; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; @@ -62,7 +64,7 @@ public void builderConsumer() throws Exception { .transportHint("grpc.builderConsumer", consumer) .build() .start()) { - Assertions.assertTrue(consumerCalled.get()); + assertTrue(consumerCalled.get()); } } @@ -81,7 +83,7 @@ public void defaultExecutorClosed() throws Exception { assertNotNull(server.grpcExecutor); executor = server.grpcExecutor; } - Assertions.assertTrue(executor.isShutdown()); + assertTrue(executor.isShutdown()); } /** Make sure that if the user provides an executor to gRPC, then Flight does not close it. */ @@ -95,9 +97,9 @@ public void suppliedExecutorNotClosed() throws Exception { .executor(executor) .build() .start()) { - Assertions.assertNull(server.grpcExecutor); + assertNull(server.grpcExecutor); } - Assertions.assertFalse(executor.isShutdown()); + assertFalse(executor.isShutdown()); } finally { executor.shutdown(); } @@ -108,7 +110,7 @@ public void domainSocket() throws Exception { Assumptions.assumeTrue( FlightTestUtil.isNativeTransportAvailable(), "We have a native transport available"); final File domainSocket = File.createTempFile("flight-unit-test-", ".sock"); - Assertions.assertTrue(domainSocket.delete()); + assertTrue(domainSocket.delete()); // Domain socket paths have a platform-dependent limit. Set a conservative limit and skip the // test if the temporary // file name is too long. (We do not assume a particular platform-dependent temporary directory @@ -126,7 +128,7 @@ public void domainSocket() throws Exception { int value = 0; while (stream.next()) { for (int i = 0; i < root.getRowCount(); i++) { - Assertions.assertEquals(value, iv.get(i)); + assertEquals(value, iv.get(i)); value++; } } @@ -168,10 +170,10 @@ public void checkReflectionMetadata() { for (final MethodDescriptor descriptor : FlightServiceGrpc.getServiceDescriptor().getMethods()) { final String methodName = descriptor.getFullMethodName(); - Assertions.assertTrue( + assertTrue( definedMethods.containsKey(methodName), "Method is missing from ServerServiceDefinition: " + methodName); - Assertions.assertTrue( + assertTrue( definedMethods.containsKey(methodName), "Method is missing from ServiceDescriptor: " + methodName); diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestTls.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestTls.java index 17869ad9a78a6..60dd131a182ed 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestTls.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/TestTls.java @@ -18,6 +18,8 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.io.FileInputStream; import java.io.IOException; @@ -27,7 +29,6 @@ import java.util.function.Consumer; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** Tests for TLS in Flight. */ @@ -43,8 +44,8 @@ public void connectTls() { final FlightClient client = builder.trustedCertificates(roots).build()) { final Iterator responses = client.doAction(new Action("hello-world")); final byte[] response = responses.next().getBody(); - Assertions.assertEquals("Hello, world!", new String(response, StandardCharsets.UTF_8)); - Assertions.assertFalse(responses.hasNext()); + assertEquals("Hello, world!", new String(response, StandardCharsets.UTF_8)); + assertFalse(responses.hasNext()); } catch (InterruptedException | IOException e) { throw new RuntimeException(e); } @@ -92,8 +93,8 @@ public void connectTlsDisableServerVerification() { try (final FlightClient client = builder.verifyServer(false).build()) { final Iterator responses = client.doAction(new Action("hello-world")); final byte[] response = responses.next().getBody(); - Assertions.assertEquals("Hello, world!", new String(response, StandardCharsets.UTF_8)); - Assertions.assertFalse(responses.hasNext()); + assertEquals("Hello, world!", new String(response, StandardCharsets.UTF_8)); + assertFalse(responses.hasNext()); } catch (InterruptedException e) { throw new RuntimeException(e); } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java index b268d3755deb6..0c63785c88fd1 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth/TestBasicAuth.java @@ -18,6 +18,8 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableList; import java.io.IOException; @@ -42,7 +44,6 @@ import org.apache.arrow.vector.types.pojo.Schema; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -60,7 +61,7 @@ public class TestBasicAuth { @Test public void validAuth() { client.authenticateBasic(USERNAME, PASSWORD); - Assertions.assertTrue(ImmutableList.copyOf(client.listFlights(Criteria.ALL)).size() == 0); + assertEquals(0, ImmutableList.copyOf(client.listFlights(Criteria.ALL)).size()); } @Test @@ -69,7 +70,7 @@ public void asyncCall() throws Exception { client.listFlights(Criteria.ALL); try (final FlightStream s = client.getStream(new Ticket(new byte[1]))) { while (s.next()) { - Assertions.assertEquals(4095, s.getRoot().getRowCount()); + assertEquals(4095, s.getRoot().getRowCount()); } } } @@ -85,7 +86,7 @@ public void invalidAuth() { FlightTestUtil.assertCode( FlightStatusCode.UNAUTHENTICATED, () -> { - client.listFlights(Criteria.ALL).forEach(action -> Assertions.fail()); + client.listFlights(Criteria.ALL).forEach(action -> fail()); }); } @@ -94,7 +95,7 @@ public void didntAuth() { FlightTestUtil.assertCode( FlightStatusCode.UNAUTHENTICATED, () -> { - client.listFlights(Criteria.ALL).forEach(action -> Assertions.fail()); + client.listFlights(Criteria.ALL).forEach(action -> fail()); }); } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth2/TestBasicAuth2.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth2/TestBasicAuth2.java index 3b968bb530861..2d1eb9331ee63 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth2/TestBasicAuth2.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/auth2/TestBasicAuth2.java @@ -18,6 +18,9 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; @@ -42,7 +45,6 @@ import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -170,7 +172,7 @@ public void asyncCall() throws Exception { client.listFlights(Criteria.ALL, bearerToken); try (final FlightStream s = client.getStream(new Ticket(new byte[1]), bearerToken)) { while (s.next()) { - Assertions.assertEquals(4095, s.getRoot().getRowCount()); + assertEquals(4095, s.getRoot().getRowCount()); } } } @@ -188,8 +190,7 @@ public void didntAuthWithBearerAuthServer() throws IOException { private void testValidAuth(FlightClient client) { final CredentialCallOption bearerToken = client.authenticateBasicToken(USERNAME_1, PASSWORD_1).get(); - Assertions.assertTrue( - ImmutableList.copyOf(client.listFlights(Criteria.ALL, bearerToken)).isEmpty()); + assertTrue(ImmutableList.copyOf(client.listFlights(Criteria.ALL, bearerToken)).isEmpty()); } private void testValidAuthWithMultipleClientsWithSameCredentials( @@ -198,10 +199,8 @@ private void testValidAuthWithMultipleClientsWithSameCredentials( client1.authenticateBasicToken(USERNAME_1, PASSWORD_1).get(); final CredentialCallOption bearerToken2 = client2.authenticateBasicToken(USERNAME_1, PASSWORD_1).get(); - Assertions.assertTrue( - ImmutableList.copyOf(client1.listFlights(Criteria.ALL, bearerToken1)).isEmpty()); - Assertions.assertTrue( - ImmutableList.copyOf(client2.listFlights(Criteria.ALL, bearerToken2)).isEmpty()); + assertTrue(ImmutableList.copyOf(client1.listFlights(Criteria.ALL, bearerToken1)).isEmpty()); + assertTrue(ImmutableList.copyOf(client2.listFlights(Criteria.ALL, bearerToken2)).isEmpty()); } private void testValidAuthWithMultipleClientsWithDifferentCredentials( @@ -210,10 +209,8 @@ private void testValidAuthWithMultipleClientsWithDifferentCredentials( client1.authenticateBasicToken(USERNAME_1, PASSWORD_1).get(); final CredentialCallOption bearerToken2 = client2.authenticateBasicToken(USERNAME_2, PASSWORD_2).get(); - Assertions.assertTrue( - ImmutableList.copyOf(client1.listFlights(Criteria.ALL, bearerToken1)).isEmpty()); - Assertions.assertTrue( - ImmutableList.copyOf(client2.listFlights(Criteria.ALL, bearerToken2)).isEmpty()); + assertTrue(ImmutableList.copyOf(client1.listFlights(Criteria.ALL, bearerToken1)).isEmpty()); + assertTrue(ImmutableList.copyOf(client2.listFlights(Criteria.ALL, bearerToken2)).isEmpty()); } private void testInvalidAuth(FlightClient client) { @@ -226,12 +223,12 @@ private void testInvalidAuth(FlightClient client) { FlightTestUtil.assertCode( FlightStatusCode.UNAUTHENTICATED, - () -> client.listFlights(Criteria.ALL).forEach(action -> Assertions.fail())); + () -> client.listFlights(Criteria.ALL).forEach(action -> fail())); } private void didntAuth(FlightClient client) { FlightTestUtil.assertCode( FlightStatusCode.UNAUTHENTICATED, - () -> client.listFlights(Criteria.ALL).forEach(action -> Assertions.fail())); + () -> client.listFlights(Criteria.ALL).forEach(action -> fail())); } } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/CustomHeaderTest.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/CustomHeaderTest.java index 0c73cb535efad..059107b0106cc 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/CustomHeaderTest.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/CustomHeaderTest.java @@ -16,6 +16,8 @@ */ package org.apache.arrow.flight.client; +import static org.junit.jupiter.api.Assertions.assertEquals; + import com.google.common.collect.ImmutableMap; import java.util.HashMap; import java.util.Map; @@ -42,10 +44,9 @@ import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** Tests to ensure custom headers are passed along to the server for each command. */ public class CustomHeaderTest { @@ -60,7 +61,7 @@ public class CustomHeaderTest { "bar", "foo", "answer", "42"); - @Before + @BeforeEach public void setUp() throws Exception { allocator = new RootAllocator(Integer.MAX_VALUE); headersMiddleware = new TestCustomHeaderMiddleware.Factory(); @@ -80,7 +81,7 @@ public void setUp() throws Exception { client = FlightClient.builder(allocator, server.getLocation()).build(); } - @After + @AfterEach public void tearDown() throws Exception { allocator.getChildAllocators().forEach(BufferAllocator::close); AutoCloseables.close(allocator, server, client); @@ -181,8 +182,7 @@ public void testDoExchange() { private void assertHeadersMatch(FlightMethod method) { for (Map.Entry entry : testHeaders.entrySet()) { - Assert.assertEquals( - entry.getValue(), headersMiddleware.getCustomHeader(method, entry.getKey())); + assertEquals(entry.getValue(), headersMiddleware.getCustomHeader(method, entry.getKey())); } } diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/TestCookieHandling.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/TestCookieHandling.java index 2e83fb49adc50..d89fd64ebadf7 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/TestCookieHandling.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/client/TestCookieHandling.java @@ -18,6 +18,8 @@ import static org.apache.arrow.flight.FlightTestUtil.LOCALHOST; import static org.apache.arrow.flight.Location.forGrpcInsecure; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import org.apache.arrow.flight.CallHeaders; @@ -37,7 +39,6 @@ import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -77,7 +78,7 @@ public void basicCookie() { headersToSend.insert(SET_COOKIE_HEADER, "k=v"); cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); } @Test @@ -86,17 +87,17 @@ public void cookieStaysAfterMultipleRequests() { headersToSend.insert(SET_COOKIE_HEADER, "k=v"); cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); headersToSend = new ErrorFlightMetadata(); cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); headersToSend = new ErrorFlightMetadata(); cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); } @Disabled @@ -107,12 +108,12 @@ public void cookieAutoExpires() { cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); // Note: using max-age changes cookie version from 0->1, which quotes values. - Assertions.assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); headersToSend = new ErrorFlightMetadata(); cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); try { Thread.sleep(5000); @@ -120,7 +121,7 @@ public void cookieAutoExpires() { } // Verify that the k cookie was discarded because it expired. - Assertions.assertTrue(cookieMiddleware.getValidCookiesAsString().isEmpty()); + assertTrue(cookieMiddleware.getValidCookiesAsString().isEmpty()); } @Test @@ -130,7 +131,7 @@ public void cookieExplicitlyExpires() { cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); // Note: using max-age changes cookie version from 0->1, which quotes values. - Assertions.assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); // Note: The JDK treats Max-Age < 0 as not expired and treats 0 as expired. // This violates the RFC, which states that less than zero and zero should both be expired. @@ -140,7 +141,7 @@ public void cookieExplicitlyExpires() { cookieMiddleware.onHeadersReceived(headersToSend); // Verify that the k cookie was discarded because the server told the client it is expired. - Assertions.assertTrue(cookieMiddleware.getValidCookiesAsString().isEmpty()); + assertTrue(cookieMiddleware.getValidCookiesAsString().isEmpty()); } @Disabled @@ -151,7 +152,7 @@ public void cookieExplicitlyExpiresWithMaxAgeMinusOne() { cookieMiddleware = testFactory.onCallStarted(new CallInfo(FlightMethod.DO_ACTION)); cookieMiddleware.onHeadersReceived(headersToSend); // Note: using max-age changes cookie version from 0->1, which quotes values. - Assertions.assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=\"v\"", cookieMiddleware.getValidCookiesAsString()); headersToSend = new ErrorFlightMetadata(); @@ -162,7 +163,7 @@ public void cookieExplicitlyExpiresWithMaxAgeMinusOne() { cookieMiddleware.onHeadersReceived(headersToSend); // Verify that the k cookie was discarded because the server told the client it is expired. - Assertions.assertTrue(cookieMiddleware.getValidCookiesAsString().isEmpty()); + assertTrue(cookieMiddleware.getValidCookiesAsString().isEmpty()); } @Test @@ -170,12 +171,12 @@ public void changeCookieValue() { CallHeaders headersToSend = new ErrorFlightMetadata(); headersToSend.insert(SET_COOKIE_HEADER, "k=v"); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", cookieMiddleware.getValidCookiesAsString()); headersToSend = new ErrorFlightMetadata(); headersToSend.insert(SET_COOKIE_HEADER, "k=v2"); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals("k=v2", cookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v2", cookieMiddleware.getValidCookiesAsString()); } @Test @@ -184,18 +185,18 @@ public void multipleCookiesWithSetCookie() { headersToSend.insert(SET_COOKIE_HEADER, "firstKey=firstVal"); headersToSend.insert(SET_COOKIE_HEADER, "secondKey=secondVal"); cookieMiddleware.onHeadersReceived(headersToSend); - Assertions.assertEquals( + assertEquals( "firstKey=firstVal; secondKey=secondVal", cookieMiddleware.getValidCookiesAsString()); } @Test public void cookieStaysAfterMultipleRequestsEndToEnd() { client.handshake(); - Assertions.assertEquals("k=v", testFactory.clientCookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", testFactory.clientCookieMiddleware.getValidCookiesAsString()); client.handshake(); - Assertions.assertEquals("k=v", testFactory.clientCookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", testFactory.clientCookieMiddleware.getValidCookiesAsString()); client.listFlights(Criteria.ALL); - Assertions.assertEquals("k=v", testFactory.clientCookieMiddleware.getValidCookiesAsString()); + assertEquals("k=v", testFactory.clientCookieMiddleware.getValidCookiesAsString()); } /** A server middleware component that injects SET_COOKIE_HEADER into the outgoing headers. */ diff --git a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/grpc/TestStatusUtils.java b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/grpc/TestStatusUtils.java index 44a73e494e925..f5ab712a75ff0 100644 --- a/java/flight/flight-core/src/test/java/org/apache/arrow/flight/grpc/TestStatusUtils.java +++ b/java/flight/flight-core/src/test/java/org/apache/arrow/flight/grpc/TestStatusUtils.java @@ -16,11 +16,13 @@ */ package org.apache.arrow.flight.grpc; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import io.grpc.Metadata; import io.grpc.Status; import org.apache.arrow.flight.CallStatus; import org.apache.arrow.flight.FlightStatusCode; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class TestStatusUtils { @@ -38,13 +40,13 @@ public void testParseTrailers() { CallStatus callStatus = StatusUtils.fromGrpcStatusAndTrailers(status, trailers); - Assertions.assertEquals(FlightStatusCode.CANCELLED, callStatus.code()); - Assertions.assertTrue(callStatus.metadata().containsKey(":status")); - Assertions.assertEquals("502", callStatus.metadata().get(":status")); - Assertions.assertTrue(callStatus.metadata().containsKey("date")); - Assertions.assertEquals("Fri, 13 Sep 2015 11:23:58 GMT", callStatus.metadata().get("date")); - Assertions.assertTrue(callStatus.metadata().containsKey("content-type")); - Assertions.assertEquals("text/html", callStatus.metadata().get("content-type")); + assertEquals(FlightStatusCode.CANCELLED, callStatus.code()); + assertTrue(callStatus.metadata().containsKey(":status")); + assertEquals("502", callStatus.metadata().get(":status")); + assertTrue(callStatus.metadata().containsKey("date")); + assertEquals("Fri, 13 Sep 2015 11:23:58 GMT", callStatus.metadata().get("date")); + assertTrue(callStatus.metadata().containsKey("content-type")); + assertEquals("text/html", callStatus.metadata().get("content-type")); } @Test @@ -52,10 +54,10 @@ public void testGrpcResourceExhaustedTranslatedToFlightStatus() { Status status = Status.RESOURCE_EXHAUSTED; CallStatus callStatus = StatusUtils.fromGrpcStatus(status); - Assertions.assertEquals(FlightStatusCode.RESOURCE_EXHAUSTED, callStatus.code()); + assertEquals(FlightStatusCode.RESOURCE_EXHAUSTED, callStatus.code()); FlightStatusCode flightStatusCode = StatusUtils.fromGrpcStatusCode(status.getCode()); - Assertions.assertEquals(FlightStatusCode.RESOURCE_EXHAUSTED, flightStatusCode); + assertEquals(FlightStatusCode.RESOURCE_EXHAUSTED, flightStatusCode); } @Test @@ -63,9 +65,9 @@ public void testFlightResourceExhaustedTranslatedToGrpcStatua() { CallStatus callStatus = CallStatus.RESOURCE_EXHAUSTED; Status.Code grpcStatusCode = StatusUtils.toGrpcStatusCode(callStatus.code()); - Assertions.assertEquals(Status.RESOURCE_EXHAUSTED.getCode(), grpcStatusCode); + assertEquals(Status.RESOURCE_EXHAUSTED.getCode(), grpcStatusCode); Status grpcStatus = StatusUtils.toGrpcStatus(callStatus); - Assertions.assertEquals(Status.RESOURCE_EXHAUSTED.getCode(), grpcStatus.getCode()); + assertEquals(Status.RESOURCE_EXHAUSTED.getCode(), grpcStatus.getCode()); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowDatabaseMetadataTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowDatabaseMetadataTest.java index 4bf534de61d40..88a172e4f2b3f 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowDatabaseMetadataTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowDatabaseMetadataTest.java @@ -31,6 +31,10 @@ import static org.apache.arrow.flight.sql.impl.FlightSql.SqlSupportsConvert.SQL_CONVERT_BIT_VALUE; import static org.apache.arrow.flight.sql.impl.FlightSql.SqlSupportsConvert.SQL_CONVERT_INTEGER_VALUE; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -77,13 +81,10 @@ import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; import org.apache.arrow.vector.util.Text; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Class containing the tests from the {@link ArrowDatabaseMetadata}. */ @SuppressWarnings("DoubleBraceInitialization") @@ -93,13 +94,13 @@ public class ArrowDatabaseMetadataTest { private static final MockFlightSqlProducer FLIGHT_SQL_PRODUCER_EMPTY_SQLINFO = new MockFlightSqlProducer(); - @ClassRule - public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(FLIGHT_SQL_PRODUCER); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension(FLIGHT_SQL_PRODUCER); - @ClassRule - public static final FlightServerTestRule FLIGHT_SERVER_EMPTY_SQLINFO_TEST_RULE = - FlightServerTestRule.createStandardTestRule(FLIGHT_SQL_PRODUCER_EMPTY_SQLINFO); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_EMPTY_SQLINFO_TEST_RULE = + FlightServerTestExtension.createStandardTestExtension(FLIGHT_SQL_PRODUCER_EMPTY_SQLINFO); private static final int ROW_COUNT = 10; private static final List> EXPECTED_GET_CATALOGS_RESULTS = @@ -338,12 +339,11 @@ public class ArrowDatabaseMetadataTest { .collect(toList()); } - @Rule public final ErrorCollector collector = new ErrorCollector(); - public final ResultSetTestUtils resultSetTestUtils = new ResultSetTestUtils(collector); + public final ResultSetTestUtils resultSetTestUtils = new ResultSetTestUtils(); - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws SQLException { - connection = FLIGHT_SERVER_TEST_RULE.getConnection(false); + connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false); final Message commandGetCatalogs = CommandGetCatalogs.getDefaultInstance(); final Consumer commandGetCatalogsResultProducer = @@ -655,7 +655,7 @@ public static void setUpBeforeClass() throws SQLException { EXPECTED_STORED_FUNCTIONS_USING_CALL_SYNTAX_SUPPORTED); } - @AfterClass + @AfterAll public static void tearDown() throws Exception { AutoCloseables.close(connection, FLIGHT_SQL_PRODUCER, FLIGHT_SQL_PRODUCER_EMPTY_SQLINFO); } @@ -835,148 +835,132 @@ public void testGetColumnsCanByIndicesFilteringColumnNames() throws SQLException @Test public void testGetSqlInfo() throws SQLException { final DatabaseMetaData metaData = connection.getMetaData(); - collector.checkThat(metaData.getDatabaseProductName(), is(EXPECTED_DATABASE_PRODUCT_NAME)); - collector.checkThat( - metaData.getDatabaseProductVersion(), is(EXPECTED_DATABASE_PRODUCT_VERSION)); - collector.checkThat(metaData.getIdentifierQuoteString(), is(EXPECTED_IDENTIFIER_QUOTE_STRING)); - collector.checkThat(metaData.isReadOnly(), is(EXPECTED_IS_READ_ONLY)); - collector.checkThat(metaData.getSQLKeywords(), is(EXPECTED_SQL_KEYWORDS)); - collector.checkThat(metaData.getNumericFunctions(), is(EXPECTED_NUMERIC_FUNCTIONS)); - collector.checkThat(metaData.getStringFunctions(), is(EXPECTED_STRING_FUNCTIONS)); - collector.checkThat(metaData.getSystemFunctions(), is(EXPECTED_SYSTEM_FUNCTIONS)); - collector.checkThat(metaData.getTimeDateFunctions(), is(EXPECTED_TIME_DATE_FUNCTIONS)); - collector.checkThat(metaData.getSearchStringEscape(), is(EXPECTED_SEARCH_STRING_ESCAPE)); - collector.checkThat(metaData.getExtraNameCharacters(), is(EXPECTED_EXTRA_NAME_CHARACTERS)); - collector.checkThat(metaData.supportsConvert(), is(EXPECTED_SQL_SUPPORTS_CONVERT)); - collector.checkThat(metaData.supportsConvert(BIT, INTEGER), is(EXPECTED_SQL_SUPPORTS_CONVERT)); - collector.checkThat(metaData.supportsConvert(BIT, BIGINT), is(EXPECTED_SQL_SUPPORTS_CONVERT)); - collector.checkThat( + assertThat(metaData.getDatabaseProductName(), is(EXPECTED_DATABASE_PRODUCT_NAME)); + assertThat(metaData.getDatabaseProductVersion(), is(EXPECTED_DATABASE_PRODUCT_VERSION)); + assertThat(metaData.getIdentifierQuoteString(), is(EXPECTED_IDENTIFIER_QUOTE_STRING)); + assertThat(metaData.isReadOnly(), is(EXPECTED_IS_READ_ONLY)); + assertThat(metaData.getSQLKeywords(), is(EXPECTED_SQL_KEYWORDS)); + assertThat(metaData.getNumericFunctions(), is(EXPECTED_NUMERIC_FUNCTIONS)); + assertThat(metaData.getStringFunctions(), is(EXPECTED_STRING_FUNCTIONS)); + assertThat(metaData.getSystemFunctions(), is(EXPECTED_SYSTEM_FUNCTIONS)); + assertThat(metaData.getTimeDateFunctions(), is(EXPECTED_TIME_DATE_FUNCTIONS)); + assertThat(metaData.getSearchStringEscape(), is(EXPECTED_SEARCH_STRING_ESCAPE)); + assertThat(metaData.getExtraNameCharacters(), is(EXPECTED_EXTRA_NAME_CHARACTERS)); + assertThat(metaData.supportsConvert(), is(EXPECTED_SQL_SUPPORTS_CONVERT)); + assertThat(metaData.supportsConvert(BIT, INTEGER), is(EXPECTED_SQL_SUPPORTS_CONVERT)); + assertThat(metaData.supportsConvert(BIT, BIGINT), is(EXPECTED_SQL_SUPPORTS_CONVERT)); + assertThat( metaData.supportsConvert(BIGINT, INTEGER), is(EXPECTED_INVALID_SQL_SUPPORTS_CONVERT)); - collector.checkThat( + assertThat( metaData.supportsConvert(JAVA_OBJECT, INTEGER), is(EXPECTED_INVALID_SQL_SUPPORTS_CONVERT)); - collector.checkThat( + assertThat( metaData.supportsTableCorrelationNames(), is(EXPECTED_SUPPORTS_TABLE_CORRELATION_NAMES)); - collector.checkThat( - metaData.supportsExpressionsInOrderBy(), is(EXPECTED_EXPRESSIONS_IN_ORDER_BY)); - collector.checkThat( - metaData.supportsOrderByUnrelated(), is(EXPECTED_SUPPORTS_ORDER_BY_UNRELATED)); - collector.checkThat(metaData.supportsGroupBy(), is(EXPECTED_SUPPORTS_GROUP_BY)); - collector.checkThat( - metaData.supportsGroupByUnrelated(), is(EXPECTED_SUPPORTS_GROUP_BY_UNRELATED)); - collector.checkThat( - metaData.supportsLikeEscapeClause(), is(EXPECTED_SUPPORTS_LIKE_ESCAPE_CLAUSE)); - collector.checkThat(metaData.supportsNonNullableColumns(), is(EXPECTED_NON_NULLABLE_COLUMNS)); - collector.checkThat(metaData.supportsMinimumSQLGrammar(), is(EXPECTED_MINIMUM_SQL_GRAMMAR)); - collector.checkThat(metaData.supportsCoreSQLGrammar(), is(EXPECTED_CORE_SQL_GRAMMAR)); - collector.checkThat(metaData.supportsExtendedSQLGrammar(), is(EXPECTED_EXTEND_SQL_GRAMMAR)); - collector.checkThat( - metaData.supportsANSI92EntryLevelSQL(), is(EXPECTED_ANSI92_ENTRY_LEVEL_SQL)); - collector.checkThat( - metaData.supportsANSI92IntermediateSQL(), is(EXPECTED_ANSI92_INTERMEDIATE_SQL)); - collector.checkThat(metaData.supportsANSI92FullSQL(), is(EXPECTED_ANSI92_FULL_SQL)); - collector.checkThat(metaData.supportsOuterJoins(), is(EXPECTED_SUPPORTS_OUTER_JOINS)); - collector.checkThat(metaData.supportsFullOuterJoins(), is(EXPECTED_SUPPORTS_FULL_OUTER_JOINS)); - collector.checkThat(metaData.supportsLimitedOuterJoins(), is(EXPECTED_SUPPORTS_LIMITED_JOINS)); - collector.checkThat(metaData.getSchemaTerm(), is(EXPECTED_SCHEMA_TERM)); - collector.checkThat(metaData.getProcedureTerm(), is(EXPECTED_PROCEDURE_TERM)); - collector.checkThat(metaData.getCatalogTerm(), is(EXPECTED_CATALOG_TERM)); - collector.checkThat(metaData.isCatalogAtStart(), is(EXPECTED_CATALOG_AT_START)); - collector.checkThat( - metaData.supportsSchemasInProcedureCalls(), is(EXPECTED_SCHEMAS_IN_PROCEDURE_CALLS)); - collector.checkThat( + assertThat(metaData.supportsExpressionsInOrderBy(), is(EXPECTED_EXPRESSIONS_IN_ORDER_BY)); + assertThat(metaData.supportsOrderByUnrelated(), is(EXPECTED_SUPPORTS_ORDER_BY_UNRELATED)); + assertThat(metaData.supportsGroupBy(), is(EXPECTED_SUPPORTS_GROUP_BY)); + assertThat(metaData.supportsGroupByUnrelated(), is(EXPECTED_SUPPORTS_GROUP_BY_UNRELATED)); + assertThat(metaData.supportsLikeEscapeClause(), is(EXPECTED_SUPPORTS_LIKE_ESCAPE_CLAUSE)); + assertThat(metaData.supportsNonNullableColumns(), is(EXPECTED_NON_NULLABLE_COLUMNS)); + assertThat(metaData.supportsMinimumSQLGrammar(), is(EXPECTED_MINIMUM_SQL_GRAMMAR)); + assertThat(metaData.supportsCoreSQLGrammar(), is(EXPECTED_CORE_SQL_GRAMMAR)); + assertThat(metaData.supportsExtendedSQLGrammar(), is(EXPECTED_EXTEND_SQL_GRAMMAR)); + assertThat(metaData.supportsANSI92EntryLevelSQL(), is(EXPECTED_ANSI92_ENTRY_LEVEL_SQL)); + assertThat(metaData.supportsANSI92IntermediateSQL(), is(EXPECTED_ANSI92_INTERMEDIATE_SQL)); + assertThat(metaData.supportsANSI92FullSQL(), is(EXPECTED_ANSI92_FULL_SQL)); + assertThat(metaData.supportsOuterJoins(), is(EXPECTED_SUPPORTS_OUTER_JOINS)); + assertThat(metaData.supportsFullOuterJoins(), is(EXPECTED_SUPPORTS_FULL_OUTER_JOINS)); + assertThat(metaData.supportsLimitedOuterJoins(), is(EXPECTED_SUPPORTS_LIMITED_JOINS)); + assertThat(metaData.getSchemaTerm(), is(EXPECTED_SCHEMA_TERM)); + assertThat(metaData.getProcedureTerm(), is(EXPECTED_PROCEDURE_TERM)); + assertThat(metaData.getCatalogTerm(), is(EXPECTED_CATALOG_TERM)); + assertThat(metaData.isCatalogAtStart(), is(EXPECTED_CATALOG_AT_START)); + assertThat(metaData.supportsSchemasInProcedureCalls(), is(EXPECTED_SCHEMAS_IN_PROCEDURE_CALLS)); + assertThat( metaData.supportsSchemasInIndexDefinitions(), is(EXPECTED_SCHEMAS_IN_INDEX_DEFINITIONS)); - collector.checkThat( + assertThat( metaData.supportsCatalogsInIndexDefinitions(), is(EXPECTED_CATALOGS_IN_INDEX_DEFINITIONS)); - collector.checkThat(metaData.supportsPositionedDelete(), is(EXPECTED_POSITIONED_DELETE)); - collector.checkThat(metaData.supportsPositionedUpdate(), is(EXPECTED_POSITIONED_UPDATE)); - collector.checkThat( + assertThat(metaData.supportsPositionedDelete(), is(EXPECTED_POSITIONED_DELETE)); + assertThat(metaData.supportsPositionedUpdate(), is(EXPECTED_POSITIONED_UPDATE)); + assertThat( metaData.supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY), is(EXPECTED_TYPE_FORWARD_ONLY)); - collector.checkThat( - metaData.supportsSelectForUpdate(), is(EXPECTED_SELECT_FOR_UPDATE_SUPPORTED)); - collector.checkThat( - metaData.supportsStoredProcedures(), is(EXPECTED_STORED_PROCEDURES_SUPPORTED)); - collector.checkThat( - metaData.supportsSubqueriesInComparisons(), is(EXPECTED_SUBQUERIES_IN_COMPARISON)); - collector.checkThat(metaData.supportsSubqueriesInExists(), is(EXPECTED_SUBQUERIES_IN_EXISTS)); - collector.checkThat(metaData.supportsSubqueriesInIns(), is(EXPECTED_SUBQUERIES_IN_INS)); - collector.checkThat( - metaData.supportsSubqueriesInQuantifieds(), is(EXPECTED_SUBQUERIES_IN_QUANTIFIEDS)); - collector.checkThat( + assertThat(metaData.supportsSelectForUpdate(), is(EXPECTED_SELECT_FOR_UPDATE_SUPPORTED)); + assertThat(metaData.supportsStoredProcedures(), is(EXPECTED_STORED_PROCEDURES_SUPPORTED)); + assertThat(metaData.supportsSubqueriesInComparisons(), is(EXPECTED_SUBQUERIES_IN_COMPARISON)); + assertThat(metaData.supportsSubqueriesInExists(), is(EXPECTED_SUBQUERIES_IN_EXISTS)); + assertThat(metaData.supportsSubqueriesInIns(), is(EXPECTED_SUBQUERIES_IN_INS)); + assertThat(metaData.supportsSubqueriesInQuantifieds(), is(EXPECTED_SUBQUERIES_IN_QUANTIFIEDS)); + assertThat( metaData.supportsCorrelatedSubqueries(), is(EXPECTED_CORRELATED_SUBQUERIES_SUPPORTED)); - collector.checkThat(metaData.supportsUnion(), is(EXPECTED_SUPPORTS_UNION)); - collector.checkThat(metaData.supportsUnionAll(), is(EXPECTED_SUPPORTS_UNION_ALL)); - collector.checkThat( - metaData.getMaxBinaryLiteralLength(), is(EXPECTED_MAX_BINARY_LITERAL_LENGTH)); - collector.checkThat(metaData.getMaxCharLiteralLength(), is(EXPECTED_MAX_CHAR_LITERAL_LENGTH)); - collector.checkThat(metaData.getMaxColumnsInGroupBy(), is(EXPECTED_MAX_COLUMNS_IN_GROUP_BY)); - collector.checkThat(metaData.getMaxColumnsInIndex(), is(EXPECTED_MAX_COLUMNS_IN_INDEX)); - collector.checkThat(metaData.getMaxColumnsInOrderBy(), is(EXPECTED_MAX_COLUMNS_IN_ORDER_BY)); - collector.checkThat(metaData.getMaxColumnsInSelect(), is(EXPECTED_MAX_COLUMNS_IN_SELECT)); - collector.checkThat(metaData.getMaxConnections(), is(EXPECTED_MAX_CONNECTIONS)); - collector.checkThat(metaData.getMaxCursorNameLength(), is(EXPECTED_MAX_CURSOR_NAME_LENGTH)); - collector.checkThat(metaData.getMaxIndexLength(), is(EXPECTED_MAX_INDEX_LENGTH)); - collector.checkThat(metaData.getMaxSchemaNameLength(), is(EXPECTED_SCHEMA_NAME_LENGTH)); - collector.checkThat( - metaData.getMaxProcedureNameLength(), is(EXPECTED_MAX_PROCEDURE_NAME_LENGTH)); - collector.checkThat(metaData.getMaxCatalogNameLength(), is(EXPECTED_MAX_CATALOG_NAME_LENGTH)); - collector.checkThat(metaData.getMaxRowSize(), is(EXPECTED_MAX_ROW_SIZE)); - collector.checkThat( - metaData.doesMaxRowSizeIncludeBlobs(), is(EXPECTED_MAX_ROW_SIZE_INCLUDES_BLOBS)); - collector.checkThat(metaData.getMaxStatementLength(), is(EXPECTED_MAX_STATEMENT_LENGTH)); - collector.checkThat(metaData.getMaxStatements(), is(EXPECTED_MAX_STATEMENTS)); - collector.checkThat(metaData.getMaxTableNameLength(), is(EXPECTED_MAX_TABLE_NAME_LENGTH)); - collector.checkThat(metaData.getMaxTablesInSelect(), is(EXPECTED_MAX_TABLES_IN_SELECT)); - collector.checkThat(metaData.getMaxUserNameLength(), is(EXPECTED_MAX_USERNAME_LENGTH)); - collector.checkThat( + assertThat(metaData.supportsUnion(), is(EXPECTED_SUPPORTS_UNION)); + assertThat(metaData.supportsUnionAll(), is(EXPECTED_SUPPORTS_UNION_ALL)); + assertThat(metaData.getMaxBinaryLiteralLength(), is(EXPECTED_MAX_BINARY_LITERAL_LENGTH)); + assertThat(metaData.getMaxCharLiteralLength(), is(EXPECTED_MAX_CHAR_LITERAL_LENGTH)); + assertThat(metaData.getMaxColumnsInGroupBy(), is(EXPECTED_MAX_COLUMNS_IN_GROUP_BY)); + assertThat(metaData.getMaxColumnsInIndex(), is(EXPECTED_MAX_COLUMNS_IN_INDEX)); + assertThat(metaData.getMaxColumnsInOrderBy(), is(EXPECTED_MAX_COLUMNS_IN_ORDER_BY)); + assertThat(metaData.getMaxColumnsInSelect(), is(EXPECTED_MAX_COLUMNS_IN_SELECT)); + assertThat(metaData.getMaxConnections(), is(EXPECTED_MAX_CONNECTIONS)); + assertThat(metaData.getMaxCursorNameLength(), is(EXPECTED_MAX_CURSOR_NAME_LENGTH)); + assertThat(metaData.getMaxIndexLength(), is(EXPECTED_MAX_INDEX_LENGTH)); + assertThat(metaData.getMaxSchemaNameLength(), is(EXPECTED_SCHEMA_NAME_LENGTH)); + assertThat(metaData.getMaxProcedureNameLength(), is(EXPECTED_MAX_PROCEDURE_NAME_LENGTH)); + assertThat(metaData.getMaxCatalogNameLength(), is(EXPECTED_MAX_CATALOG_NAME_LENGTH)); + assertThat(metaData.getMaxRowSize(), is(EXPECTED_MAX_ROW_SIZE)); + assertThat(metaData.doesMaxRowSizeIncludeBlobs(), is(EXPECTED_MAX_ROW_SIZE_INCLUDES_BLOBS)); + assertThat(metaData.getMaxStatementLength(), is(EXPECTED_MAX_STATEMENT_LENGTH)); + assertThat(metaData.getMaxStatements(), is(EXPECTED_MAX_STATEMENTS)); + assertThat(metaData.getMaxTableNameLength(), is(EXPECTED_MAX_TABLE_NAME_LENGTH)); + assertThat(metaData.getMaxTablesInSelect(), is(EXPECTED_MAX_TABLES_IN_SELECT)); + assertThat(metaData.getMaxUserNameLength(), is(EXPECTED_MAX_USERNAME_LENGTH)); + assertThat( metaData.getDefaultTransactionIsolation(), is(EXPECTED_DEFAULT_TRANSACTION_ISOLATION)); - collector.checkThat(metaData.supportsTransactions(), is(EXPECTED_TRANSACTIONS_SUPPORTED)); - collector.checkThat(metaData.supportsBatchUpdates(), is(EXPECTED_BATCH_UPDATES_SUPPORTED)); - collector.checkThat(metaData.supportsSavepoints(), is(EXPECTED_SAVEPOINTS_SUPPORTED)); - collector.checkThat( - metaData.supportsNamedParameters(), is(EXPECTED_NAMED_PARAMETERS_SUPPORTED)); - collector.checkThat(metaData.locatorsUpdateCopy(), is(EXPECTED_LOCATORS_UPDATE_COPY)); - - collector.checkThat( + assertThat(metaData.supportsTransactions(), is(EXPECTED_TRANSACTIONS_SUPPORTED)); + assertThat(metaData.supportsBatchUpdates(), is(EXPECTED_BATCH_UPDATES_SUPPORTED)); + assertThat(metaData.supportsSavepoints(), is(EXPECTED_SAVEPOINTS_SUPPORTED)); + assertThat(metaData.supportsNamedParameters(), is(EXPECTED_NAMED_PARAMETERS_SUPPORTED)); + assertThat(metaData.locatorsUpdateCopy(), is(EXPECTED_LOCATORS_UPDATE_COPY)); + + assertThat( metaData.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE), is(EXPECTED_TYPE_SCROLL_INSENSITIVE)); - collector.checkThat( + assertThat( metaData.supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE), is(EXPECTED_TYPE_SCROLL_SENSITIVE)); - collector.checkThat( + assertThat( metaData.supportsSchemasInPrivilegeDefinitions(), is(EXPECTED_SCHEMAS_IN_PRIVILEGE_DEFINITIONS)); - collector.checkThat( + assertThat( metaData.supportsCatalogsInPrivilegeDefinitions(), is(EXPECTED_CATALOGS_IN_PRIVILEGE_DEFINITIONS)); - collector.checkThat( + assertThat( metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE), is(EXPECTED_TRANSACTION_NONE)); - collector.checkThat( + assertThat( metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED), is(EXPECTED_TRANSACTION_READ_COMMITTED)); - collector.checkThat( + assertThat( metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED), is(EXPECTED_TRANSACTION_READ_UNCOMMITTED)); - collector.checkThat( + assertThat( metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ), is(EXPECTED_TRANSACTION_REPEATABLE_READ)); - collector.checkThat( + assertThat( metaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE), is(EXPECTED_TRANSACTION_SERIALIZABLE)); - collector.checkThat( + assertThat( metaData.dataDefinitionCausesTransactionCommit(), is(EXPECTED_DATA_DEFINITION_CAUSES_TRANSACTION_COMMIT)); - collector.checkThat( + assertThat( metaData.dataDefinitionIgnoredInTransactions(), is(EXPECTED_DATA_DEFINITIONS_IN_TRANSACTIONS_IGNORED)); - collector.checkThat( + assertThat( metaData.supportsStoredFunctionsUsingCallSyntax(), is(EXPECTED_STORED_FUNCTIONS_USING_CALL_SYNTAX_SUPPORTED)); - collector.checkThat( + assertThat( metaData.supportsIntegrityEnhancementFacility(), is(EXPECTED_SUPPORTS_INTEGRITY_ENHANCEMENT_FACILITY)); - collector.checkThat( + assertThat( metaData.supportsDifferentTableCorrelationNames(), is(EXPECTED_SUPPORTS_DIFFERENT_TABLE_CORRELATION_NAMES)); @@ -1406,122 +1390,122 @@ public void testGetPseudoColumns() throws SQLException { private void testEmptyResultSet( final ResultSet resultSet, final Map expectedResultSetSchema) throws SQLException { - Assert.assertFalse(resultSet.next()); + assertFalse(resultSet.next()); final ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); for (final Map.Entry entry : expectedResultSetSchema.entrySet()) { - Assert.assertEquals(entry.getValue(), resultSetMetaData.getColumnLabel(entry.getKey())); + assertEquals(entry.getValue(), resultSetMetaData.getColumnLabel(entry.getKey())); } } @Test public void testGetColumnSize() { - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_BYTE), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Int(Byte.SIZE, true))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_SHORT), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Int(Short.SIZE, true))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_INT), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Int(Integer.SIZE, true))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_LONG), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Int(Long.SIZE, true))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_VARCHAR_AND_BINARY), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Utf8())); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_VARCHAR_AND_BINARY), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Binary())); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIMESTAMP_SECONDS), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Timestamp(TimeUnit.SECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIMESTAMP_MILLISECONDS), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Timestamp(TimeUnit.MILLISECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIMESTAMP_MICROSECONDS), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Timestamp(TimeUnit.MICROSECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIMESTAMP_NANOSECONDS), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Timestamp(TimeUnit.NANOSECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIME), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Time(TimeUnit.SECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIME_MILLISECONDS), ArrowDatabaseMetadata.getColumnSize( new ArrowType.Time(TimeUnit.MILLISECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIME_MICROSECONDS), ArrowDatabaseMetadata.getColumnSize( new ArrowType.Time(TimeUnit.MICROSECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_TIME_NANOSECONDS), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Time(TimeUnit.NANOSECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.COLUMN_SIZE_DATE), ArrowDatabaseMetadata.getColumnSize(new ArrowType.Date(DateUnit.DAY))); - Assert.assertNull( + assertNull( ArrowDatabaseMetadata.getColumnSize( new ArrowType.FloatingPoint(FloatingPointPrecision.DOUBLE))); } @Test public void testGetDecimalDigits() { - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.NO_DECIMAL_DIGITS), ArrowDatabaseMetadata.getDecimalDigits(new ArrowType.Int(Byte.SIZE, true))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.NO_DECIMAL_DIGITS), ArrowDatabaseMetadata.getDecimalDigits(new ArrowType.Timestamp(TimeUnit.SECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.DECIMAL_DIGITS_TIME_MILLISECONDS), ArrowDatabaseMetadata.getDecimalDigits( new ArrowType.Timestamp(TimeUnit.MILLISECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.DECIMAL_DIGITS_TIME_MICROSECONDS), ArrowDatabaseMetadata.getDecimalDigits( new ArrowType.Timestamp(TimeUnit.MICROSECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.DECIMAL_DIGITS_TIME_NANOSECONDS), ArrowDatabaseMetadata.getDecimalDigits(new ArrowType.Timestamp(TimeUnit.NANOSECOND, null))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.NO_DECIMAL_DIGITS), ArrowDatabaseMetadata.getDecimalDigits(new ArrowType.Time(TimeUnit.SECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.DECIMAL_DIGITS_TIME_MILLISECONDS), ArrowDatabaseMetadata.getDecimalDigits( new ArrowType.Time(TimeUnit.MILLISECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.DECIMAL_DIGITS_TIME_MICROSECONDS), ArrowDatabaseMetadata.getDecimalDigits( new ArrowType.Time(TimeUnit.MICROSECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.DECIMAL_DIGITS_TIME_NANOSECONDS), ArrowDatabaseMetadata.getDecimalDigits( new ArrowType.Time(TimeUnit.NANOSECOND, Integer.SIZE))); - Assert.assertEquals( + assertEquals( Integer.valueOf(ArrowDatabaseMetadata.NO_DECIMAL_DIGITS), ArrowDatabaseMetadata.getDecimalDigits(new ArrowType.Date(DateUnit.DAY))); - Assert.assertNull(ArrowDatabaseMetadata.getDecimalDigits(new ArrowType.Utf8())); + assertNull(ArrowDatabaseMetadata.getDecimalDigits(new ArrowType.Utf8())); } @Test public void testSqlToRegexLike() { - Assert.assertEquals(".*", ArrowDatabaseMetadata.sqlToRegexLike("%")); - Assert.assertEquals(".", ArrowDatabaseMetadata.sqlToRegexLike("_")); - Assert.assertEquals("\\*", ArrowDatabaseMetadata.sqlToRegexLike("*")); - Assert.assertEquals("T\\*E.S.*T", ArrowDatabaseMetadata.sqlToRegexLike("T*E_S%T")); + assertEquals(".*", ArrowDatabaseMetadata.sqlToRegexLike("%")); + assertEquals(".", ArrowDatabaseMetadata.sqlToRegexLike("_")); + assertEquals("\\*", ArrowDatabaseMetadata.sqlToRegexLike("*")); + assertEquals("T\\*E.S.*T", ArrowDatabaseMetadata.sqlToRegexLike("T*E_S%T")); } @Test @@ -1529,11 +1513,11 @@ public void testEmptySqlInfo() throws Exception { try (final Connection testConnection = FLIGHT_SERVER_EMPTY_SQLINFO_TEST_RULE.getConnection(false)) { final DatabaseMetaData metaData = testConnection.getMetaData(); - collector.checkThat(metaData.getSQLKeywords(), is("")); - collector.checkThat(metaData.getNumericFunctions(), is("")); - collector.checkThat(metaData.getStringFunctions(), is("")); - collector.checkThat(metaData.getSystemFunctions(), is("")); - collector.checkThat(metaData.getTimeDateFunctions(), is("")); + assertThat(metaData.getSQLKeywords(), is("")); + assertThat(metaData.getNumericFunctions(), is("")); + assertThat(metaData.getStringFunctions(), is("")); + assertThat(metaData.getSystemFunctions(), is("")); + assertThat(metaData.getTimeDateFunctions(), is("")); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcArrayTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcArrayTest.java index 0ec2b86fad33e..06d101724cd0d 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcArrayTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcArrayTest.java @@ -16,36 +16,41 @@ */ package org.apache.arrow.driver.jdbc; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Types; import java.util.Arrays; import java.util.HashMap; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.util.JsonStringArrayList; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) public class ArrowFlightJdbcArrayTest { - @Rule public RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); IntVector dataVector; - @Before + @BeforeEach public void setup() { - dataVector = rootAllocatorTestRule.createIntVector(); + dataVector = rootAllocatorTestExtension.createIntVector(); } - @After + @AfterEach public void tearDown() { this.dataVector.close(); } @@ -54,14 +59,14 @@ public void tearDown() { public void testShouldGetBaseTypeNameReturnCorrectTypeName() { ArrowFlightJdbcArray arrowFlightJdbcArray = new ArrowFlightJdbcArray(dataVector, 0, dataVector.getValueCount()); - Assert.assertEquals("INTEGER", arrowFlightJdbcArray.getBaseTypeName()); + assertEquals("INTEGER", arrowFlightJdbcArray.getBaseTypeName()); } @Test public void testShouldGetBaseTypeReturnCorrectType() { ArrowFlightJdbcArray arrowFlightJdbcArray = new ArrowFlightJdbcArray(dataVector, 0, dataVector.getValueCount()); - Assert.assertEquals(Types.INTEGER, arrowFlightJdbcArray.getBaseType()); + assertEquals(Types.INTEGER, arrowFlightJdbcArray.getBaseType()); } @Test @@ -74,7 +79,7 @@ public void testShouldGetArrayReturnValidArray() throws SQLException { for (int i = 0; i < expected.length; i++) { expected[i] = dataVector.getObject(i); } - Assert.assertArrayEquals(array, expected); + assertArrayEquals(array, expected); } @Test @@ -87,31 +92,34 @@ public void testShouldGetArrayReturnValidArrayWithOffsets() throws SQLException for (int i = 0; i < expected.length; i++) { expected[i] = dataVector.getObject(i + 1); } - Assert.assertArrayEquals(array, expected); + assertArrayEquals(array, expected); } - @Test(expected = ArrayIndexOutOfBoundsException.class) + @Test public void testShouldGetArrayWithOffsetsThrowArrayIndexOutOfBoundsException() throws SQLException { ArrowFlightJdbcArray arrowFlightJdbcArray = new ArrowFlightJdbcArray(dataVector, 0, dataVector.getValueCount()); - arrowFlightJdbcArray.getArray(0, dataVector.getValueCount() + 1); + assertThrows( + ArrayIndexOutOfBoundsException.class, + () -> arrowFlightJdbcArray.getArray(0, dataVector.getValueCount() + 1)); } - @Test(expected = SQLFeatureNotSupportedException.class) + @Test public void testShouldGetArrayWithMapNotBeSupported() throws SQLException { ArrowFlightJdbcArray arrowFlightJdbcArray = new ArrowFlightJdbcArray(dataVector, 0, dataVector.getValueCount()); HashMap> map = new HashMap<>(); - arrowFlightJdbcArray.getArray(map); + assertThrows(SQLFeatureNotSupportedException.class, () -> arrowFlightJdbcArray.getArray(map)); } - @Test(expected = SQLFeatureNotSupportedException.class) + @Test public void testShouldGetArrayWithOffsetsAndMapNotBeSupported() throws SQLException { ArrowFlightJdbcArray arrowFlightJdbcArray = new ArrowFlightJdbcArray(dataVector, 0, dataVector.getValueCount()); HashMap> map = new HashMap<>(); - arrowFlightJdbcArray.getArray(0, 5, map); + assertThrows( + SQLFeatureNotSupportedException.class, () -> arrowFlightJdbcArray.getArray(0, 5, map)); } @Test @@ -121,7 +129,7 @@ public void testShouldGetResultSetReturnValidResultSet() throws SQLException { try (ResultSet resultSet = arrowFlightJdbcArray.getResultSet()) { int count = 0; while (resultSet.next()) { - Assert.assertEquals((Object) resultSet.getInt(1), dataVector.getObject(count)); + assertEquals((Object) resultSet.getInt(1), dataVector.getObject(count)); count++; } } @@ -134,10 +142,10 @@ public void testShouldGetResultSetReturnValidResultSetWithOffsets() throws SQLEx try (ResultSet resultSet = arrowFlightJdbcArray.getResultSet(3, 5)) { int count = 0; while (resultSet.next()) { - Assert.assertEquals((Object) resultSet.getInt(1), dataVector.getObject(count + 3)); + assertEquals((Object) resultSet.getInt(1), dataVector.getObject(count + 3)); count++; } - Assert.assertEquals(5, count); + assertEquals(5, count); } } @@ -149,22 +157,24 @@ public void testToString() throws SQLException { JsonStringArrayList array = new JsonStringArrayList<>(); array.addAll(Arrays.asList((Object[]) arrowFlightJdbcArray.getArray())); - Assert.assertEquals(array.toString(), arrowFlightJdbcArray.toString()); + assertEquals(array.toString(), arrowFlightJdbcArray.toString()); } - @Test(expected = SQLFeatureNotSupportedException.class) + @Test public void testShouldGetResultSetWithMapNotBeSupported() throws SQLException { ArrowFlightJdbcArray arrowFlightJdbcArray = new ArrowFlightJdbcArray(dataVector, 0, dataVector.getValueCount()); HashMap> map = new HashMap<>(); - arrowFlightJdbcArray.getResultSet(map); + assertThrows( + SQLFeatureNotSupportedException.class, () -> arrowFlightJdbcArray.getResultSet(map)); } - @Test(expected = SQLFeatureNotSupportedException.class) + @Test public void testShouldGetResultSetWithOffsetsAndMapNotBeSupported() throws SQLException { ArrowFlightJdbcArray arrowFlightJdbcArray = new ArrowFlightJdbcArray(dataVector, 0, dataVector.getValueCount()); HashMap> map = new HashMap<>(); - arrowFlightJdbcArray.getResultSet(0, 5, map); + assertThrows( + SQLFeatureNotSupportedException.class, () -> arrowFlightJdbcArray.getResultSet(0, 5, map)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionCookieTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionCookieTest.java index aaaf676835a1f..1977b61392eb4 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionCookieTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionCookieTest.java @@ -16,35 +16,34 @@ */ package org.apache.arrow.driver.jdbc; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import org.apache.arrow.driver.jdbc.utils.CoreMockedSqlProducers; -import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcConnectionCookieTest { - @Rule public final ErrorCollector collector = new ErrorCollector(); - - @ClassRule - public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(CoreMockedSqlProducers.getLegacyProducer()); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension( + CoreMockedSqlProducers.getLegacyProducer()); @Test public void testCookies() throws SQLException { - try (Connection connection = FLIGHT_SERVER_TEST_RULE.getConnection(false); + try (Connection connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false); Statement statement = connection.createStatement()) { // Expect client didn't receive cookies before any operation - Assert.assertNull(FLIGHT_SERVER_TEST_RULE.getMiddlewareCookieFactory().getCookie()); + assertNull(FLIGHT_SERVER_TEST_EXTENSION.getMiddlewareCookieFactory().getCookie()); // Run another action for check if the cookies was sent by the server. statement.execute(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD); - Assert.assertEquals("k=v", FLIGHT_SERVER_TEST_RULE.getMiddlewareCookieFactory().getCookie()); + assertEquals("k=v", FLIGHT_SERVER_TEST_EXTENSION.getMiddlewareCookieFactory().getCookie()); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java index 3718f9752a74c..18ff45bbde6f6 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcConnectionPoolDataSourceTest.java @@ -16,19 +16,24 @@ */ package org.apache.arrow.driver.jdbc; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.sql.Connection; import javax.sql.PooledConnection; import org.apache.arrow.driver.jdbc.authentication.UserPasswordAuthentication; import org.apache.arrow.driver.jdbc.utils.ConnectionWrapper; import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcConnectionPoolDataSourceTest { - @ClassRule public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + + @RegisterExtension public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); @@ -39,8 +44,8 @@ public class ArrowFlightJdbcConnectionPoolDataSourceTest { .user("user2", "pass2") .build(); - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(authentication) .producer(PRODUCER) .build(); @@ -48,12 +53,12 @@ public class ArrowFlightJdbcConnectionPoolDataSourceTest { private ArrowFlightJdbcConnectionPoolDataSource dataSource; - @Before + @BeforeEach public void setUp() { - dataSource = FLIGHT_SERVER_TEST_RULE.createConnectionPoolDataSource(false); + dataSource = FLIGHT_SERVER_TEST_EXTENSION.createConnectionPoolDataSource(false); } - @After + @AfterEach public void tearDown() throws Exception { dataSource.close(); } @@ -62,18 +67,18 @@ public void tearDown() throws Exception { public void testShouldInnerConnectionIsClosedReturnCorrectly() throws Exception { PooledConnection pooledConnection = dataSource.getPooledConnection(); Connection connection = pooledConnection.getConnection(); - Assert.assertFalse(connection.isClosed()); + assertFalse(connection.isClosed()); connection.close(); - Assert.assertTrue(connection.isClosed()); + assertTrue(connection.isClosed()); } @Test public void testShouldInnerConnectionShouldIgnoreDoubleClose() throws Exception { PooledConnection pooledConnection = dataSource.getPooledConnection(); Connection connection = pooledConnection.getConnection(); - Assert.assertFalse(connection.isClosed()); + assertFalse(connection.isClosed()); connection.close(); - Assert.assertTrue(connection.isClosed()); + assertTrue(connection.isClosed()); } @Test @@ -81,30 +86,30 @@ public void testShouldInnerConnectionIsClosedReturnTrueIfPooledConnectionCloses( throws Exception { PooledConnection pooledConnection = dataSource.getPooledConnection(); Connection connection = pooledConnection.getConnection(); - Assert.assertFalse(connection.isClosed()); + assertFalse(connection.isClosed()); pooledConnection.close(); - Assert.assertTrue(connection.isClosed()); + assertTrue(connection.isClosed()); } @Test public void testShouldReuseConnectionsOnPool() throws Exception { PooledConnection pooledConnection = dataSource.getPooledConnection("user1", "pass1"); ConnectionWrapper connection = ((ConnectionWrapper) pooledConnection.getConnection()); - Assert.assertFalse(connection.isClosed()); + assertFalse(connection.isClosed()); connection.close(); - Assert.assertTrue(connection.isClosed()); - Assert.assertFalse(connection.unwrap(ArrowFlightConnection.class).isClosed()); + assertTrue(connection.isClosed()); + assertFalse(connection.unwrap(ArrowFlightConnection.class).isClosed()); PooledConnection pooledConnection2 = dataSource.getPooledConnection("user1", "pass1"); ConnectionWrapper connection2 = ((ConnectionWrapper) pooledConnection2.getConnection()); - Assert.assertFalse(connection2.isClosed()); + assertFalse(connection2.isClosed()); connection2.close(); - Assert.assertTrue(connection2.isClosed()); - Assert.assertFalse(connection2.unwrap(ArrowFlightConnection.class).isClosed()); + assertTrue(connection2.isClosed()); + assertFalse(connection2.unwrap(ArrowFlightConnection.class).isClosed()); - Assert.assertSame(pooledConnection, pooledConnection2); - Assert.assertNotSame(connection, connection2); - Assert.assertSame( + assertSame(pooledConnection, pooledConnection2); + assertNotSame(connection, connection2); + assertSame( connection.unwrap(ArrowFlightConnection.class), connection2.unwrap(ArrowFlightConnection.class)); } @@ -113,21 +118,21 @@ public void testShouldReuseConnectionsOnPool() throws Exception { public void testShouldNotMixConnectionsForDifferentUsers() throws Exception { PooledConnection pooledConnection = dataSource.getPooledConnection("user1", "pass1"); ConnectionWrapper connection = ((ConnectionWrapper) pooledConnection.getConnection()); - Assert.assertFalse(connection.isClosed()); + assertFalse(connection.isClosed()); connection.close(); - Assert.assertTrue(connection.isClosed()); - Assert.assertFalse(connection.unwrap(ArrowFlightConnection.class).isClosed()); + assertTrue(connection.isClosed()); + assertFalse(connection.unwrap(ArrowFlightConnection.class).isClosed()); PooledConnection pooledConnection2 = dataSource.getPooledConnection("user2", "pass2"); ConnectionWrapper connection2 = ((ConnectionWrapper) pooledConnection2.getConnection()); - Assert.assertFalse(connection2.isClosed()); + assertFalse(connection2.isClosed()); connection2.close(); - Assert.assertTrue(connection2.isClosed()); - Assert.assertFalse(connection2.unwrap(ArrowFlightConnection.class).isClosed()); + assertTrue(connection2.isClosed()); + assertFalse(connection2.unwrap(ArrowFlightConnection.class).isClosed()); - Assert.assertNotSame(pooledConnection, pooledConnection2); - Assert.assertNotSame(connection, connection2); - Assert.assertNotSame( + assertNotSame(pooledConnection, pooledConnection2); + assertNotSame(connection, connection2); + assertNotSame( connection.unwrap(ArrowFlightConnection.class), connection2.unwrap(ArrowFlightConnection.class)); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcCursorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcCursorTest.java index fc090dbdf431b..5cfe8ae74e567 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcCursorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcCursorTest.java @@ -16,7 +16,7 @@ */ package org.apache.arrow.driver.jdbc; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableList; import java.sql.SQLException; @@ -51,8 +51,8 @@ import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.types.pojo.Schema; import org.apache.calcite.avatica.util.Cursor; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; /** Tests for {@link ArrowFlightJdbcCursor}. */ public class ArrowFlightJdbcCursorTest { @@ -60,7 +60,7 @@ public class ArrowFlightJdbcCursorTest { ArrowFlightJdbcCursor cursor; BufferAllocator allocator; - @After + @AfterEach public void cleanUp() { allocator.close(); cursor.close(); diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java index 0fae4db7c876f..ae355829d7ecc 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcDriverTest.java @@ -35,15 +35,15 @@ import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests for {@link ArrowFlightJdbcDriver}. */ public class ArrowFlightJdbcDriverTest { - @ClassRule public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + @RegisterExtension public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); static { @@ -53,8 +53,8 @@ public class ArrowFlightJdbcDriverTest { .user("user2", "pass2") .build(); - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(authentication) .producer(PRODUCER) .build(); @@ -63,13 +63,13 @@ public class ArrowFlightJdbcDriverTest { private BufferAllocator allocator; private ArrowFlightJdbcConnectionPoolDataSource dataSource; - @Before + @BeforeEach public void setUp() throws Exception { allocator = new RootAllocator(Long.MAX_VALUE); - dataSource = FLIGHT_SERVER_TEST_RULE.createConnectionPoolDataSource(); + dataSource = FLIGHT_SERVER_TEST_EXTENSION.createConnectionPoolDataSource(); } - @After + @AfterEach public void tearDown() throws Exception { Collection childAllocators = allocator.getChildAllocators(); AutoCloseables.close(childAllocators.toArray(new AutoCloseable[0])); @@ -206,12 +206,14 @@ public void testConnectWithInsensitiveCasePropertyKeys2() throws Exception { * * @throws SQLException If an error occurs. */ - @Test(expected = SQLException.class) + @Test public void testShouldThrowExceptionWhenAttemptingToConnectToMalformedUrl() throws SQLException { final Driver driver = new ArrowFlightJdbcDriver(); final String malformedUri = "yes:??/chainsaw.i=T333"; - driver.connect(malformedUri, dataSource.getProperties("flight", "flight123")); + assertThrows( + SQLException.class, + () -> driver.connect(malformedUri, dataSource.getProperties("flight", "flight123"))); } /** @@ -219,15 +221,18 @@ public void testShouldThrowExceptionWhenAttemptingToConnectToMalformedUrl() thro * * @throws SQLException If an error occurs. */ - @Test(expected = SQLException.class) + @Test public void testShouldThrowExceptionWhenAttemptingToConnectToUrlNoPrefix() throws SQLException { final Driver driver = new ArrowFlightJdbcDriver(); final String malformedUri = "localhost:32010"; - driver.connect( - malformedUri, - dataSource.getProperties( - dataSource.getConfig().getUser(), dataSource.getConfig().getPassword())); + assertThrows( + SQLException.class, + () -> + driver.connect( + malformedUri, + dataSource.getProperties( + dataSource.getConfig().getUser(), dataSource.getConfig().getPassword()))); } /** Tests whether an exception is thrown upon attempting to connect to a malformed URI. */ diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactoryTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactoryTest.java index 9f61b935e8df6..d3b0c3700846a 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactoryTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcFactoryTest.java @@ -27,15 +27,15 @@ import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; import org.apache.calcite.avatica.UnregisteredDriver; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests for {@link ArrowFlightJdbcDriver}. */ public class ArrowFlightJdbcFactoryTest { - @ClassRule public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + @RegisterExtension public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); static { @@ -45,8 +45,8 @@ public class ArrowFlightJdbcFactoryTest { .user("user2", "pass2") .build(); - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(authentication) .producer(PRODUCER) .build(); @@ -55,13 +55,13 @@ public class ArrowFlightJdbcFactoryTest { private BufferAllocator allocator; private ArrowFlightJdbcConnectionPoolDataSource dataSource; - @Before + @BeforeEach public void setUp() throws Exception { allocator = new RootAllocator(Long.MAX_VALUE); - dataSource = FLIGHT_SERVER_TEST_RULE.createConnectionPoolDataSource(); + dataSource = FLIGHT_SERVER_TEST_EXTENSION.createConnectionPoolDataSource(); } - @After + @AfterEach public void tearDown() throws Exception { AutoCloseables.close(dataSource, allocator); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java index 961b2dd40bca3..aa499d805bcf2 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java @@ -18,16 +18,14 @@ import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.time.LocalTime; import java.util.concurrent.TimeUnit; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.Test; public class ArrowFlightJdbcTimeTest { - @ClassRule public static final ErrorCollector collector = new ErrorCollector(); final int hour = 5; final int minute = 6; final int second = 7; @@ -38,10 +36,10 @@ public void testPrintingMillisNoLeadingZeroes() { LocalTime dateTime = LocalTime.of(hour, minute, second, (int) TimeUnit.MILLISECONDS.toNanos(999)); ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(dateTime); - collector.checkThat(time.toString(), endsWith(".999")); - collector.checkThat(time.getHours(), is(hour)); - collector.checkThat(time.getMinutes(), is(minute)); - collector.checkThat(time.getSeconds(), is(second)); + assertThat(time.toString(), endsWith(".999")); + assertThat(time.getHours(), is(hour)); + assertThat(time.getMinutes(), is(minute)); + assertThat(time.getSeconds(), is(second)); } @Test @@ -50,10 +48,10 @@ public void testPrintingMillisOneLeadingZeroes() { LocalTime dateTime = LocalTime.of(hour, minute, second, (int) TimeUnit.MILLISECONDS.toNanos(99)); ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(dateTime); - collector.checkThat(time.toString(), endsWith(".099")); - collector.checkThat(time.getHours(), is(hour)); - collector.checkThat(time.getMinutes(), is(minute)); - collector.checkThat(time.getSeconds(), is(second)); + assertThat(time.toString(), endsWith(".099")); + assertThat(time.getHours(), is(hour)); + assertThat(time.getMinutes(), is(minute)); + assertThat(time.getSeconds(), is(second)); } @Test @@ -61,10 +59,10 @@ public void testPrintingMillisTwoLeadingZeroes() { // test case where two leading zeroes needs to be added LocalTime dateTime = LocalTime.of(hour, minute, second, (int) TimeUnit.MILLISECONDS.toNanos(1)); ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(dateTime); - collector.checkThat(time.toString(), endsWith(".001")); - collector.checkThat(time.getHours(), is(hour)); - collector.checkThat(time.getMinutes(), is(minute)); - collector.checkThat(time.getSeconds(), is(second)); + assertThat(time.toString(), endsWith(".001")); + assertThat(time.getHours(), is(hour)); + assertThat(time.getMinutes(), is(minute)); + assertThat(time.getSeconds(), is(second)); } @Test @@ -73,7 +71,7 @@ public void testEquality() { LocalTime dateTime = LocalTime.of(hour, minute, second, (int) TimeUnit.MILLISECONDS.toNanos(1)); ArrowFlightJdbcTime time1 = new ArrowFlightJdbcTime(dateTime); ArrowFlightJdbcTime time2 = new ArrowFlightJdbcTime(dateTime); - collector.checkThat(time1, is(time2)); - collector.checkThat(time1.hashCode(), is(time2.hashCode())); + assertThat(time1, is(time2)); + assertThat(time1.hashCode(), is(time2.hashCode())); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java index 6da731e1bd2c2..774ad0081e846 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightPreparedStatementTest.java @@ -17,6 +17,8 @@ package org.apache.arrow.driver.jdbc; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; @@ -40,38 +42,34 @@ import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.types.pojo.Schema; import org.apache.arrow.vector.util.Text; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightPreparedStatementTest { public static final MockFlightSqlProducer PRODUCER = CoreMockedSqlProducers.getLegacyProducer(); - @ClassRule - public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(PRODUCER); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension(PRODUCER); private static Connection connection; - @Rule public final ErrorCollector collector = new ErrorCollector(); - - @BeforeClass + @BeforeAll public static void setup() throws SQLException { - connection = FLIGHT_SERVER_TEST_RULE.getConnection(false); + connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false); } - @AfterClass + @AfterAll public static void tearDown() throws SQLException { connection.close(); } - @Before + @BeforeEach public void before() { PRODUCER.clearActionTypeCounter(); } @@ -81,7 +79,7 @@ public void testSimpleQueryNoParameterBinding() throws SQLException { final String query = CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD; try (final PreparedStatement preparedStatement = connection.prepareStatement(query); final ResultSet resultSet = preparedStatement.executeQuery()) { - CoreMockedSqlProducers.assertLegacyRegularSqlResultSet(resultSet, collector); + CoreMockedSqlProducers.assertLegacyRegularSqlResultSet(resultSet); } } @@ -134,7 +132,7 @@ public void testQueryWithParameterBinding() throws SQLException { } @Test - @Ignore("https://github.com/apache/arrow/issues/34741: flaky test") + @Disabled("https://github.com/apache/arrow/issues/34741: flaky test") public void testPreparedStatementExecutionOnce() throws SQLException { final PreparedStatement statement = connection.prepareStatement(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD); @@ -154,13 +152,15 @@ public void testPreparedStatementExecutionOnce() throws SQLException { public void testReturnColumnCount() throws SQLException { final String query = CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD; try (final PreparedStatement psmt = connection.prepareStatement(query)) { - collector.checkThat("ID", equalTo(psmt.getMetaData().getColumnName(1))); - collector.checkThat("Name", equalTo(psmt.getMetaData().getColumnName(2))); - collector.checkThat("Age", equalTo(psmt.getMetaData().getColumnName(3))); - collector.checkThat("Salary", equalTo(psmt.getMetaData().getColumnName(4))); - collector.checkThat("Hire Date", equalTo(psmt.getMetaData().getColumnName(5))); - collector.checkThat("Last Sale", equalTo(psmt.getMetaData().getColumnName(6))); - collector.checkThat(6, equalTo(psmt.getMetaData().getColumnCount())); + assertAll( + "Column count is as expected", + () -> assertThat("ID", equalTo(psmt.getMetaData().getColumnName(1))), + () -> assertThat("Name", equalTo(psmt.getMetaData().getColumnName(2))), + () -> assertThat("Age", equalTo(psmt.getMetaData().getColumnName(3))), + () -> assertThat("Salary", equalTo(psmt.getMetaData().getColumnName(4))), + () -> assertThat("Hire Date", equalTo(psmt.getMetaData().getColumnName(5))), + () -> assertThat("Last Sale", equalTo(psmt.getMetaData().getColumnName(6))), + () -> assertThat(6, equalTo(psmt.getMetaData().getColumnCount()))); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java index 42ce7f80bd455..632cb0ba5619b 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteTest.java @@ -21,6 +21,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Connection; import java.sql.ResultSet; @@ -41,14 +42,12 @@ import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; import org.apache.calcite.avatica.AvaticaUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests for {@link ArrowFlightStatement#execute}. */ public class ArrowFlightStatementExecuteTest { @@ -65,15 +64,14 @@ public class ArrowFlightStatementExecuteTest { private static final long SAMPLE_LARGE_UPDATE_COUNT = Long.MAX_VALUE; private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); - @ClassRule - public static final FlightServerTestRule SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(PRODUCER); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension(PRODUCER); - @Rule public final ErrorCollector collector = new ErrorCollector(); private Connection connection; private Statement statement; - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { PRODUCER.addSelectQuery( SAMPLE_QUERY_CMD, @@ -100,26 +98,25 @@ public static void setUpBeforeClass() { PRODUCER.addUpdateQuery(SAMPLE_LARGE_UPDATE_QUERY, SAMPLE_LARGE_UPDATE_COUNT); } - @Before + @BeforeEach public void setUp() throws SQLException { - connection = SERVER_TEST_RULE.getConnection(false); + connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false); statement = connection.createStatement(); } - @After + @AfterEach public void tearDown() throws Exception { AutoCloseables.close(statement, connection); } - @AfterClass + @AfterAll public static void tearDownAfterClass() throws Exception { AutoCloseables.close(PRODUCER); } @Test public void testExecuteShouldRunSelectQuery() throws SQLException { - collector.checkThat( - statement.execute(SAMPLE_QUERY_CMD), is(true)); // Means this is a SELECT query. + assertThat(statement.execute(SAMPLE_QUERY_CMD), is(true)); // Means this is a SELECT query. final Set numbers = IntStream.range(0, SAMPLE_QUERY_ROWS) .boxed() @@ -127,49 +124,48 @@ public void testExecuteShouldRunSelectQuery() throws SQLException { .collect(Collectors.toCollection(HashSet::new)); try (final ResultSet resultSet = statement.getResultSet()) { final int columnCount = resultSet.getMetaData().getColumnCount(); - collector.checkThat(columnCount, is(1)); + assertThat(columnCount, is(1)); int rowCount = 0; for (; resultSet.next(); rowCount++) { - collector.checkThat(numbers.remove(resultSet.getByte(1)), is(true)); + assertThat(numbers.remove(resultSet.getByte(1)), is(true)); } - collector.checkThat(rowCount, is(equalTo(SAMPLE_QUERY_ROWS))); + assertThat(rowCount, is(equalTo(SAMPLE_QUERY_ROWS))); } - collector.checkThat(numbers, is(Collections.emptySet())); - collector.checkThat( + assertThat(numbers, is(Collections.emptySet())); + assertThat( (long) statement.getUpdateCount(), is(allOf(equalTo(statement.getLargeUpdateCount()), equalTo(-1L)))); } @Test public void testExecuteShouldRunUpdateQueryForSmallUpdate() throws SQLException { - collector.checkThat( - statement.execute(SAMPLE_UPDATE_QUERY), is(false)); // Means this is an UPDATE query. - collector.checkThat( + assertThat(statement.execute(SAMPLE_UPDATE_QUERY), is(false)); // Means this is an UPDATE query. + assertThat( (long) statement.getUpdateCount(), is(allOf(equalTo(statement.getLargeUpdateCount()), equalTo(SAMPLE_UPDATE_COUNT)))); - collector.checkThat(statement.getResultSet(), is(nullValue())); + assertThat(statement.getResultSet(), is(nullValue())); } @Test public void testExecuteShouldRunUpdateQueryForLargeUpdate() throws SQLException { - collector.checkThat(statement.execute(SAMPLE_LARGE_UPDATE_QUERY), is(false)); // UPDATE query. + assertThat(statement.execute(SAMPLE_LARGE_UPDATE_QUERY), is(false)); // UPDATE query. final long updateCountSmall = statement.getUpdateCount(); final long updateCountLarge = statement.getLargeUpdateCount(); - collector.checkThat(updateCountLarge, is(equalTo(SAMPLE_LARGE_UPDATE_COUNT))); - collector.checkThat( + assertThat(updateCountLarge, is(equalTo(SAMPLE_LARGE_UPDATE_COUNT))); + assertThat( updateCountSmall, is( allOf( equalTo((long) AvaticaUtils.toSaturatedInt(updateCountLarge)), not(equalTo(updateCountLarge))))); - collector.checkThat(statement.getResultSet(), is(nullValue())); + assertThat(statement.getResultSet(), is(nullValue())); } @Test public void testUpdateCountShouldStartOnZero() throws SQLException { - collector.checkThat( + assertThat( (long) statement.getUpdateCount(), is(allOf(equalTo(statement.getLargeUpdateCount()), equalTo(0L)))); - collector.checkThat(statement.getResultSet(), is(nullValue())); + assertThat(statement.getResultSet(), is(nullValue())); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java index 669801a3b1da4..f7c31c590c556 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightStatementExecuteUpdateTest.java @@ -22,6 +22,8 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.sql.Connection; import java.sql.SQLException; @@ -37,14 +39,12 @@ import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; import org.apache.calcite.avatica.AvaticaUtils; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests for {@link ArrowFlightStatement#executeUpdate}. */ public class ArrowFlightStatementExecuteUpdateTest { @@ -60,15 +60,14 @@ public class ArrowFlightStatementExecuteUpdateTest { Collections.singletonList(Field.nullable("placeholder", MinorType.VARCHAR.getType()))); private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); - @ClassRule - public static final FlightServerTestRule SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(PRODUCER); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension(PRODUCER); - @Rule public final ErrorCollector collector = new ErrorCollector(); public Connection connection; public Statement statement; - @BeforeClass + @BeforeAll public static void setUpBeforeClass() { PRODUCER.addUpdateQuery(UPDATE_SAMPLE_QUERY, UPDATE_SAMPLE_QUERY_AFFECTED_COLS); PRODUCER.addUpdateQuery(LARGE_UPDATE_SAMPLE_QUERY, LARGE_UPDATE_SAMPLE_QUERY_AFFECTED_COLS); @@ -90,18 +89,18 @@ public static void setUpBeforeClass() { })); } - @Before + @BeforeEach public void setUp() throws SQLException { - connection = SERVER_TEST_RULE.getConnection(false); + connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false); statement = connection.createStatement(); } - @After + @AfterEach public void tearDown() throws Exception { AutoCloseables.close(statement, connection); } - @AfterClass + @AfterAll public static void tearDownAfterClass() throws Exception { AutoCloseables.close(PRODUCER); } @@ -109,8 +108,7 @@ public static void tearDownAfterClass() throws Exception { @Test public void testExecuteUpdateShouldReturnNumColsAffectedForNumRowsFittingInt() throws SQLException { - collector.checkThat( - statement.executeUpdate(UPDATE_SAMPLE_QUERY), is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); + assertThat(statement.executeUpdate(UPDATE_SAMPLE_QUERY), is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); } @Test @@ -118,7 +116,7 @@ public void testExecuteUpdateShouldReturnSaturatedNumColsAffectedIfDoesNotFitInI throws SQLException { final long result = statement.executeUpdate(LARGE_UPDATE_SAMPLE_QUERY); final long expectedRowCountRaw = LARGE_UPDATE_SAMPLE_QUERY_AFFECTED_COLS; - collector.checkThat( + assertThat( result, is( allOf( @@ -131,40 +129,52 @@ public void testExecuteUpdateShouldReturnSaturatedNumColsAffectedIfDoesNotFitInI @Test public void testExecuteLargeUpdateShouldReturnNumColsAffected() throws SQLException { - collector.checkThat( + assertThat( statement.executeLargeUpdate(LARGE_UPDATE_SAMPLE_QUERY), is(LARGE_UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); } - @Test(expected = SQLFeatureNotSupportedException.class) + @Test // TODO Implement `Statement#executeUpdate(String, int)` public void testExecuteUpdateUnsupportedWithDriverFlag() throws SQLException { - collector.checkThat( - statement.executeUpdate(UPDATE_SAMPLE_QUERY, Statement.RETURN_GENERATED_KEYS), - is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); + assertThrows( + SQLFeatureNotSupportedException.class, + () -> { + assertThat( + statement.executeUpdate(UPDATE_SAMPLE_QUERY, Statement.NO_GENERATED_KEYS), + is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); + }); } - @Test(expected = SQLFeatureNotSupportedException.class) + @Test // TODO Implement `Statement#executeUpdate(String, int[])` public void testExecuteUpdateUnsupportedWithArrayOfInts() throws SQLException { - collector.checkThat( - statement.executeUpdate(UPDATE_SAMPLE_QUERY, new int[0]), - is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); + assertThrows( + SQLFeatureNotSupportedException.class, + () -> { + assertThat( + statement.executeUpdate(UPDATE_SAMPLE_QUERY, new int[0]), + is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); + }); } - @Test(expected = SQLFeatureNotSupportedException.class) + @Test // TODO Implement `Statement#executeUpdate(String, String[])` public void testExecuteUpdateUnsupportedWithArraysOfStrings() throws SQLException { - collector.checkThat( - statement.executeUpdate(UPDATE_SAMPLE_QUERY, new String[0]), - is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); + assertThrows( + SQLFeatureNotSupportedException.class, + () -> { + assertThat( + statement.executeUpdate(UPDATE_SAMPLE_QUERY, new String[0]), + is(UPDATE_SAMPLE_QUERY_AFFECTED_COLS)); + }); } @Test public void testExecuteShouldExecuteUpdateQueryAutomatically() throws SQLException { - collector.checkThat( + assertThat( statement.execute(UPDATE_SAMPLE_QUERY), is(false)); // Meaning there was an update query. - collector.checkThat( + assertThat( statement.execute(REGULAR_QUERY_SAMPLE), is(true)); // Meaning there was a select query. } @@ -172,26 +182,26 @@ public void testExecuteShouldExecuteUpdateQueryAutomatically() throws SQLExcepti public void testShouldFailToPrepareStatementForNullQuery() { int count = 0; try { - collector.checkThat(statement.execute(null), is(false)); + assertThat(statement.execute(null), is(false)); } catch (final SQLException e) { count++; - collector.checkThat(e.getCause(), is(instanceOf(NullPointerException.class))); + assertThat(e.getCause(), is(instanceOf(NullPointerException.class))); } - collector.checkThat(count, is(1)); + assertThat(count, is(1)); } @Test public void testShouldFailToPrepareStatementForClosedStatement() throws SQLException { statement.close(); - collector.checkThat(statement.isClosed(), is(true)); + assertThat(statement.isClosed(), is(true)); int count = 0; try { statement.execute(UPDATE_SAMPLE_QUERY); } catch (final SQLException e) { count++; - collector.checkThat(e.getMessage(), is("Statement closed")); + assertThat(e.getMessage(), is("Statement closed")); } - collector.checkThat(count, is(1)); + assertThat(count, is(1)); } @Test @@ -208,10 +218,10 @@ public void testShouldFailToPrepareStatementForBadStatement() { * we simply throw an `IllegalArgumentException` for queries not registered * in our `MockFlightSqlProducer`. */ - collector.checkThat( + assertThat( e.getMessage(), is(format("Error while executing SQL \"%s\": Query not found", badQuery))); } - collector.checkThat(count, is(1)); + assertThat(count, is(1)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionMutualTlsTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionMutualTlsTest.java index 65b0db285f8cc..cc95115b9330b 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionMutualTlsTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionMutualTlsTest.java @@ -16,8 +16,10 @@ */ package org.apache.arrow.driver.jdbc; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.net.URLEncoder; @@ -34,16 +36,15 @@ import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests encrypted connections. */ public class ConnectionMutualTlsTest { - @ClassRule public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + @RegisterExtension public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; private static final String tlsRootCertsPath; private static final String clientMTlsCertPath; private static final String badClientMTlsCertPath; @@ -73,8 +74,8 @@ public class ConnectionMutualTlsTest { UserPasswordAuthentication authentication = new UserPasswordAuthentication.Builder().user(userTest, passTest).build(); - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(authentication) .useEncryption(certKey.cert, certKey.key) .useMTlsClientVerification(serverMTlsCACert) @@ -84,12 +85,12 @@ public class ConnectionMutualTlsTest { private BufferAllocator allocator; - @Before + @BeforeEach public void setUp() throws Exception { allocator = new RootAllocator(Long.MAX_VALUE); } - @After + @AfterEach public void tearDown() throws Exception { allocator.getChildAllocators().forEach(BufferAllocator::close); AutoCloseables.close(allocator); @@ -105,8 +106,8 @@ public void testGetEncryptedClientAuthenticated() throws Exception { try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withUsername(userTest) .withPassword(passTest) .withTlsRootCertificates(tlsRootCertsPath) @@ -131,8 +132,8 @@ public void testGetEncryptedClientWithBadMTlsCertPath() { () -> { try (ArrowFlightSqlClientHandler handler = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withUsername(userTest) .withPassword(passTest) .withTlsRootCertificates(tlsRootCertsPath) @@ -141,7 +142,7 @@ public void testGetEncryptedClientWithBadMTlsCertPath() { .withBufferAllocator(allocator) .withEncryption(true) .build()) { - Assert.fail(); + fail(); } }); } @@ -158,8 +159,8 @@ public void testGetEncryptedClientWithBadMTlsKeyPath() { () -> { try (ArrowFlightSqlClientHandler handler = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withUsername(userTest) .withPassword(passTest) .withTlsRootCertificates(tlsRootCertsPath) @@ -168,7 +169,7 @@ public void testGetEncryptedClientWithBadMTlsKeyPath() { .withBufferAllocator(allocator) .withEncryption(true) .build()) { - Assert.fail(); + fail(); } }); } @@ -182,7 +183,7 @@ public void testGetEncryptedClientWithBadMTlsKeyPath() { public void testGetNonAuthenticatedEncryptedClientNoAuth() throws Exception { try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) .withTlsRootCertificates(tlsRootCertsPath) .withClientCertificate(clientMTlsCertPath) .withClientKey(clientMTlsKeyPath) @@ -205,7 +206,7 @@ public void testGetEncryptedConnectionWithValidCredentialsAndTlsRootsPath() thro properties.put(ArrowFlightConnectionProperty.HOST.camelName(), "localhost"); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); properties.put(ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), tlsRootCertsPath); @@ -216,7 +217,7 @@ public void testGetEncryptedConnectionWithValidCredentialsAndTlsRootsPath() thro final ArrowFlightJdbcDataSource dataSource = ArrowFlightJdbcDataSource.createNewDataSource(properties); try (final Connection connection = dataSource.getConnection()) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -231,9 +232,9 @@ public void testGetNonAuthenticatedEncryptedConnection() throws Exception { final Properties properties = new Properties(); properties.put( - ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_RULE.getHost()); + ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getHost()); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USE_ENCRYPTION.camelName(), true); properties.put(ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), tlsRootCertsPath); properties.put( @@ -243,7 +244,7 @@ public void testGetNonAuthenticatedEncryptedConnection() throws Exception { final ArrowFlightJdbcDataSource dataSource = ArrowFlightJdbcDataSource.createNewDataSource(properties); try (final Connection connection = dataSource.getConnection()) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -262,7 +263,7 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlWithDriverManager() throw String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s" + "&useEncryption=true&%s=%s&%s=%s&%s=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), @@ -273,7 +274,7 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlWithDriverManager() throw URLEncoder.encode(clientMTlsKeyPath, "UTF-8")); try (Connection connection = DriverManager.getConnection(jdbcUrl)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -302,10 +303,11 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlWithDriverManager() throw properties.setProperty(ArrowFlightConnectionProperty.CLIENT_KEY.camelName(), clientMTlsKeyPath); final String jdbcUrl = - String.format("jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()); + String.format( + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()); try (Connection connection = DriverManager.getConnection(jdbcUrl, properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -332,10 +334,11 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlAndPropertiesUsingPutWith properties.put(ArrowFlightConnectionProperty.CLIENT_KEY.camelName(), clientMTlsKeyPath); final String jdbcUrl = - String.format("jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()); + String.format( + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()); try (Connection connection = DriverManager.getConnection(jdbcUrl, properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -355,7 +358,7 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s" + "&useEncryption=1&useSystemTrustStore=0&%s=%s&%s=%s&%s=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), @@ -366,7 +369,7 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( URLEncoder.encode(clientMTlsKeyPath, "UTF-8")); try (Connection connection = DriverManager.getConnection(jdbcUrl)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -396,10 +399,11 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( properties.setProperty(ArrowFlightConnectionProperty.CLIENT_KEY.camelName(), clientMTlsKeyPath); final String jdbcUrl = - String.format("jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()); + String.format( + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()); try (Connection connection = DriverManager.getConnection(jdbcUrl, properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -428,10 +432,11 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( properties.put(ArrowFlightConnectionProperty.CLIENT_KEY.camelName(), clientMTlsKeyPath); final String jdbcUrl = - String.format("jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()); + String.format( + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()); try (Connection connection = DriverManager.getConnection(jdbcUrl, properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java index f7d99349664cf..8e872a11671c5 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java @@ -16,10 +16,10 @@ */ package org.apache.arrow.driver.jdbc; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.net.URISyntaxException; import java.sql.Connection; @@ -34,16 +34,15 @@ import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests for {@link Connection}. */ public class ConnectionTest { - @ClassRule public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + @RegisterExtension public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); private static final String userTest = "user1"; private static final String passTest = "pass1"; @@ -52,8 +51,8 @@ public class ConnectionTest { UserPasswordAuthentication authentication = new UserPasswordAuthentication.Builder().user(userTest, passTest).build(); - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(authentication) .producer(PRODUCER) .build(); @@ -61,12 +60,12 @@ public class ConnectionTest { private BufferAllocator allocator; - @Before + @BeforeEach public void setUp() throws Exception { allocator = new RootAllocator(Long.MAX_VALUE); } - @After + @AfterEach public void tearDown() throws Exception { allocator.getChildAllocators().forEach(BufferAllocator::close); AutoCloseables.close(allocator); @@ -85,7 +84,7 @@ public void testUnencryptedConnectionShouldOpenSuccessfullyWhenProvidedValidCred properties.put(ArrowFlightConnectionProperty.HOST.camelName(), "localhost"); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); properties.put("useEncryption", false); @@ -93,11 +92,11 @@ public void testUnencryptedConnectionShouldOpenSuccessfullyWhenProvidedValidCred try (Connection connection = DriverManager.getConnection( "jdbc:arrow-flight-sql://" - + FLIGHT_SERVER_TEST_RULE.getHost() + + FLIGHT_SERVER_TEST_EXTENSION.getHost() + ":" - + FLIGHT_SERVER_TEST_RULE.getPort(), + + FLIGHT_SERVER_TEST_EXTENSION.getPort(), properties)) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -111,7 +110,7 @@ public void testTokenOverridesUsernameAndPasswordAuth() { properties.put(ArrowFlightConnectionProperty.HOST.camelName(), "localhost"); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); properties.put(ArrowFlightConnectionProperty.TOKEN.camelName(), "token"); @@ -124,11 +123,11 @@ public void testTokenOverridesUsernameAndPasswordAuth() { try (Connection conn = DriverManager.getConnection( "jdbc:arrow-flight-sql://" - + FLIGHT_SERVER_TEST_RULE.getHost() + + FLIGHT_SERVER_TEST_EXTENSION.getHost() + ":" - + FLIGHT_SERVER_TEST_RULE.getPort(), + + FLIGHT_SERVER_TEST_EXTENSION.getPort(), properties)) { - Assert.fail(); + fail(); } }); assertTrue(e.getMessage().contains("UNAUTHENTICATED")); @@ -140,7 +139,7 @@ public void testTokenOverridesUsernameAndPasswordAuth() { * * @throws SQLException on error. */ - @Test(expected = SQLException.class) + @Test public void testUnencryptedConnectionWithEmptyHost() throws Exception { final Properties properties = new Properties(); @@ -148,9 +147,13 @@ public void testUnencryptedConnectionWithEmptyHost() throws Exception { properties.put("password", passTest); final String invalidUrl = "jdbc:arrow-flight-sql://"; - try (Connection conn = DriverManager.getConnection(invalidUrl, properties)) { - Assert.fail("Expected SQLException."); - } + assertThrows( + SQLException.class, + () -> { + try (Connection conn = DriverManager.getConnection(invalidUrl, properties)) { + fail("Expected SQLException."); + } + }); } /** @@ -163,8 +166,8 @@ public void testGetBasicClientAuthenticatedShouldOpenConnection() throws Excepti try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withEncryption(false) .withUsername(userTest) .withPassword(passTest) @@ -181,7 +184,7 @@ public void testGetBasicClientAuthenticatedShouldOpenConnection() throws Excepti * * @throws SQLException on error. */ - @Test(expected = SQLException.class) + @Test public void testUnencryptedConnectionProvidingInvalidPort() throws Exception { final Properties properties = new Properties(); @@ -190,11 +193,15 @@ public void testUnencryptedConnectionProvidingInvalidPort() throws Exception { properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); properties.put(ArrowFlightConnectionProperty.USE_ENCRYPTION.camelName(), false); final String invalidUrl = - "jdbc:arrow-flight-sql://" + FLIGHT_SERVER_TEST_RULE.getHost() + ":" + 65537; - - try (Connection conn = DriverManager.getConnection(invalidUrl, properties)) { - fail("Expected SQLException"); - } + "jdbc:arrow-flight-sql://" + FLIGHT_SERVER_TEST_EXTENSION.getHost() + ":" + 65537; + + assertThrows( + SQLException.class, + () -> { + try (Connection conn = DriverManager.getConnection(invalidUrl, properties)) { + fail("Expected SQLException"); + } + }); } /** @@ -207,7 +214,7 @@ public void testGetBasicClientNoAuthShouldOpenConnection() throws Exception { try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) .withBufferAllocator(allocator) .withEncryption(false) .build()) { @@ -227,11 +234,11 @@ public void testUnencryptedConnectionShouldOpenSuccessfullyWithoutAuthentication final Properties properties = new Properties(); properties.put(ArrowFlightConnectionProperty.HOST.camelName(), "localhost"); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USE_ENCRYPTION.camelName(), false); try (Connection connection = DriverManager.getConnection("jdbc:arrow-flight-sql://localhost:32010", properties)) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -240,7 +247,7 @@ public void testUnencryptedConnectionShouldOpenSuccessfullyWithoutAuthentication * * @throws SQLException The exception expected to be thrown. */ - @Test(expected = SQLException.class) + @Test public void testUnencryptedConnectionShouldThrowExceptionWhenProvidedWithInvalidCredentials() throws Exception { @@ -249,14 +256,18 @@ public void testUnencryptedConnectionShouldThrowExceptionWhenProvidedWithInvalid properties.put(ArrowFlightConnectionProperty.HOST.camelName(), "localhost"); properties.put(ArrowFlightConnectionProperty.USER.camelName(), "invalidUser"); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USE_ENCRYPTION.camelName(), false); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), "invalidPassword"); - try (Connection ignored = - DriverManager.getConnection("jdbc:arrow-flight-sql://localhost:32010", properties)) { - Assert.fail(); - } + assertThrows( + SQLException.class, + () -> { + try (Connection ignored = + DriverManager.getConnection("jdbc:arrow-flight-sql://localhost:32010", properties)) { + fail(); + } + }); } /** @@ -274,8 +285,8 @@ public void testTLSConnectionPropertyFalseCorrectCastUrlWithDriverManager() thro DriverManager.getConnection( String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s&useEncryption=false", - FLIGHT_SERVER_TEST_RULE.getPort(), userTest, passTest))) { - Assert.assertTrue(connection.isValid(0)); + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest))) { + assertTrue(connection.isValid(0)); } } @@ -301,9 +312,9 @@ public void testTLSConnectionPropertyFalseCorrectCastUrlWithDriverManager() thro try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -327,9 +338,9 @@ public void testTLSConnectionPropertyFalseCorrectCastUrlAndPropertiesUsingPutWit try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -349,8 +360,8 @@ public void testTLSConnectionPropertyFalseIntegerCorrectCastUrlWithDriverManager DriverManager.getConnection( String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s&useEncryption=0", - FLIGHT_SERVER_TEST_RULE.getPort(), userTest, passTest))) { - Assert.assertTrue(connection.isValid(0)); + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest))) { + assertTrue(connection.isValid(0)); } } @@ -376,9 +387,9 @@ public void testTLSConnectionPropertyFalseIntegerCorrectCastUrlWithDriverManager try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -404,9 +415,9 @@ public void testTLSConnectionPropertyFalseIntegerCorrectCastUrlWithDriverManager try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -426,8 +437,8 @@ public void testThreadPoolSizeConnectionPropertyCorrectCastUrlWithDriverManager( DriverManager.getConnection( String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s&threadPoolSize=1&useEncryption=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), userTest, passTest, false))) { - Assert.assertTrue(connection.isValid(0)); + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, false))) { + assertTrue(connection.isValid(0)); } } @@ -454,9 +465,9 @@ public void testThreadPoolSizeConnectionPropertyCorrectCastUrlWithDriverManager( try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -483,9 +494,9 @@ public void testThreadPoolSizeConnectionPropertyCorrectCastUrlWithDriverManager( try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -505,8 +516,8 @@ public void testPasswordConnectionPropertyIntegerCorrectCastUrlWithDriverManager DriverManager.getConnection( String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s&useEncryption=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), userTest, passTest, false))) { - Assert.assertTrue(connection.isValid(0)); + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, false))) { + assertTrue(connection.isValid(0)); } } @@ -532,9 +543,9 @@ public void testPasswordConnectionPropertyIntegerCorrectCastUrlWithDriverManager try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -560,9 +571,9 @@ public void testPasswordConnectionPropertyIntegerCorrectCastUrlWithDriverManager try (Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsRootCertsTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsRootCertsTest.java index a36797f289231..f46ab1fa1c373 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsRootCertsTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsRootCertsTest.java @@ -16,8 +16,10 @@ */ package org.apache.arrow.driver.jdbc; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.net.URLEncoder; import java.sql.Connection; @@ -33,16 +35,15 @@ import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests encrypted connections. */ public class ConnectionTlsRootCertsTest { - @ClassRule public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + @RegisterExtension public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; private static final String tlsRootCertsPath; private static final String badTlsRootCertsPath; private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); @@ -60,8 +61,8 @@ public class ConnectionTlsRootCertsTest { UserPasswordAuthentication authentication = new UserPasswordAuthentication.Builder().user(userTest, passTest).build(); - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(authentication) .useEncryption(certKey.cert, certKey.key) .producer(PRODUCER) @@ -70,12 +71,12 @@ public class ConnectionTlsRootCertsTest { private BufferAllocator allocator; - @Before + @BeforeEach public void setUp() throws Exception { allocator = new RootAllocator(Long.MAX_VALUE); } - @After + @AfterEach public void tearDown() throws Exception { allocator.getChildAllocators().forEach(BufferAllocator::close); AutoCloseables.close(allocator); @@ -91,8 +92,8 @@ public void testGetEncryptedClientAuthenticated() throws Exception { try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withUsername(userTest) .withPassword(passTest) .withTlsRootCertificates(tlsRootCertsPath) @@ -114,12 +115,12 @@ public void testGetEncryptedClientWithNoCertificateOnKeyStore() { () -> { try (ArrowFlightSqlClientHandler handler = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) .withTlsRootCertificates(badTlsRootCertsPath) .withBufferAllocator(allocator) .withEncryption(true) .build()) { - Assert.fail(); + fail(); } }); } @@ -133,7 +134,7 @@ public void testGetEncryptedClientWithNoCertificateOnKeyStore() { public void testGetNonAuthenticatedEncryptedClientNoAuth() throws Exception { try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) .withTlsRootCertificates(tlsRootCertsPath) .withBufferAllocator(allocator) .withEncryption(true) @@ -154,7 +155,7 @@ public void testGetEncryptedConnectionWithValidCredentialsAndTlsRootsPath() thro properties.put(ArrowFlightConnectionProperty.HOST.camelName(), "localhost"); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); properties.put(ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), tlsRootCertsPath); @@ -162,7 +163,7 @@ public void testGetEncryptedConnectionWithValidCredentialsAndTlsRootsPath() thro final ArrowFlightJdbcDataSource dataSource = ArrowFlightJdbcDataSource.createNewDataSource(properties); try (final Connection connection = dataSource.getConnection()) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -177,16 +178,16 @@ public void testGetNonAuthenticatedEncryptedConnection() throws Exception { final Properties properties = new Properties(); properties.put( - ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_RULE.getHost()); + ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getHost()); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USE_ENCRYPTION.camelName(), true); properties.put(ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), tlsRootCertsPath); final ArrowFlightJdbcDataSource dataSource = ArrowFlightJdbcDataSource.createNewDataSource(properties); try (final Connection connection = dataSource.getConnection()) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -206,12 +207,12 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlWithDriverManager() throw String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s" + "&useEncryption=true&%s=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), URLEncoder.encode(tlsRootCertsPath, "UTF-8")))) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -239,9 +240,9 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlWithDriverManager() throw try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -267,9 +268,9 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlAndPropertiesUsingPutWith try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -290,12 +291,12 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s" + "&useEncryption=1&useSystemTrustStore=0&%s=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, ArrowFlightConnectionProperty.TLS_ROOT_CERTS.camelName(), URLEncoder.encode(tlsRootCertsPath, "UTF-8")))) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -324,9 +325,9 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -354,9 +355,9 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsTest.java index 599aece248f7b..387436afe99d2 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTlsTest.java @@ -16,7 +16,10 @@ */ package org.apache.arrow.driver.jdbc; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.net.URLEncoder; import java.nio.file.Paths; @@ -34,16 +37,15 @@ import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; import org.apache.arrow.util.Preconditions; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Tests encrypted connections. */ public class ConnectionTlsTest { - @ClassRule public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + @RegisterExtension public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; private static final MockFlightSqlProducer PRODUCER = new MockFlightSqlProducer(); private static final String userTest = "user1"; private static final String passTest = "pass1"; @@ -55,8 +57,8 @@ public class ConnectionTlsTest { UserPasswordAuthentication authentication = new UserPasswordAuthentication.Builder().user(userTest, passTest).build(); - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(authentication) .useEncryption(certKey.cert, certKey.key) .producer(PRODUCER) @@ -68,7 +70,7 @@ public class ConnectionTlsTest { private final String trustStorePass = "flight"; private BufferAllocator allocator; - @Before + @BeforeEach public void setUp() throws Exception { trustStorePath = Paths.get(Preconditions.checkNotNull(getClass().getResource("/keys/keyStore.jks")).toURI()) @@ -81,7 +83,7 @@ public void setUp() throws Exception { allocator = new RootAllocator(Long.MAX_VALUE); } - @After + @AfterEach public void tearDown() throws Exception { allocator.getChildAllocators().forEach(BufferAllocator::close); AutoCloseables.close(allocator); @@ -97,8 +99,8 @@ public void testGetEncryptedClientAuthenticatedWithDisableCertVerification() thr try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withUsername(userTest) .withPassword(passTest) .withDisableCertificateVerification(true) @@ -119,8 +121,8 @@ public void testGetEncryptedClientAuthenticated() throws Exception { try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withSystemTrustStore(false) .withUsername(userTest) .withPassword(passTest) @@ -139,21 +141,25 @@ public void testGetEncryptedClientAuthenticated() throws Exception { * * @throws Exception on error. */ - @Test(expected = SQLException.class) + @Test public void testGetEncryptedClientWithNoCertificateOnKeyStore() throws Exception { final String noCertificateKeyStorePassword = "flight1"; - try (ArrowFlightSqlClientHandler ignored = - new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withTrustStorePath(noCertificateKeyStorePath) - .withTrustStorePassword(noCertificateKeyStorePassword) - .withSystemTrustStore(false) - .withBufferAllocator(allocator) - .withEncryption(true) - .build()) { - Assert.fail(); - } + assertThrows( + SQLException.class, + () -> { + try (ArrowFlightSqlClientHandler ignored = + new ArrowFlightSqlClientHandler.Builder() + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withTrustStorePath(noCertificateKeyStorePath) + .withTrustStorePassword(noCertificateKeyStorePassword) + .withSystemTrustStore(false) + .withBufferAllocator(allocator) + .withEncryption(true) + .build()) { + fail(); + } + }); } /** @@ -165,7 +171,7 @@ public void testGetEncryptedClientWithNoCertificateOnKeyStore() throws Exception public void testGetNonAuthenticatedEncryptedClientNoAuth() throws Exception { try (ArrowFlightSqlClientHandler client = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) .withSystemTrustStore(false) .withTrustStorePath(trustStorePath) .withTrustStorePassword(trustStorePass) @@ -182,21 +188,25 @@ public void testGetNonAuthenticatedEncryptedClientNoAuth() throws Exception { * * @throws Exception on error. */ - @Test(expected = SQLException.class) + @Test public void testGetEncryptedClientWithKeyStoreBadPasswordAndNoAuth() throws Exception { String keyStoreBadPassword = "badPassword"; - try (ArrowFlightSqlClientHandler ignored = - new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withSystemTrustStore(false) - .withTrustStorePath(trustStorePath) - .withTrustStorePassword(keyStoreBadPassword) - .withBufferAllocator(allocator) - .withEncryption(true) - .build()) { - Assert.fail(); - } + assertThrows( + SQLException.class, + () -> { + try (ArrowFlightSqlClientHandler ignored = + new ArrowFlightSqlClientHandler.Builder() + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withSystemTrustStore(false) + .withTrustStorePath(trustStorePath) + .withTrustStorePassword(keyStoreBadPassword) + .withBufferAllocator(allocator) + .withEncryption(true) + .build()) { + fail(); + } + }); } /** @@ -211,7 +221,7 @@ public void testGetEncryptedConnectionWithValidCredentialsAndKeyStore() throws E properties.put(ArrowFlightConnectionProperty.HOST.camelName(), "localhost"); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); properties.put(ArrowFlightConnectionProperty.TRUST_STORE.camelName(), trustStorePath); @@ -221,7 +231,7 @@ public void testGetEncryptedConnectionWithValidCredentialsAndKeyStore() throws E final ArrowFlightJdbcDataSource dataSource = ArrowFlightJdbcDataSource.createNewDataSource(properties); try (final Connection connection = dataSource.getConnection()) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -231,14 +241,14 @@ public void testGetEncryptedConnectionWithValidCredentialsAndKeyStore() throws E * * @throws SQLException on error. */ - @Test(expected = SQLException.class) + @Test public void testGetAuthenticatedEncryptedConnectionWithKeyStoreBadPassword() throws Exception { final Properties properties = new Properties(); properties.put( - ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_RULE.getHost()); + ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getHost()); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); properties.put(ArrowFlightConnectionProperty.USE_ENCRYPTION.camelName(), true); @@ -247,9 +257,14 @@ public void testGetAuthenticatedEncryptedConnectionWithKeyStoreBadPassword() thr final ArrowFlightJdbcDataSource dataSource = ArrowFlightJdbcDataSource.createNewDataSource(properties); - try (final Connection ignored = dataSource.getConnection()) { - Assert.fail(); - } + + assertThrows( + SQLException.class, + () -> { + try (final Connection ignored = dataSource.getConnection()) { + fail(); + } + }); } /** @@ -263,9 +278,9 @@ public void testGetNonAuthenticatedEncryptedConnection() throws Exception { final Properties properties = new Properties(); properties.put( - ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_RULE.getHost()); + ArrowFlightConnectionProperty.HOST.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getHost()); properties.put( - ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_RULE.getPort()); + ArrowFlightConnectionProperty.PORT.camelName(), FLIGHT_SERVER_TEST_EXTENSION.getPort()); properties.put(ArrowFlightConnectionProperty.USE_ENCRYPTION.camelName(), true); properties.put(ArrowFlightConnectionProperty.USE_SYSTEM_TRUST_STORE.camelName(), false); properties.put(ArrowFlightConnectionProperty.TRUST_STORE.camelName(), trustStorePath); @@ -274,7 +289,7 @@ public void testGetNonAuthenticatedEncryptedConnection() throws Exception { final ArrowFlightJdbcDataSource dataSource = ArrowFlightJdbcDataSource.createNewDataSource(properties); try (final Connection connection = dataSource.getConnection()) { - Assert.assertTrue(connection.isValid(300)); + assertTrue(connection.isValid(300)); } } @@ -294,14 +309,14 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlWithDriverManager() throw String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s" + "&useEncryption=true&useSystemTrustStore=false&%s=%s&%s=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, ArrowFlightConnectionProperty.TRUST_STORE.camelName(), URLEncoder.encode(trustStorePath, "UTF-8"), ArrowFlightConnectionProperty.TRUST_STORE_PASSWORD.camelName(), URLEncoder.encode(trustStorePass, "UTF-8")))) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -332,9 +347,9 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlWithDriverManager() throw try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -362,9 +377,9 @@ public void testTLSConnectionPropertyTrueCorrectCastUrlAndPropertiesUsingPutWith try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -385,14 +400,14 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( String.format( "jdbc:arrow-flight-sql://localhost:%s?user=%s&password=%s" + "&useEncryption=1&useSystemTrustStore=0&%s=%s&%s=%s", - FLIGHT_SERVER_TEST_RULE.getPort(), + FLIGHT_SERVER_TEST_EXTENSION.getPort(), userTest, passTest, ArrowFlightConnectionProperty.TRUST_STORE.camelName(), URLEncoder.encode(trustStorePath, "UTF-8"), ArrowFlightConnectionProperty.TRUST_STORE_PASSWORD.camelName(), URLEncoder.encode(trustStorePass, "UTF-8")))) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -423,9 +438,9 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } @@ -455,9 +470,9 @@ public void testTLSConnectionPropertyTrueIntegerCorrectCastUrlWithDriverManager( try (final Connection connection = DriverManager.getConnection( String.format( - "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_RULE.getPort()), + "jdbc:arrow-flight-sql://localhost:%s", FLIGHT_SERVER_TEST_EXTENSION.getPort()), properties)) { - Assert.assertTrue(connection.isValid(0)); + assertTrue(connection.isValid(0)); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/FlightServerTestRule.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/FlightServerTestExtension.java similarity index 85% rename from java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/FlightServerTestRule.java rename to java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/FlightServerTestExtension.java index 183c2dbe31985..aa586651f569f 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/FlightServerTestRule.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/FlightServerTestExtension.java @@ -42,9 +42,9 @@ import org.apache.arrow.memory.RootAllocator; import org.apache.arrow.util.AutoCloseables; import org.apache.arrow.util.Preconditions; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,11 +52,12 @@ * Utility class for unit tests that need to instantiate a {@link FlightServer} and interact with * it. */ -public class FlightServerTestRule implements TestRule, AutoCloseable { +public class FlightServerTestExtension + implements BeforeAllCallback, AfterAllCallback, AutoCloseable { public static final String DEFAULT_USER = "flight-test-user"; public static final String DEFAULT_PASSWORD = "flight-test-password"; - private static final Logger LOGGER = LoggerFactory.getLogger(FlightServerTestRule.class); + private static final Logger LOGGER = LoggerFactory.getLogger(FlightServerTestExtension.class); private final Properties properties; private final ArrowFlightConnectionConfigImpl config; @@ -68,7 +69,7 @@ public class FlightServerTestRule implements TestRule, AutoCloseable { private final MiddlewareCookie.Factory middlewareCookieFactory = new MiddlewareCookie.Factory(); - private FlightServerTestRule( + private FlightServerTestExtension( final Properties properties, final ArrowFlightConnectionConfigImpl config, final BufferAllocator allocator, @@ -86,12 +87,14 @@ private FlightServerTestRule( } /** - * Create a {@link FlightServerTestRule} with standard values such as: user, password, localhost. + * Create a {@link FlightServerTestExtension} with standard values such as: user, password, + * localhost. * - * @param producer the producer used to create the FlightServerTestRule. - * @return the FlightServerTestRule. + * @param producer the producer used to create the FlightServerTestExtension. + * @return the FlightServerTestExtension. */ - public static FlightServerTestRule createStandardTestRule(final FlightSqlProducer producer) { + public static FlightServerTestExtension createStandardTestExtension( + final FlightSqlProducer producer) { UserPasswordAuthentication authentication = new UserPasswordAuthentication.Builder().user(DEFAULT_USER, DEFAULT_PASSWORD).build(); @@ -151,19 +154,26 @@ private FlightServer initiateServer(Location location) throws IOException { } @Override - public Statement apply(Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try (FlightServer flightServer = getStartServer(location -> initiateServer(location), 3)) { - properties.put("port", flightServer.getPort()); - LOGGER.info("Started " + FlightServer.class.getName() + " as " + flightServer); - base.evaluate(); - } finally { - close(); - } - } - }; + public void beforeAll(ExtensionContext context) throws Exception { + try { + FlightServer flightServer = getStartServer(this::initiateServer, 3); + properties.put("port", flightServer.getPort()); + LOGGER.info("Started " + FlightServer.class.getName() + " as " + flightServer); + context.getStore(ExtensionContext.Namespace.GLOBAL).put("flightServer", flightServer); + } catch (Exception e) { + LOGGER.error("Failed to start FlightServer", e); + throw e; + } + } + + @Override + public void afterAll(ExtensionContext context) throws Exception { + FlightServer flightServer = + context.getStore(ExtensionContext.Namespace.GLOBAL).get("flightServer", FlightServer.class); + if (flightServer != null) { + flightServer.close(); + } + close(); } private FlightServer getStartServer( @@ -210,7 +220,7 @@ public void close() throws Exception { AutoCloseables.close(allocator); } - /** Builder for {@link FlightServerTestRule}. */ + /** Builder for {@link FlightServerTestExtension}. */ public static final class Builder { private final Properties properties; private FlightSqlProducer producer; @@ -270,13 +280,13 @@ public Builder useMTlsClientVerification(final File mTlsCACert) { } /** - * Builds the {@link FlightServerTestRule} using the provided values. + * Builds the {@link FlightServerTestExtension} using the provided values. * - * @return a {@link FlightServerTestRule}. + * @return a {@link FlightServerTestExtension}. */ - public FlightServerTestRule build() { + public FlightServerTestExtension build() { authentication.populateProperties(properties); - return new FlightServerTestRule( + return new FlightServerTestExtension( properties, new ArrowFlightConnectionConfigImpl(properties), new RootAllocator(Long.MAX_VALUE), diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetMetadataTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetMetadataTest.java index 9d1c11662d0dd..4583194f50897 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetMetadataTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetMetadataTest.java @@ -18,6 +18,8 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.sql.Connection; import java.sql.ResultSet; @@ -27,28 +29,24 @@ import java.sql.Types; import org.apache.arrow.driver.jdbc.utils.CoreMockedSqlProducers; import org.hamcrest.CoreMatchers; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ResultSetMetadataTest { private static ResultSetMetaData metadata; private static Connection connection; - @Rule public ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension( + CoreMockedSqlProducers.getLegacyProducer()); - @ClassRule - public static final FlightServerTestRule SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(CoreMockedSqlProducers.getLegacyProducer()); - - @BeforeClass + @BeforeAll public static void setup() throws SQLException { - connection = SERVER_TEST_RULE.getConnection(false); + connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false); try (Statement statement = connection.createStatement(); ResultSet resultSet = @@ -57,7 +55,7 @@ public static void setup() throws SQLException { } } - @AfterClass + @AfterAll public static void teardown() throws SQLException { connection.close(); } @@ -65,7 +63,7 @@ public static void teardown() throws SQLException { /** Test if {@link ResultSetMetaData} object is not null. */ @Test public void testShouldGetResultSetMetadata() { - collector.checkThat(metadata, CoreMatchers.is(notNullValue())); + assertThat(metadata, CoreMatchers.is(notNullValue())); } /** @@ -92,22 +90,22 @@ public void testShouldGetColumnTypesName() throws SQLException { final String secondColumn = metadata.getColumnTypeName(2); final String thirdColumn = metadata.getColumnTypeName(3); - collector.checkThat(firstColumn, equalTo("BIGINT")); - collector.checkThat(secondColumn, equalTo("VARCHAR")); - collector.checkThat(thirdColumn, equalTo("FLOAT")); + assertThat(firstColumn, equalTo("BIGINT")); + assertThat(secondColumn, equalTo("VARCHAR")); + assertThat(thirdColumn, equalTo("FLOAT")); } /** * Test if {@link ResultSetMetaData#getColumnTypeName(int)} passing an column index that does not * exist. - * - * @throws SQLException in case of error. */ - @Test(expected = IndexOutOfBoundsException.class) - public void testShouldGetColumnTypesNameFromOutOfBoundIndex() throws SQLException { - metadata.getColumnTypeName(4); - - Assert.fail(); + @Test + public void testShouldGetColumnTypesNameFromOutOfBoundIndex() { + assertThrows( + IndexOutOfBoundsException.class, + () -> { + metadata.getColumnTypeName(4); + }); } /** @@ -121,22 +119,18 @@ public void testShouldGetColumnNames() throws SQLException { final String secondColumn = metadata.getColumnName(2); final String thirdColumn = metadata.getColumnName(3); - collector.checkThat(firstColumn, equalTo("integer0")); - collector.checkThat(secondColumn, equalTo("string1")); - collector.checkThat(thirdColumn, equalTo("float2")); + assertThat(firstColumn, equalTo("integer0")); + assertThat(secondColumn, equalTo("string1")); + assertThat(thirdColumn, equalTo("float2")); } /** * Test {@link ResultSetMetaData#getColumnTypeName(int)} passing an column index that does not * exist. - * - * @throws SQLException in case of error. */ - @Test(expected = IndexOutOfBoundsException.class) - public void testShouldGetColumnNameFromOutOfBoundIndex() throws SQLException { - metadata.getColumnName(4); - - Assert.fail(); + @Test + public void testShouldGetColumnNameFromOutOfBoundIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> metadata.getColumnName(4)); } /** @@ -150,84 +144,80 @@ public void testShouldGetColumnType() throws SQLException { final int secondColumn = metadata.getColumnType(2); final int thirdColumn = metadata.getColumnType(3); - collector.checkThat(firstColumn, equalTo(Types.BIGINT)); - collector.checkThat(secondColumn, equalTo(Types.VARCHAR)); - collector.checkThat(thirdColumn, equalTo(Types.FLOAT)); + assertThat(firstColumn, equalTo(Types.BIGINT)); + assertThat(secondColumn, equalTo(Types.VARCHAR)); + assertThat(thirdColumn, equalTo(Types.FLOAT)); } @Test public void testShouldGetPrecision() throws SQLException { - collector.checkThat(metadata.getPrecision(1), equalTo(10)); - collector.checkThat(metadata.getPrecision(2), equalTo(65535)); - collector.checkThat(metadata.getPrecision(3), equalTo(15)); + assertThat(metadata.getPrecision(1), equalTo(10)); + assertThat(metadata.getPrecision(2), equalTo(65535)); + assertThat(metadata.getPrecision(3), equalTo(15)); } @Test public void testShouldGetScale() throws SQLException { - collector.checkThat(metadata.getScale(1), equalTo(0)); - collector.checkThat(metadata.getScale(2), equalTo(0)); - collector.checkThat(metadata.getScale(3), equalTo(20)); + assertThat(metadata.getScale(1), equalTo(0)); + assertThat(metadata.getScale(2), equalTo(0)); + assertThat(metadata.getScale(3), equalTo(20)); } @Test public void testShouldGetCatalogName() throws SQLException { - collector.checkThat(metadata.getCatalogName(1), equalTo("CATALOG_NAME_1")); - collector.checkThat(metadata.getCatalogName(2), equalTo("CATALOG_NAME_2")); - collector.checkThat(metadata.getCatalogName(3), equalTo("CATALOG_NAME_3")); + assertThat(metadata.getCatalogName(1), equalTo("CATALOG_NAME_1")); + assertThat(metadata.getCatalogName(2), equalTo("CATALOG_NAME_2")); + assertThat(metadata.getCatalogName(3), equalTo("CATALOG_NAME_3")); } @Test public void testShouldGetSchemaName() throws SQLException { - collector.checkThat(metadata.getSchemaName(1), equalTo("SCHEMA_NAME_1")); - collector.checkThat(metadata.getSchemaName(2), equalTo("SCHEMA_NAME_2")); - collector.checkThat(metadata.getSchemaName(3), equalTo("SCHEMA_NAME_3")); + assertThat(metadata.getSchemaName(1), equalTo("SCHEMA_NAME_1")); + assertThat(metadata.getSchemaName(2), equalTo("SCHEMA_NAME_2")); + assertThat(metadata.getSchemaName(3), equalTo("SCHEMA_NAME_3")); } @Test public void testShouldGetTableName() throws SQLException { - collector.checkThat(metadata.getTableName(1), equalTo("TABLE_NAME_1")); - collector.checkThat(metadata.getTableName(2), equalTo("TABLE_NAME_2")); - collector.checkThat(metadata.getTableName(3), equalTo("TABLE_NAME_3")); + assertThat(metadata.getTableName(1), equalTo("TABLE_NAME_1")); + assertThat(metadata.getTableName(2), equalTo("TABLE_NAME_2")); + assertThat(metadata.getTableName(3), equalTo("TABLE_NAME_3")); } @Test public void testShouldIsAutoIncrement() throws SQLException { - collector.checkThat(metadata.isAutoIncrement(1), equalTo(true)); - collector.checkThat(metadata.isAutoIncrement(2), equalTo(false)); - collector.checkThat(metadata.isAutoIncrement(3), equalTo(false)); + assertThat(metadata.isAutoIncrement(1), equalTo(true)); + assertThat(metadata.isAutoIncrement(2), equalTo(false)); + assertThat(metadata.isAutoIncrement(3), equalTo(false)); } @Test public void testShouldIsCaseSensitive() throws SQLException { - collector.checkThat(metadata.isCaseSensitive(1), equalTo(false)); - collector.checkThat(metadata.isCaseSensitive(2), equalTo(true)); - collector.checkThat(metadata.isCaseSensitive(3), equalTo(false)); + assertThat(metadata.isCaseSensitive(1), equalTo(false)); + assertThat(metadata.isCaseSensitive(2), equalTo(true)); + assertThat(metadata.isCaseSensitive(3), equalTo(false)); } @Test public void testShouldIsReadonly() throws SQLException { - collector.checkThat(metadata.isReadOnly(1), equalTo(true)); - collector.checkThat(metadata.isReadOnly(2), equalTo(false)); - collector.checkThat(metadata.isReadOnly(3), equalTo(false)); + assertThat(metadata.isReadOnly(1), equalTo(true)); + assertThat(metadata.isReadOnly(2), equalTo(false)); + assertThat(metadata.isReadOnly(3), equalTo(false)); } @Test public void testShouldIsSearchable() throws SQLException { - collector.checkThat(metadata.isSearchable(1), equalTo(true)); - collector.checkThat(metadata.isSearchable(2), equalTo(true)); - collector.checkThat(metadata.isSearchable(3), equalTo(true)); + assertThat(metadata.isSearchable(1), equalTo(true)); + assertThat(metadata.isSearchable(2), equalTo(true)); + assertThat(metadata.isSearchable(3), equalTo(true)); } /** * Test if {@link ResultSetMetaData#getColumnTypeName(int)} passing an column index that does not * exist. - * - * @throws SQLException in case of error. */ - @Test(expected = IndexOutOfBoundsException.class) - public void testShouldGetColumnTypesFromOutOfBoundIndex() throws SQLException { - metadata.getColumnType(4); - - Assert.fail(); + @Test + public void testShouldGetColumnTypesFromOutOfBoundIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> metadata.getColumnType(4)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java index 1b4224cb3897c..a8d04dfc83ac0 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ResultSetTest.java @@ -24,10 +24,13 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableSet; import java.nio.charset.StandardCharsets; @@ -63,31 +66,27 @@ import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.jupiter.api.Assertions; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ResultSetTest { private static final Random RANDOM = new Random(10); - @ClassRule - public static final FlightServerTestRule SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(CoreMockedSqlProducers.getLegacyProducer()); + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension( + CoreMockedSqlProducers.getLegacyProducer()); private static Connection connection; - @Rule public final ErrorCollector collector = new ErrorCollector(); - - @BeforeClass + @BeforeAll public static void setup() throws SQLException { - connection = SERVER_TEST_RULE.getConnection(false); + connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false); } - @AfterClass + @AfterAll public static void tearDown() throws SQLException { connection.close(); } @@ -109,7 +108,7 @@ public void testShouldRunSelectQuery() throws Exception { try (Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD)) { - CoreMockedSqlProducers.assertLegacyRegularSqlResultSet(resultSet, collector); + CoreMockedSqlProducers.assertLegacyRegularSqlResultSet(resultSet); } } @@ -140,7 +139,7 @@ public void testShouldRunSelectQuerySettingMaxRowLimit() throws Exception { final int maxRowsLimit = 3; statement.setMaxRows(maxRowsLimit); - collector.checkThat(statement.getMaxRows(), is(maxRowsLimit)); + assertThat(statement.getMaxRows(), is(maxRowsLimit)); int count = 0; int columns = 6; @@ -148,10 +147,10 @@ public void testShouldRunSelectQuerySettingMaxRowLimit() throws Exception { for (int column = 1; column <= columns; column++) { resultSet.getObject(column); } - collector.checkThat("Test Name #" + count, is(resultSet.getString(2))); + assertThat("Test Name #" + count, is(resultSet.getString(2))); } - collector.checkThat(maxRowsLimit, is(count)); + assertThat(maxRowsLimit, is(count)); } } @@ -160,13 +159,16 @@ public void testShouldRunSelectQuerySettingMaxRowLimit() throws Exception { * * @throws Exception If the connection fails to be established. */ - @Test(expected = SQLException.class) - public void testShouldThrowExceptionUponAttemptingToExecuteAnInvalidSelectQuery() - throws Exception { - try (Statement statement = connection.createStatement(); - ResultSet result = statement.executeQuery("SELECT * FROM SHOULD-FAIL")) { - fail(); - } + @Test + public void testShouldThrowExceptionUponAttemptingToExecuteAnInvalidSelectQuery() { + assertThrows( + SQLException.class, + () -> { + try (Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM SHOULD-FAIL")) { + fail(); + } + }); } /** @@ -183,7 +185,7 @@ public void testShouldRunSelectQuerySettingLargeMaxRowLimit() throws Exception { final long maxRowsLimit = 3; statement.setLargeMaxRows(maxRowsLimit); - collector.checkThat(statement.getLargeMaxRows(), is(maxRowsLimit)); + assertThat(statement.getLargeMaxRows(), is(maxRowsLimit)); int count = 0; int columns = resultSet.getMetaData().getColumnCount(); @@ -209,7 +211,7 @@ public void testColumnCountShouldRemainConsistentForResultSetThroughoutEntireDur counts.add(resultSet.getMetaData().getColumnCount()); } } - collector.checkThat(counts, is(ImmutableSet.of(6))); + assertThat(counts, is(ImmutableSet.of(6))); } /** @@ -228,7 +230,7 @@ public void testShouldCloseStatementWhenIsCloseOnCompletion() throws Exception { resultSetNextUntilDone(resultSet); - collector.checkThat(statement.isClosed(), is(true)); + assertThat(statement.isClosed(), is(true)); } } @@ -251,7 +253,7 @@ public void testShouldCloseStatementWhenIsCloseOnCompletionWithMaxRowsLimit() th resultSetNextUntilDone(resultSet); - collector.checkThat(statement.isClosed(), is(true)); + assertThat(statement.isClosed(), is(true)); } } @@ -272,10 +274,10 @@ public void testShouldNotCloseStatementWhenIsNotCloseOnCompletionWithMaxRowsLimi final long maxRowsLimit = 3; statement.setLargeMaxRows(maxRowsLimit); - collector.checkThat(statement.isClosed(), is(false)); + assertThat(statement.isClosed(), is(false)); resultSetNextUntilDone(resultSet); - collector.checkThat(resultSet.isClosed(), is(false)); - collector.checkThat(resultSet, is(instanceOf(ArrowFlightJdbcFlightStreamResultSet.class))); + assertThat(resultSet.isClosed(), is(false)); + assertThat(resultSet, is(instanceOf(ArrowFlightJdbcFlightStreamResultSet.class))); } } @@ -285,14 +287,14 @@ public void testShouldCancelQueryUponCancelAfterQueryingResultSet() throws SQLEx final ResultSet resultSet = statement.executeQuery(CoreMockedSqlProducers.LEGACY_REGULAR_SQL_CMD)) { final int column = RANDOM.nextInt(resultSet.getMetaData().getColumnCount()) + 1; - collector.checkThat(resultSet.isClosed(), is(false)); - collector.checkThat(resultSet.next(), is(true)); - collector.checkSucceeds(() -> resultSet.getObject(column)); + assertThat(resultSet.isClosed(), is(false)); + assertThat(resultSet.next(), is(true)); + assertDoesNotThrow(() -> resultSet.getObject(column)); statement.cancel(); // Should reset `ResultSet`; keep both `ResultSet` and `Connection` open. - collector.checkThat(statement.isClosed(), is(false)); - collector.checkThat(resultSet.isClosed(), is(false)); - collector.checkThat(resultSet.getMetaData().getColumnCount(), is(0)); + assertThat(statement.isClosed(), is(false)); + assertThat(resultSet.isClosed(), is(false)); + assertThat(resultSet.getMetaData().getColumnCount(), is(0)); } } @@ -322,7 +324,7 @@ public void testShouldInterruptFlightStreamsIfQueryIsCancelledMidQuerying() thread.start(); statement.cancel(); thread.join(); - collector.checkThat( + assertThat( exceptions.stream() .map(Exception::getMessage) .map(StringBuilder::new) @@ -355,7 +357,7 @@ public void testShouldInterruptFlightStreamsIfQueryIsCancelledMidQuerying() Thread.sleep(5000); // Let the other thread attempt to retrieve results. statement.cancel(); thread.join(); - collector.checkThat( + assertThat( exceptions.stream() .map(Exception::getMessage) .map(StringBuilder::new) @@ -385,8 +387,8 @@ public void testShouldInterruptFlightStreamsIfQueryTimeoutIsOver() throws SQLExc } final Throwable comparisonCause = exceptions.stream().findFirst().orElseThrow(RuntimeException::new).getCause().getCause(); - collector.checkThat(comparisonCause, is(instanceOf(SQLTimeoutException.class))); - collector.checkThat( + assertThat(comparisonCause, is(instanceOf(SQLTimeoutException.class))); + assertThat( comparisonCause.getMessage(), is(format("Query timed out after %d %s", timeoutValue, timeoutUnit))); } @@ -399,7 +401,7 @@ public void testFlightStreamsQueryShouldNotTimeout() throws SQLException { try (Statement statement = connection.createStatement()) { statement.setQueryTimeout(timeoutValue); try (ResultSet resultSet = statement.executeQuery(query)) { - CoreMockedSqlProducers.assertLegacyRegularSqlResultSet(resultSet, collector); + CoreMockedSqlProducers.assertLegacyRegularSqlResultSet(resultSet); } } } @@ -501,16 +503,16 @@ public void testPartitionedFlightServerIgnoreFailure() throws Exception { rootServer.getLocation().getUri().getHost(), rootServer.getPort())); Statement newStatement = newConnection.createStatement()) { final SQLException e = - Assertions.assertThrows( + assertThrows( SQLException.class, () -> { ResultSet result = newStatement.executeQuery("Select partitioned_data"); while (result.next()) {} }); final Throwable cause = e.getCause(); - Assertions.assertTrue(cause instanceof FlightRuntimeException); + assertTrue(cause instanceof FlightRuntimeException); final FlightRuntimeException fre = (FlightRuntimeException) cause; - Assertions.assertEquals(FlightStatusCode.UNAVAILABLE, fre.status().code()); + assertEquals(FlightStatusCode.UNAVAILABLE, fre.status().code()); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/TokenAuthenticationTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/TokenAuthenticationTest.java index 8399bb6cb4546..1dfb1efcf16ce 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/TokenAuthenticationTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/TokenAuthenticationTest.java @@ -16,45 +16,46 @@ */ package org.apache.arrow.driver.jdbc; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.sql.Connection; import java.sql.SQLException; import org.apache.arrow.driver.jdbc.authentication.TokenAuthentication; import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer; import org.apache.arrow.util.AutoCloseables; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class TokenAuthenticationTest { private static final MockFlightSqlProducer FLIGHT_SQL_PRODUCER = new MockFlightSqlProducer(); - @ClassRule public static FlightServerTestRule FLIGHT_SERVER_TEST_RULE; + @RegisterExtension public static FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION; static { - FLIGHT_SERVER_TEST_RULE = - new FlightServerTestRule.Builder() + FLIGHT_SERVER_TEST_EXTENSION = + new FlightServerTestExtension.Builder() .authentication(new TokenAuthentication.Builder().token("1234").build()) .producer(FLIGHT_SQL_PRODUCER) .build(); } - @AfterClass + @AfterAll public static void tearDownAfterClass() { AutoCloseables.closeNoChecked(FLIGHT_SQL_PRODUCER); } - @Test(expected = SQLException.class) + @Test public void connectUsingTokenAuthenticationShouldFail() throws SQLException { - try (Connection ignored = FLIGHT_SERVER_TEST_RULE.getConnection(false, "invalid")) { - Assert.fail(); - } + assertThrows( + SQLException.class, () -> FLIGHT_SERVER_TEST_EXTENSION.getConnection(false, "invalid")); } @Test public void connectUsingTokenAuthenticationShouldSuccess() throws SQLException { - try (Connection connection = FLIGHT_SERVER_TEST_RULE.getConnection(false, "1234")) { - Assert.assertFalse(connection.isClosed()); + try (Connection connection = FLIGHT_SERVER_TEST_EXTENSION.getConnection(false, "1234")) { + assertFalse(connection.isClosed()); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorFactoryTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorFactoryTest.java index 965317695616e..b56bf3c63d8e3 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorFactoryTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorFactoryTest.java @@ -16,6 +16,8 @@ */ package org.apache.arrow.driver.jdbc.accessor; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.function.IntSupplier; import org.apache.arrow.driver.jdbc.accessor.impl.binary.ArrowFlightJdbcBinaryVectorAccessor; import org.apache.arrow.driver.jdbc.accessor.impl.calendar.ArrowFlightJdbcDateVectorAccessor; @@ -36,7 +38,7 @@ import org.apache.arrow.driver.jdbc.accessor.impl.numeric.ArrowFlightJdbcFloat4VectorAccessor; import org.apache.arrow.driver.jdbc.accessor.impl.numeric.ArrowFlightJdbcFloat8VectorAccessor; import org.apache.arrow.driver.jdbc.accessor.impl.text.ArrowFlightJdbcVarCharVectorAccessor; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.IntervalDayVector; import org.apache.arrow.vector.IntervalMonthDayNanoVector; @@ -51,290 +53,290 @@ import org.apache.arrow.vector.types.TimeUnit; import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.FieldType; -import org.junit.Assert; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcAccessorFactoryTest { public static final IntSupplier GET_CURRENT_ROW = () -> 0; - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); @Test public void createAccessorForUInt1Vector() { - try (ValueVector valueVector = rootAllocatorTestRule.createUInt1Vector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createUInt1Vector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForUInt2Vector() { - try (ValueVector valueVector = rootAllocatorTestRule.createUInt2Vector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createUInt2Vector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForUInt4Vector() { - try (ValueVector valueVector = rootAllocatorTestRule.createUInt4Vector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createUInt4Vector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForUInt8Vector() { - try (ValueVector valueVector = rootAllocatorTestRule.createUInt8Vector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createUInt8Vector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForTinyIntVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createTinyIntVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createTinyIntVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForSmallIntVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createSmallIntVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createSmallIntVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForIntVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createIntVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createIntVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForBigIntVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createBigIntVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createBigIntVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBaseIntVectorAccessor); } } @Test public void createAccessorForFloat4Vector() { - try (ValueVector valueVector = rootAllocatorTestRule.createFloat4Vector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createFloat4Vector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcFloat4VectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcFloat4VectorAccessor); } } @Test public void createAccessorForFloat8Vector() { - try (ValueVector valueVector = rootAllocatorTestRule.createFloat8Vector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createFloat8Vector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcFloat8VectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcFloat8VectorAccessor); } } @Test public void createAccessorForBitVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createBitVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createBitVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBitVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBitVectorAccessor); } } @Test public void createAccessorForDecimalVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createDecimalVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createDecimalVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcDecimalVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcDecimalVectorAccessor); } } @Test public void createAccessorForDecimal256Vector() { - try (ValueVector valueVector = rootAllocatorTestRule.createDecimal256Vector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createDecimal256Vector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcDecimalVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcDecimalVectorAccessor); } } @Test public void createAccessorForVarBinaryVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createVarBinaryVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createVarBinaryVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBinaryVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBinaryVectorAccessor); } } @Test public void createAccessorForLargeVarBinaryVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createLargeVarBinaryVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createLargeVarBinaryVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBinaryVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBinaryVectorAccessor); } } @Test public void createAccessorForFixedSizeBinaryVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createFixedSizeBinaryVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createFixedSizeBinaryVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcBinaryVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcBinaryVectorAccessor); } } @Test public void createAccessorForTimeStampVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createTimeStampMilliVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createTimeStampMilliVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcTimeStampVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcTimeStampVectorAccessor); } } @Test public void createAccessorForTimeNanoVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createTimeNanoVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createTimeNanoVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); } } @Test public void createAccessorForTimeMicroVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createTimeMicroVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createTimeMicroVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); } } @Test public void createAccessorForTimeMilliVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createTimeMilliVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createTimeMilliVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); } } @Test public void createAccessorForTimeSecVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createTimeSecVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createTimeSecVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcTimeVectorAccessor); } } @Test public void createAccessorForDateDayVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createDateDayVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createDateDayVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcDateVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcDateVectorAccessor); } } @Test public void createAccessorForDateMilliVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createDateMilliVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createDateMilliVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcDateVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcDateVectorAccessor); } } @Test public void createAccessorForVarCharVector() { try (ValueVector valueVector = - new VarCharVector("", rootAllocatorTestRule.getRootAllocator())) { + new VarCharVector("", rootAllocatorTestExtension.getRootAllocator())) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcVarCharVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcVarCharVectorAccessor); } } @Test public void createAccessorForLargeVarCharVector() { try (ValueVector valueVector = - new LargeVarCharVector("", rootAllocatorTestRule.getRootAllocator())) { + new LargeVarCharVector("", rootAllocatorTestExtension.getRootAllocator())) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcVarCharVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcVarCharVectorAccessor); } } @@ -344,129 +346,129 @@ public void createAccessorForDurationVector() { new DurationVector( "", new FieldType(true, new ArrowType.Duration(TimeUnit.MILLISECOND), null), - rootAllocatorTestRule.getRootAllocator())) { + rootAllocatorTestExtension.getRootAllocator())) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcDurationVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcDurationVectorAccessor); } } @Test public void createAccessorForIntervalDayVector() { try (ValueVector valueVector = - new IntervalDayVector("", rootAllocatorTestRule.getRootAllocator())) { + new IntervalDayVector("", rootAllocatorTestExtension.getRootAllocator())) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcIntervalVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcIntervalVectorAccessor); } } @Test public void createAccessorForIntervalYearVector() { try (ValueVector valueVector = - new IntervalYearVector("", rootAllocatorTestRule.getRootAllocator())) { + new IntervalYearVector("", rootAllocatorTestExtension.getRootAllocator())) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcIntervalVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcIntervalVectorAccessor); } } @Test public void createAccessorForIntervalMonthDayNanoVector() { try (ValueVector valueVector = - new IntervalMonthDayNanoVector("", rootAllocatorTestRule.getRootAllocator())) { + new IntervalMonthDayNanoVector("", rootAllocatorTestExtension.getRootAllocator())) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcIntervalVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcIntervalVectorAccessor); } } @Test public void createAccessorForUnionVector() { try (ValueVector valueVector = - new UnionVector("", rootAllocatorTestRule.getRootAllocator(), null, null)) { + new UnionVector("", rootAllocatorTestExtension.getRootAllocator(), null, null)) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcUnionVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcUnionVectorAccessor); } } @Test public void createAccessorForDenseUnionVector() { try (ValueVector valueVector = - new DenseUnionVector("", rootAllocatorTestRule.getRootAllocator(), null, null)) { + new DenseUnionVector("", rootAllocatorTestExtension.getRootAllocator(), null, null)) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcDenseUnionVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcDenseUnionVectorAccessor); } } @Test public void createAccessorForStructVector() { try (ValueVector valueVector = - StructVector.empty("", rootAllocatorTestRule.getRootAllocator())) { + StructVector.empty("", rootAllocatorTestExtension.getRootAllocator())) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcStructVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcStructVectorAccessor); } } @Test public void createAccessorForListVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createListVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createListVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcListVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcListVectorAccessor); } } @Test public void createAccessorForLargeListVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createLargeListVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createLargeListVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcLargeListVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcLargeListVectorAccessor); } } @Test public void createAccessorForFixedSizeListVector() { - try (ValueVector valueVector = rootAllocatorTestRule.createFixedSizeListVector()) { + try (ValueVector valueVector = rootAllocatorTestExtension.createFixedSizeListVector()) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcFixedSizeListVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcFixedSizeListVectorAccessor); } } @Test public void createAccessorForMapVector() { try (ValueVector valueVector = - MapVector.empty("", rootAllocatorTestRule.getRootAllocator(), true)) { + MapVector.empty("", rootAllocatorTestExtension.getRootAllocator(), true)) { ArrowFlightJdbcAccessor accessor = ArrowFlightJdbcAccessorFactory.createAccessor( valueVector, GET_CURRENT_ROW, (boolean wasNull) -> {}); - Assert.assertTrue(accessor instanceof ArrowFlightJdbcMapVectorAccessor); + assertTrue(accessor instanceof ArrowFlightJdbcMapVectorAccessor); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorTest.java index 50c413ec4ec08..6a101e90d3a27 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/ArrowFlightJdbcAccessorTest.java @@ -16,6 +16,9 @@ */ package org.apache.arrow.driver.jdbc.accessor; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -24,13 +27,12 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ArrowFlightJdbcAccessorTest { static class MockedArrowFlightJdbcAccessor extends ArrowFlightJdbcAccessor { @@ -54,7 +56,7 @@ public void testShouldGetObjectWithByteClassReturnGetByte() throws SQLException when(accessor.getObject(Byte.class)).thenCallRealMethod(); - Assert.assertEquals(accessor.getObject(Byte.class), (Object) expected); + assertEquals(accessor.getObject(Byte.class), (Object) expected); verify(accessor).getByte(); } @@ -65,7 +67,7 @@ public void testShouldGetObjectWithShortClassReturnGetShort() throws SQLExceptio when(accessor.getObject(Short.class)).thenCallRealMethod(); - Assert.assertEquals(accessor.getObject(Short.class), (Object) expected); + assertEquals(accessor.getObject(Short.class), (Object) expected); verify(accessor).getShort(); } @@ -76,7 +78,7 @@ public void testShouldGetObjectWithIntegerClassReturnGetInt() throws SQLExceptio when(accessor.getObject(Integer.class)).thenCallRealMethod(); - Assert.assertEquals(accessor.getObject(Integer.class), (Object) expected); + assertEquals(accessor.getObject(Integer.class), (Object) expected); verify(accessor).getInt(); } @@ -87,7 +89,7 @@ public void testShouldGetObjectWithLongClassReturnGetLong() throws SQLException when(accessor.getObject(Long.class)).thenCallRealMethod(); - Assert.assertEquals(accessor.getObject(Long.class), (Object) expected); + assertEquals(accessor.getObject(Long.class), (Object) expected); verify(accessor).getLong(); } @@ -98,7 +100,7 @@ public void testShouldGetObjectWithFloatClassReturnGetFloat() throws SQLExceptio when(accessor.getObject(Float.class)).thenCallRealMethod(); - Assert.assertEquals(accessor.getObject(Float.class), (Object) expected); + assertEquals(accessor.getObject(Float.class), (Object) expected); verify(accessor).getFloat(); } @@ -109,7 +111,7 @@ public void testShouldGetObjectWithDoubleClassReturnGetDouble() throws SQLExcept when(accessor.getObject(Double.class)).thenCallRealMethod(); - Assert.assertEquals(accessor.getObject(Double.class), (Object) expected); + assertEquals(accessor.getObject(Double.class), (Object) expected); verify(accessor).getDouble(); } @@ -119,7 +121,7 @@ public void testShouldGetObjectWithBooleanClassReturnGetBoolean() throws SQLExce when(accessor.getObject(Boolean.class)).thenCallRealMethod(); - Assert.assertEquals(true, accessor.getObject(Boolean.class)); + assertEquals(true, accessor.getObject(Boolean.class)); verify(accessor).getBoolean(); } @@ -130,7 +132,7 @@ public void testShouldGetObjectWithBigDecimalClassReturnGetBigDecimal() throws S when(accessor.getObject(BigDecimal.class)).thenCallRealMethod(); - Assert.assertEquals(expected, accessor.getObject(BigDecimal.class)); + assertEquals(expected, accessor.getObject(BigDecimal.class)); verify(accessor).getBigDecimal(); } @@ -141,7 +143,7 @@ public void testShouldGetObjectWithStringClassReturnGetString() throws SQLExcept when(accessor.getObject(String.class)).thenCallRealMethod(); - Assert.assertEquals(expected, accessor.getObject(String.class)); + assertEquals(expected, accessor.getObject(String.class)); verify(accessor).getString(); } @@ -152,7 +154,7 @@ public void testShouldGetObjectWithByteArrayClassReturnGetBytes() throws SQLExce when(accessor.getObject(byte[].class)).thenCallRealMethod(); - Assert.assertArrayEquals(accessor.getObject(byte[].class), expected); + assertArrayEquals(accessor.getObject(byte[].class), expected); verify(accessor).getBytes(); } @@ -163,7 +165,7 @@ public void testShouldGetObjectWithObjectClassReturnGetObject() throws SQLExcept when(accessor.getObject(Object.class)).thenCallRealMethod(); - Assert.assertEquals(expected, accessor.getObject(Object.class)); + assertEquals(expected, accessor.getObject(Object.class)); verify(accessor).getObject(); } @@ -177,178 +179,178 @@ public void testShouldGetObjectWithAccessorsObjectClassReturnGetObject() throws verify(accessor).getObject(objectClass); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetBoolean() throws SQLException { when(accessor.getBoolean()).thenCallRealMethod(); - accessor.getBoolean(); + assertThrows(SQLException.class, () -> accessor.getBoolean()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetByte() throws SQLException { when(accessor.getByte()).thenCallRealMethod(); - accessor.getByte(); + assertThrows(SQLException.class, () -> accessor.getByte()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetShort() throws SQLException { when(accessor.getShort()).thenCallRealMethod(); - accessor.getShort(); + assertThrows(SQLException.class, () -> accessor.getShort()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetInt() throws SQLException { when(accessor.getInt()).thenCallRealMethod(); - accessor.getInt(); + assertThrows(SQLException.class, () -> accessor.getInt()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetLong() throws SQLException { when(accessor.getLong()).thenCallRealMethod(); - accessor.getLong(); + assertThrows(SQLException.class, () -> accessor.getLong()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetFloat() throws SQLException { when(accessor.getFloat()).thenCallRealMethod(); - accessor.getFloat(); + assertThrows(SQLException.class, () -> accessor.getFloat()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetDouble() throws SQLException { when(accessor.getDouble()).thenCallRealMethod(); - accessor.getDouble(); + assertThrows(SQLException.class, () -> accessor.getDouble()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetBigDecimal() throws SQLException { when(accessor.getBigDecimal()).thenCallRealMethod(); - accessor.getBigDecimal(); + assertThrows(SQLException.class, () -> accessor.getBigDecimal()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetBytes() throws SQLException { when(accessor.getBytes()).thenCallRealMethod(); - accessor.getBytes(); + assertThrows(SQLException.class, () -> accessor.getBytes()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetAsciiStream() throws SQLException { when(accessor.getAsciiStream()).thenCallRealMethod(); - accessor.getAsciiStream(); + assertThrows(SQLException.class, () -> accessor.getAsciiStream()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetUnicodeStream() throws SQLException { when(accessor.getUnicodeStream()).thenCallRealMethod(); - accessor.getUnicodeStream(); + assertThrows(SQLException.class, () -> accessor.getUnicodeStream()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetBinaryStream() throws SQLException { when(accessor.getBinaryStream()).thenCallRealMethod(); - accessor.getBinaryStream(); + assertThrows(SQLException.class, () -> accessor.getBinaryStream()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetObject() throws SQLException { when(accessor.getObject()).thenCallRealMethod(); - accessor.getObject(); + assertThrows(SQLException.class, () -> accessor.getObject()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetObjectMap() throws SQLException { Map> map = new HashMap<>(); when(accessor.getObject(map)).thenCallRealMethod(); - accessor.getObject(map); + assertThrows(SQLException.class, () -> accessor.getObject(map)); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetCharacterStream() throws SQLException { when(accessor.getCharacterStream()).thenCallRealMethod(); - accessor.getCharacterStream(); + assertThrows(SQLException.class, () -> accessor.getCharacterStream()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetRef() throws SQLException { when(accessor.getRef()).thenCallRealMethod(); - accessor.getRef(); + assertThrows(SQLException.class, () -> accessor.getRef()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetBlob() throws SQLException { when(accessor.getBlob()).thenCallRealMethod(); - accessor.getBlob(); + assertThrows(SQLException.class, () -> accessor.getBlob()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetClob() throws SQLException { when(accessor.getClob()).thenCallRealMethod(); - accessor.getClob(); + assertThrows(SQLException.class, () -> accessor.getClob()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetArray() throws SQLException { when(accessor.getArray()).thenCallRealMethod(); - accessor.getArray(); + assertThrows(SQLException.class, () -> accessor.getArray()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetStruct() throws SQLException { when(accessor.getStruct()).thenCallRealMethod(); - accessor.getStruct(); + assertThrows(SQLException.class, () -> accessor.getStruct()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetURL() throws SQLException { when(accessor.getURL()).thenCallRealMethod(); - accessor.getURL(); + assertThrows(SQLException.class, () -> accessor.getURL()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetNClob() throws SQLException { when(accessor.getNClob()).thenCallRealMethod(); - accessor.getNClob(); + assertThrows(SQLException.class, () -> accessor.getNClob()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetSQLXML() throws SQLException { when(accessor.getSQLXML()).thenCallRealMethod(); - accessor.getSQLXML(); + assertThrows(SQLException.class, () -> accessor.getSQLXML()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetNString() throws SQLException { when(accessor.getNString()).thenCallRealMethod(); - accessor.getNString(); + assertThrows(SQLException.class, () -> accessor.getNString()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetNCharacterStream() throws SQLException { when(accessor.getNCharacterStream()).thenCallRealMethod(); - accessor.getNCharacterStream(); + assertThrows(SQLException.class, () -> accessor.getNCharacterStream()); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetDate() throws SQLException { when(accessor.getDate(null)).thenCallRealMethod(); - accessor.getDate(null); + assertThrows(SQLException.class, () -> accessor.getDate(null)); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetTime() throws SQLException { when(accessor.getTime(null)).thenCallRealMethod(); - accessor.getTime(null); + assertThrows(SQLException.class, () -> accessor.getTime(null)); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetTimestamp() throws SQLException { when(accessor.getTimestamp(null)).thenCallRealMethod(); - accessor.getTimestamp(null); + assertThrows(SQLException.class, () -> accessor.getTimestamp(null)); } - @Test(expected = SQLException.class) + @Test public void testShouldFailToGetBigDecimalWithValue() throws SQLException { when(accessor.getBigDecimal(0)).thenCallRealMethod(); - accessor.getBigDecimal(0); + assertThrows(SQLException.class, () -> accessor.getBigDecimal(0)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/ArrowFlightJdbcNullVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/ArrowFlightJdbcNullVectorAccessorTest.java index 5acab95500c9f..2db957badf02d 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/ArrowFlightJdbcNullVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/ArrowFlightJdbcNullVectorAccessorTest.java @@ -16,8 +16,10 @@ */ package org.apache.arrow.driver.jdbc.accessor.impl; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; public class ArrowFlightJdbcNullVectorAccessorTest { @@ -26,11 +28,11 @@ public class ArrowFlightJdbcNullVectorAccessorTest { @Test public void testShouldWasNullReturnTrue() { - Assert.assertTrue(accessor.wasNull()); + assertTrue(accessor.wasNull()); } @Test public void testShouldGetObjectReturnNull() { - Assert.assertNull(accessor.getObject()); + assertNull(accessor.getObject()); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/binary/ArrowFlightJdbcBinaryVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/binary/ArrowFlightJdbcBinaryVectorAccessorTest.java index f787bc0e08aab..f445fb15a46ae 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/binary/ArrowFlightJdbcBinaryVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/binary/ArrowFlightJdbcBinaryVectorAccessorTest.java @@ -19,40 +19,34 @@ import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.io.InputStream; import java.io.Reader; -import java.util.Arrays; -import java.util.Collection; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.FixedSizeBinaryVector; import org.apache.arrow.vector.LargeVarBinaryVector; import org.apache.arrow.vector.ValueVector; import org.apache.arrow.vector.VarBinaryVector; import org.apache.commons.io.IOUtils; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class ArrowFlightJdbcBinaryVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private ValueVector vector; - private final Supplier vectorSupplier; private final AccessorTestUtils.AccessorSupplier accessorSupplier = @@ -73,52 +67,45 @@ public class ArrowFlightJdbcBinaryVectorAccessorTest { }; private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); - - @Parameterized.Parameters(name = "{1}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - { - (Supplier) () -> rootAllocatorTestRule.createVarBinaryVector(), - "VarBinaryVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createLargeVarBinaryVector(), - "LargeVarBinaryVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createFixedSizeBinaryVector(), - "FixedSizeBinaryVector" - }, - }); - } - - public ArrowFlightJdbcBinaryVectorAccessorTest( - Supplier vectorSupplier, String vectorType) { - this.vectorSupplier = vectorSupplier; + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); + + public static Stream data() { + return Stream.of( + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createVarBinaryVector(), + "VarBinaryVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createLargeVarBinaryVector(), + "LargeVarBinaryVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createFixedSizeBinaryVector(), + "FixedSizeBinaryVector")); } - @Before - public void setup() { + public void setup(Supplier vectorSupplier) { this.vector = vectorSupplier.get(); } - @After + @AfterEach public void tearDown() { this.vector.close(); } - @Test - public void testShouldGetStringReturnExpectedString() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringReturnExpectedString(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBinaryVectorAccessor::getString, (accessor) -> is(new String(accessor.getBytes(), UTF_8))); } - @Test - public void testShouldGetStringReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringReturnNull(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); vector.reset(); vector.setValueCount(5); @@ -126,8 +113,11 @@ public void testShouldGetStringReturnNull() throws Exception { vector, ArrowFlightJdbcBinaryVectorAccessor::getString, CoreMatchers.nullValue()); } - @Test - public void testShouldGetBytesReturnExpectedByteArray() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBytesReturnExpectedByteArray(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBinaryVectorAccessor::getBytes, @@ -143,119 +133,146 @@ public void testShouldGetBytesReturnExpectedByteArray() throws Exception { }); } - @Test - public void testShouldGetBytesReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBytesReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.reset(); vector.setValueCount(5); ArrowFlightJdbcBinaryVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getBytes(), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getBytes(), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetObjectReturnAsGetBytes() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectReturnAsGetBytes(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBinaryVectorAccessor::getObject, (accessor) -> is(accessor.getBytes())); } - @Test - public void testShouldGetObjectReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.reset(); vector.setValueCount(5); ArrowFlightJdbcBinaryVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getObject(), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getObject(), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetUnicodeStreamReturnCorrectInputStream() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetUnicodeStreamReturnCorrectInputStream( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { InputStream inputStream = accessor.getUnicodeStream(); String actualString = IOUtils.toString(inputStream, UTF_8); - collector.checkThat(accessor.wasNull(), is(false)); - collector.checkThat(actualString, is(accessor.getString())); + assertThat(accessor.wasNull(), is(false)); + assertThat(actualString, is(accessor.getString())); }); } - @Test - public void testShouldGetUnicodeStreamReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetUnicodeStreamReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.reset(); vector.setValueCount(5); ArrowFlightJdbcBinaryVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getUnicodeStream(), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getUnicodeStream(), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetAsciiStreamReturnCorrectInputStream() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetAsciiStreamReturnCorrectInputStream(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { InputStream inputStream = accessor.getAsciiStream(); String actualString = IOUtils.toString(inputStream, US_ASCII); - collector.checkThat(accessor.wasNull(), is(false)); - collector.checkThat(actualString, is(accessor.getString())); + assertThat(accessor.wasNull(), is(false)); + assertThat(actualString, is(accessor.getString())); }); } - @Test - public void testShouldGetAsciiStreamReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetAsciiStreamReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.reset(); vector.setValueCount(5); ArrowFlightJdbcBinaryVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getAsciiStream(), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getAsciiStream(), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetBinaryStreamReturnCurrentInputStream() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBinaryStreamReturnCurrentInputStream( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { InputStream inputStream = accessor.getBinaryStream(); String actualString = IOUtils.toString(inputStream, UTF_8); - collector.checkThat(accessor.wasNull(), is(false)); - collector.checkThat(actualString, is(accessor.getString())); + assertThat(accessor.wasNull(), is(false)); + assertThat(actualString, is(accessor.getString())); }); } - @Test - public void testShouldGetBinaryStreamReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBinaryStreamReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.reset(); vector.setValueCount(5); ArrowFlightJdbcBinaryVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getBinaryStream(), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getBinaryStream(), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetCharacterStreamReturnCorrectReader() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetCharacterStreamReturnCorrectReader(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { Reader characterStream = accessor.getCharacterStream(); String actualString = IOUtils.toString(characterStream); - collector.checkThat(accessor.wasNull(), is(false)); - collector.checkThat(actualString, is(accessor.getString())); + assertThat(accessor.wasNull(), is(false)); + assertThat(actualString, is(accessor.getString())); }); } - @Test - public void testShouldGetCharacterStreamReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetCharacterStreamReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.reset(); vector.setValueCount(5); ArrowFlightJdbcBinaryVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getCharacterStream(), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getCharacterStream(), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDateVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDateVectorAccessorTest.java index 478a4eea0249f..3bbe3e1711124 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDateVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDateVectorAccessorTest.java @@ -20,46 +20,40 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Date; import java.sql.Timestamp; import java.time.LocalDateTime; -import java.util.Arrays; import java.util.Calendar; -import java.util.Collection; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.impl.text.ArrowFlightJdbcVarCharVectorAccessor; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.BaseFixedWidthVector; import org.apache.arrow.vector.DateDayVector; import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.util.Text; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + public class ArrowFlightJdbcDateVectorAccessorTest { public static final String AMERICA_VANCOUVER = "America/Vancouver"; - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private BaseFixedWidthVector vector; - private final Supplier vectorSupplier; private final AccessorTestUtils.AccessorSupplier accessorSupplier = @@ -75,56 +69,54 @@ public class ArrowFlightJdbcDateVectorAccessorTest { }; private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); - - @Parameterized.Parameters(name = "{1}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - { - (Supplier) () -> rootAllocatorTestRule.createDateDayVector(), - "DateDayVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createDateMilliVector(), - "DateMilliVector" - }, - }); - } - - public ArrowFlightJdbcDateVectorAccessorTest( - Supplier vectorSupplier, String vectorType) { - this.vectorSupplier = vectorSupplier; + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); + + public static Stream data() { + return Stream.of( + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createDateDayVector(), + "DateDayVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createDateMilliVector(), + "DateMilliVector")); } - @Before - public void setup() { + public void setup(Supplier vectorSupplier) { this.vector = vectorSupplier.get(); } - @After + @AfterEach public void tearDown() { this.vector.close(); } - @Test - public void testShouldGetTimestampReturnValidTimestampWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnValidTimestampWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getTimestamp(null), (accessor, currentRow) -> is(getTimestampForVector(currentRow))); } - @Test - public void testShouldGetObjectWithDateClassReturnValidDateWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectWithDateClassReturnValidDateWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getObject(Date.class), (accessor, currentRow) -> is(new Date(getTimestampForVector(currentRow).getTime()))); } - @Test - public void testShouldGetTimestampReturnValidTimestampWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnValidTimestampWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); TimeZone timeZone = TimeZone.getTimeZone(AMERICA_VANCOUVER); Calendar calendar = Calendar.getInstance(timeZone); @@ -136,29 +128,37 @@ public void testShouldGetTimestampReturnValidTimestampWithCalendar() throws Exce long offset = timeZone.getOffset(resultWithoutCalendar.getTime()); - collector.checkThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); + assertThat(accessor.wasNull(), is(false)); }); } - @Test - public void testShouldGetTimestampReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.setNull(0); ArrowFlightJdbcDateVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getTimestamp(null), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getTimestamp(null), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetDateReturnValidDateWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDateReturnValidDateWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getDate(null), (accessor, currentRow) -> is(new Date(getTimestampForVector(currentRow).getTime()))); } - @Test - public void testShouldGetDateReturnValidDateWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDateReturnValidDateWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); TimeZone timeZone = TimeZone.getTimeZone(AMERICA_VANCOUVER); Calendar calendar = Calendar.getInstance(timeZone); @@ -170,17 +170,19 @@ public void testShouldGetDateReturnValidDateWithCalendar() throws Exception { long offset = timeZone.getOffset(resultWithoutCalendar.getTime()); - collector.checkThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); + assertThat(accessor.wasNull(), is(false)); }); } - @Test - public void testShouldGetDateReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDateReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.setNull(0); ArrowFlightJdbcDateVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getDate(null), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getDate(null), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } private Timestamp getTimestampForVector(int currentRow) { @@ -198,25 +200,37 @@ private Timestamp getTimestampForVector(int currentRow) { return expectedTimestamp; } - @Test - public void testShouldGetObjectClass() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectClass(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDateVectorAccessor::getObjectClass, equalTo(Date.class)); } - @Test - public void testShouldGetStringBeConsistentWithVarCharAccessorWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringBeConsistentWithVarCharAccessorWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); assertGetStringIsConsistentWithVarCharAccessor(null); } - @Test - public void testShouldGetStringBeConsistentWithVarCharAccessorWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringBeConsistentWithVarCharAccessorWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(AMERICA_VANCOUVER)); assertGetStringIsConsistentWithVarCharAccessor(calendar); } - @Test - public void testValidateGetStringTimeZoneConsistency() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testValidateGetStringTimeZoneConsistency( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { @@ -228,13 +242,13 @@ public void testValidateGetStringTimeZoneConsistency() throws Exception { // Validate with UTC Date date = accessor.getDate(null); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); - collector.checkThat(date.toString(), is(string)); + assertThat(date.toString(), is(string)); // Validate with different TZ TimeZone.setDefault(TimeZone.getTimeZone(AMERICA_VANCOUVER)); - collector.checkThat(date.toString(), not(string)); + assertThat(date.toString(), not(string)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(accessor.wasNull(), is(false)); } finally { // Set default Tz back TimeZone.setDefault(defaultTz); @@ -244,7 +258,7 @@ public void testValidateGetStringTimeZoneConsistency() throws Exception { private void assertGetStringIsConsistentWithVarCharAccessor(Calendar calendar) throws Exception { try (VarCharVector varCharVector = - new VarCharVector("", rootAllocatorTestRule.getRootAllocator())) { + new VarCharVector("", rootAllocatorTestExtension.getRootAllocator())) { varCharVector.allocateNew(1); ArrowFlightJdbcVarCharVectorAccessor varCharVectorAccessor = new ArrowFlightJdbcVarCharVectorAccessor(varCharVector, () -> 0, (boolean wasNull) -> {}); @@ -259,8 +273,8 @@ private void assertGetStringIsConsistentWithVarCharAccessor(Calendar calendar) t Date dateFromVarChar = varCharVectorAccessor.getDate(calendar); Date date = accessor.getDate(calendar); - collector.checkThat(date, is(dateFromVarChar)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(date, is(dateFromVarChar)); + assertThat(accessor.wasNull(), is(false)); }); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDurationVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDurationVectorAccessorTest.java index 0f8dd12dee422..48492e21224b2 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDurationVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcDurationVectorAccessorTest.java @@ -22,24 +22,21 @@ import java.time.Duration; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessor; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.DurationVector; import org.apache.arrow.vector.types.TimeUnit; import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.FieldType; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcDurationVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private DurationVector vector; @@ -50,12 +47,12 @@ public class ArrowFlightJdbcDurationVectorAccessorTest { (DurationVector) vector, getCurrentRow, (boolean wasNull) -> {}); private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @Before + @BeforeEach public void setup() { FieldType fieldType = new FieldType(true, new ArrowType.Duration(TimeUnit.MILLISECOND), null); - this.vector = new DurationVector("", fieldType, rootAllocatorTestRule.getRootAllocator()); + this.vector = new DurationVector("", fieldType, rootAllocatorTestExtension.getRootAllocator()); int valueCount = 10; this.vector.setValueCount(valueCount); @@ -64,7 +61,7 @@ public void setup() { } } - @After + @AfterEach public void tearDown() { this.vector.close(); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcIntervalVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcIntervalVectorAccessorTest.java index 4f78e1fa7bbbb..521debc323e83 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcIntervalVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcIntervalVectorAccessorTest.java @@ -20,40 +20,33 @@ import static org.apache.arrow.driver.jdbc.utils.IntervalStringUtils.formatIntervalYear; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import java.time.Period; import java.time.format.DateTimeParseException; -import java.util.Arrays; -import java.util.Collection; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.IntervalDayVector; import org.apache.arrow.vector.IntervalMonthDayNanoVector; import org.apache.arrow.vector.IntervalYearVector; import org.apache.arrow.vector.PeriodDuration; import org.apache.arrow.vector.ValueVector; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public class ArrowFlightJdbcIntervalVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); - @Rule public final ErrorCollector collector = new ErrorCollector(); - - private final Supplier vectorSupplier; private ValueVector vector; private final AccessorTestUtils.AccessorSupplier @@ -75,17 +68,15 @@ public class ArrowFlightJdbcIntervalVectorAccessorTest { }; final AccessorTestUtils.AccessorIterator accessorIterator = - new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @Parameterized.Parameters(name = "{1}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - { + public static Stream data() { + return Stream.of( + Arguments.of( (Supplier) () -> { IntervalDayVector vector = - new IntervalDayVector("", rootAllocatorTestRule.getRootAllocator()); + new IntervalDayVector("", rootAllocatorTestExtension.getRootAllocator()); int valueCount = 10; vector.setValueCount(valueCount); @@ -94,13 +85,12 @@ public static Collection data() { } return vector; }, - "IntervalDayVector" - }, - { + "IntervalDayVector"), + Arguments.of( (Supplier) () -> { IntervalYearVector vector = - new IntervalYearVector("", rootAllocatorTestRule.getRootAllocator()); + new IntervalYearVector("", rootAllocatorTestExtension.getRootAllocator()); int valueCount = 10; vector.setValueCount(valueCount); @@ -109,13 +99,13 @@ public static Collection data() { } return vector; }, - "IntervalYearVector" - }, - { + "IntervalYearVector"), + Arguments.of( (Supplier) () -> { IntervalMonthDayNanoVector vector = - new IntervalMonthDayNanoVector("", rootAllocatorTestRule.getRootAllocator()); + new IntervalMonthDayNanoVector( + "", rootAllocatorTestExtension.getRootAllocator()); int valueCount = 10; vector.setValueCount(valueCount); @@ -124,36 +114,36 @@ public static Collection data() { } return vector; }, - "IntervalMonthDayNanoVector" - }, - }); - } - - public ArrowFlightJdbcIntervalVectorAccessorTest( - Supplier vectorSupplier, String vectorType) { - this.vectorSupplier = vectorSupplier; + "IntervalMonthDayNanoVector")); } - @Before - public void setup() { + public void setup(Supplier vectorSupplier) { this.vector = vectorSupplier.get(); } - @After + @AfterEach public void tearDown() { - this.vector.close(); + if (this.vector != null) { + this.vector.close(); + } } - @Test - public void testShouldGetObjectReturnValidObject() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectReturnValidObject(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcIntervalVectorAccessor::getObject, (accessor, currentRow) -> is(getExpectedObject(vector, currentRow))); } - @Test - public void testShouldGetObjectPassingObjectClassAsParameterReturnValidObject() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectPassingObjectClassAsParameterReturnValidObject( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); Class objectClass = getExpectedObjectClassForVector(vector); accessorIterator.assertAccessorGetter( vector, @@ -161,8 +151,10 @@ public void testShouldGetObjectPassingObjectClassAsParameterReturnValidObject() (accessor, currentRow) -> is(getExpectedObject(vector, currentRow))); } - @Test - public void testShouldGetObjectReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectReturnNull(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); setAllNullOnVector(vector); accessorIterator.assertAccessorGetter( vector, @@ -204,73 +196,79 @@ private String getStringOnVector(ValueVector vector, int index) { return null; } - @Test - public void testShouldGetIntervalYear() { - Assert.assertEquals("-002-00", formatIntervalYear(Period.parse("P-2Y"))); - Assert.assertEquals("-001-01", formatIntervalYear(Period.parse("P-1Y-1M"))); - Assert.assertEquals("-001-02", formatIntervalYear(Period.parse("P-1Y-2M"))); - Assert.assertEquals("-002-03", formatIntervalYear(Period.parse("P-2Y-3M"))); - Assert.assertEquals("-002-04", formatIntervalYear(Period.parse("P-2Y-4M"))); - Assert.assertEquals("-011-01", formatIntervalYear(Period.parse("P-11Y-1M"))); - Assert.assertEquals("+002-00", formatIntervalYear(Period.parse("P+2Y"))); - Assert.assertEquals("+001-01", formatIntervalYear(Period.parse("P+1Y1M"))); - Assert.assertEquals("+001-02", formatIntervalYear(Period.parse("P+1Y2M"))); - Assert.assertEquals("+002-03", formatIntervalYear(Period.parse("P+2Y3M"))); - Assert.assertEquals("+002-04", formatIntervalYear(Period.parse("P+2Y4M"))); - Assert.assertEquals("+011-01", formatIntervalYear(Period.parse("P+11Y1M"))); + @ParameterizedTest + @MethodSource("data") + public void testShouldGetIntervalYear(Supplier vectorSupplier) { + setup(vectorSupplier); + assertEquals("-002-00", formatIntervalYear(Period.parse("P-2Y"))); + assertEquals("-001-01", formatIntervalYear(Period.parse("P-1Y-1M"))); + assertEquals("-001-02", formatIntervalYear(Period.parse("P-1Y-2M"))); + assertEquals("-002-03", formatIntervalYear(Period.parse("P-2Y-3M"))); + assertEquals("-002-04", formatIntervalYear(Period.parse("P-2Y-4M"))); + assertEquals("-011-01", formatIntervalYear(Period.parse("P-11Y-1M"))); + assertEquals("+002-00", formatIntervalYear(Period.parse("P+2Y"))); + assertEquals("+001-01", formatIntervalYear(Period.parse("P+1Y1M"))); + assertEquals("+001-02", formatIntervalYear(Period.parse("P+1Y2M"))); + assertEquals("+002-03", formatIntervalYear(Period.parse("P+2Y3M"))); + assertEquals("+002-04", formatIntervalYear(Period.parse("P+2Y4M"))); + assertEquals("+011-01", formatIntervalYear(Period.parse("P+11Y1M"))); } - @Test - public void testShouldGetIntervalDay() { - Assert.assertEquals("-001 00:00:00.000", formatIntervalDay(Duration.parse("PT-24H"))); - Assert.assertEquals("+001 00:00:00.000", formatIntervalDay(Duration.parse("PT+24H"))); - Assert.assertEquals("-000 01:00:00.000", formatIntervalDay(Duration.parse("PT-1H"))); + @ParameterizedTest + @MethodSource("data") + public void testShouldGetIntervalDay(Supplier vectorSupplier) { + setup(vectorSupplier); + assertEquals("-001 00:00:00.000", formatIntervalDay(Duration.parse("PT-24H"))); + assertEquals("+001 00:00:00.000", formatIntervalDay(Duration.parse("PT+24H"))); + assertEquals("-000 01:00:00.000", formatIntervalDay(Duration.parse("PT-1H"))); // "JDK-8054978: java.time.Duration.parse() fails for negative duration with 0 seconds and // nanos" not fixed on JDK8 - // Assert.assertEquals("-000 01:00:00.001", - // formatIntervalDay(Duration.parse("PT-1H-0M-00.001S"))); - Assert.assertEquals( - "-000 01:00:00.001", formatIntervalDay(Duration.ofHours(-1).minusMillis(1))); - Assert.assertEquals("-000 01:01:01.000", formatIntervalDay(Duration.parse("PT-1H-1M-1S"))); - Assert.assertEquals("-000 02:02:02.002", formatIntervalDay(Duration.parse("PT-2H-2M-02.002S"))); - Assert.assertEquals( - "-000 23:59:59.999", formatIntervalDay(Duration.parse("PT-23H-59M-59.999S"))); + // assertEquals("-000 01:00:00.001", formatIntervalDay(Duration.parse("PT-1H-0M-00.001S"))); + assertEquals("-000 01:00:00.001", formatIntervalDay(Duration.ofHours(-1).minusMillis(1))); + assertEquals("-000 01:01:01.000", formatIntervalDay(Duration.parse("PT-1H-1M-1S"))); + assertEquals("-000 02:02:02.002", formatIntervalDay(Duration.parse("PT-2H-2M-02.002S"))); + assertEquals("-000 23:59:59.999", formatIntervalDay(Duration.parse("PT-23H-59M-59.999S"))); // "JDK-8054978: java.time.Duration.parse() fails for negative duration with 0 seconds and // nanos" not fixed on JDK8 - // Assert.assertEquals("-000 11:59:00.100", - // formatIntervalDay(Duration.parse("PT-11H-59M-00.100S"))); - Assert.assertEquals( + // assertEquals("-000 11:59:00.100", formatIntervalDay(Duration.parse("PT-11H-59M-00.100S"))); + assertEquals( "-000 11:59:00.100", formatIntervalDay(Duration.ofHours(-11).minusMinutes(59).minusMillis(100))); - Assert.assertEquals("-000 05:02:03.000", formatIntervalDay(Duration.parse("PT-5H-2M-3S"))); - Assert.assertEquals( - "-000 22:22:22.222", formatIntervalDay(Duration.parse("PT-22H-22M-22.222S"))); - Assert.assertEquals("+000 01:00:00.000", formatIntervalDay(Duration.parse("PT+1H"))); - Assert.assertEquals("+000 01:00:00.001", formatIntervalDay(Duration.parse("PT+1H0M00.001S"))); - Assert.assertEquals("+000 01:01:01.000", formatIntervalDay(Duration.parse("PT+1H1M1S"))); - Assert.assertEquals("+000 02:02:02.002", formatIntervalDay(Duration.parse("PT+2H2M02.002S"))); - Assert.assertEquals("+000 23:59:59.999", formatIntervalDay(Duration.parse("PT+23H59M59.999S"))); - Assert.assertEquals("+000 11:59:00.100", formatIntervalDay(Duration.parse("PT+11H59M00.100S"))); - Assert.assertEquals("+000 05:02:03.000", formatIntervalDay(Duration.parse("PT+5H2M3S"))); - Assert.assertEquals("+000 22:22:22.222", formatIntervalDay(Duration.parse("PT+22H22M22.222S"))); + assertEquals("-000 05:02:03.000", formatIntervalDay(Duration.parse("PT-5H-2M-3S"))); + assertEquals("-000 22:22:22.222", formatIntervalDay(Duration.parse("PT-22H-22M-22.222S"))); + assertEquals("+000 01:00:00.000", formatIntervalDay(Duration.parse("PT+1H"))); + assertEquals("+000 01:00:00.001", formatIntervalDay(Duration.parse("PT+1H0M00.001S"))); + assertEquals("+000 01:01:01.000", formatIntervalDay(Duration.parse("PT+1H1M1S"))); + assertEquals("+000 02:02:02.002", formatIntervalDay(Duration.parse("PT+2H2M02.002S"))); + assertEquals("+000 23:59:59.999", formatIntervalDay(Duration.parse("PT+23H59M59.999S"))); + assertEquals("+000 11:59:00.100", formatIntervalDay(Duration.parse("PT+11H59M00.100S"))); + assertEquals("+000 05:02:03.000", formatIntervalDay(Duration.parse("PT+5H2M3S"))); + assertEquals("+000 22:22:22.222", formatIntervalDay(Duration.parse("PT+22H22M22.222S"))); } - @Test - public void testIntervalDayWithJodaPeriodObject() { - Assert.assertEquals("+1567 00:00:00.000", formatIntervalDay(Duration.ofDays(1567))); - Assert.assertEquals("-1567 00:00:00.000", formatIntervalDay(Duration.ofDays(-1567))); + @ParameterizedTest + @MethodSource("data") + public void testIntervalDayWithJodaPeriodObject(Supplier vectorSupplier) { + setup(vectorSupplier); + assertEquals("+1567 00:00:00.000", formatIntervalDay(Duration.ofDays(1567))); + assertEquals("-1567 00:00:00.000", formatIntervalDay(Duration.ofDays(-1567))); } - @Test - public void testShouldGetStringReturnCorrectString() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringReturnCorrectString(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcIntervalVectorAccessor::getString, (accessor, currentRow) -> is(getStringOnVector(vector, currentRow))); } - @Test - public void testShouldGetStringReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringReturnNull(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); setAllNullOnVector(vector); accessorIterator.assertAccessorGetter( vector, @@ -278,8 +276,11 @@ public void testShouldGetStringReturnNull() throws Exception { (accessor, currentRow) -> equalTo(null)); } - @Test - public void testShouldGetObjectClassReturnCorrectClass() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectClassReturnCorrectClass(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); Class expectedObjectClass = getExpectedObjectClassForVector(vector); accessorIterator.assertAccessorGetter( vector, diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeStampVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeStampVectorAccessorTest.java index 7fc7b986b1bfa..2e329f148e66c 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeStampVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeStampVectorAccessorTest.java @@ -20,20 +20,20 @@ import static org.apache.arrow.driver.jdbc.accessor.impl.calendar.ArrowFlightJdbcTimeStampVectorAccessor.getTimeZoneForVector; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.time.LocalDateTime; -import java.util.Arrays; import java.util.Calendar; -import java.util.Collection; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.impl.text.ArrowFlightJdbcVarCharVectorAccessor; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.TimeStampMicroVector; import org.apache.arrow.vector.TimeStampMilliVector; import org.apache.arrow.vector.TimeStampNanoVector; @@ -42,31 +42,24 @@ import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.util.Text; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + public class ArrowFlightJdbcTimeStampVectorAccessorTest { public static final String AMERICA_VANCOUVER = "America/Vancouver"; public static final String ASIA_BANGKOK = "Asia/Bangkok"; public static final String AMERICA_SAO_PAULO = "America/Sao_Paulo"; - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); - private final String timeZone; + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private TimeStampVector vector; - private final Supplier vectorSupplier; private final AccessorTestUtils.AccessorSupplier accessorSupplier = @@ -75,133 +68,117 @@ public class ArrowFlightJdbcTimeStampVectorAccessorTest { (TimeStampVector) vector, getCurrentRow, (boolean wasNull) -> {}); private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); - - @Parameterized.Parameters(name = "{1} - TimeZone: {2}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - { - (Supplier) () -> rootAllocatorTestRule.createTimeStampNanoVector(), + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); + + public static Stream data() { + return Stream.of( + Arguments.of( + (Supplier) + () -> rootAllocatorTestExtension.createTimeStampNanoVector(), "TimeStampNanoVector", - null - }, - { + null), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampNanoTZVector("UTC"), + () -> rootAllocatorTestExtension.createTimeStampNanoTZVector("UTC"), "TimeStampNanoTZVector", - "UTC" - }, - { + "UTC"), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampNanoTZVector(AMERICA_VANCOUVER), + () -> rootAllocatorTestExtension.createTimeStampNanoTZVector(AMERICA_VANCOUVER), "TimeStampNanoTZVector", - AMERICA_VANCOUVER - }, - { + AMERICA_VANCOUVER), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampNanoTZVector(ASIA_BANGKOK), + () -> rootAllocatorTestExtension.createTimeStampNanoTZVector(ASIA_BANGKOK), "TimeStampNanoTZVector", - ASIA_BANGKOK - }, - { - (Supplier) () -> rootAllocatorTestRule.createTimeStampMicroVector(), + ASIA_BANGKOK), + Arguments.of( + (Supplier) + () -> rootAllocatorTestExtension.createTimeStampMicroVector(), "TimeStampMicroVector", - null - }, - { + null), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampMicroTZVector("UTC"), + () -> rootAllocatorTestExtension.createTimeStampMicroTZVector("UTC"), "TimeStampMicroTZVector", - "UTC" - }, - { + "UTC"), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampMicroTZVector(AMERICA_VANCOUVER), + () -> rootAllocatorTestExtension.createTimeStampMicroTZVector(AMERICA_VANCOUVER), "TimeStampMicroTZVector", - AMERICA_VANCOUVER - }, - { + AMERICA_VANCOUVER), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampMicroTZVector(ASIA_BANGKOK), + () -> rootAllocatorTestExtension.createTimeStampMicroTZVector(ASIA_BANGKOK), "TimeStampMicroTZVector", - ASIA_BANGKOK - }, - { - (Supplier) () -> rootAllocatorTestRule.createTimeStampMilliVector(), + ASIA_BANGKOK), + Arguments.of( + (Supplier) + () -> rootAllocatorTestExtension.createTimeStampMilliVector(), "TimeStampMilliVector", - null - }, - { + null), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampMilliTZVector("UTC"), + () -> rootAllocatorTestExtension.createTimeStampMilliTZVector("UTC"), "TimeStampMilliTZVector", - "UTC" - }, - { + "UTC"), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampMilliTZVector(AMERICA_VANCOUVER), + () -> rootAllocatorTestExtension.createTimeStampMilliTZVector(AMERICA_VANCOUVER), "TimeStampMilliTZVector", - AMERICA_VANCOUVER - }, - { + AMERICA_VANCOUVER), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampMilliTZVector(ASIA_BANGKOK), + () -> rootAllocatorTestExtension.createTimeStampMilliTZVector(ASIA_BANGKOK), "TimeStampMilliTZVector", - ASIA_BANGKOK - }, - { - (Supplier) () -> rootAllocatorTestRule.createTimeStampSecVector(), + ASIA_BANGKOK), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createTimeStampSecVector(), "TimeStampSecVector", - null - }, - { + null), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampSecTZVector("UTC"), + () -> rootAllocatorTestExtension.createTimeStampSecTZVector("UTC"), "TimeStampSecTZVector", - "UTC" - }, - { + "UTC"), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampSecTZVector(AMERICA_VANCOUVER), + () -> rootAllocatorTestExtension.createTimeStampSecTZVector(AMERICA_VANCOUVER), "TimeStampSecTZVector", - AMERICA_VANCOUVER - }, - { + AMERICA_VANCOUVER), + Arguments.of( (Supplier) - () -> rootAllocatorTestRule.createTimeStampSecTZVector(ASIA_BANGKOK), + () -> rootAllocatorTestExtension.createTimeStampSecTZVector(ASIA_BANGKOK), "TimeStampSecTZVector", - ASIA_BANGKOK - } - }); - } - - public ArrowFlightJdbcTimeStampVectorAccessorTest( - Supplier vectorSupplier, String vectorType, String timeZone) { - this.vectorSupplier = vectorSupplier; - this.timeZone = timeZone; + ASIA_BANGKOK)); } - @Before - public void setup() { + public void setup(Supplier vectorSupplier) { this.vector = vectorSupplier.get(); } - @After + @AfterEach public void tearDown() { this.vector.close(); } - @Test - public void testShouldGetTimestampReturnValidTimestampWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnValidTimestampWithoutCalendar( + Supplier vectorSupplier, String vectorType, String timeZone) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getTimestamp(null), - (accessor, currentRow) -> is(getTimestampForVector(currentRow))); + (accessor, currentRow) -> is(getTimestampForVector(currentRow, timeZone))); } - @Test - public void testShouldGetTimestampReturnValidTimestampWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnValidTimestampWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); TimeZone timeZone = TimeZone.getTimeZone(AMERICA_SAO_PAULO); Calendar calendar = Calendar.getInstance(timeZone); @@ -217,29 +194,39 @@ public void testShouldGetTimestampReturnValidTimestampWithCalendar() throws Exce (long) timeZone.getOffset(resultWithoutCalendar.getTime()) - timeZoneForVector.getOffset(resultWithoutCalendar.getTime()); - collector.checkThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); + assertThat(accessor.wasNull(), is(false)); }); } - @Test - public void testShouldGetTimestampReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.setNull(0); ArrowFlightJdbcTimeStampVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getTimestamp(null), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getTimestamp(null), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetDateReturnValidDateWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDateReturnValidDateWithoutCalendar( + Supplier vectorSupplier, String vectorType, String timeZone) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getDate(null), - (accessor, currentRow) -> is(new Date(getTimestampForVector(currentRow).getTime()))); + (accessor, currentRow) -> + is(new Date(getTimestampForVector(currentRow, timeZone).getTime()))); } - @Test - public void testShouldGetDateReturnValidDateWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDateReturnValidDateWithCalendar(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); TimeZone timeZone = TimeZone.getTimeZone(AMERICA_SAO_PAULO); Calendar calendar = Calendar.getInstance(timeZone); @@ -255,29 +242,39 @@ public void testShouldGetDateReturnValidDateWithCalendar() throws Exception { (long) timeZone.getOffset(resultWithoutCalendar.getTime()) - timeZoneForVector.getOffset(resultWithoutCalendar.getTime()); - collector.checkThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); + assertThat(accessor.wasNull(), is(false)); }); } - @Test - public void testShouldGetDateReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDateReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.setNull(0); ArrowFlightJdbcTimeStampVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getDate(null), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getDate(null), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetTimeReturnValidTimeWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimeReturnValidTimeWithoutCalendar( + Supplier vectorSupplier, String vectorType, String timeZone) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getTime(null), - (accessor, currentRow) -> is(new Time(getTimestampForVector(currentRow).getTime()))); + (accessor, currentRow) -> + is(new Time(getTimestampForVector(currentRow, timeZone).getTime()))); } - @Test - public void testShouldGetTimeReturnValidTimeWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimeReturnValidTimeWithCalendar(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); TimeZone timeZone = TimeZone.getTimeZone(AMERICA_SAO_PAULO); Calendar calendar = Calendar.getInstance(timeZone); @@ -293,20 +290,22 @@ public void testShouldGetTimeReturnValidTimeWithCalendar() throws Exception { (long) timeZone.getOffset(resultWithoutCalendar.getTime()) - timeZoneForVector.getOffset(resultWithoutCalendar.getTime()); - collector.checkThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); + assertThat(accessor.wasNull(), is(false)); }); } - @Test - public void testShouldGetTimeReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimeReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.setNull(0); ArrowFlightJdbcTimeStampVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getTime(null), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getTime(null), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - private Timestamp getTimestampForVector(int currentRow) { + private Timestamp getTimestampForVector(int currentRow, String timeZone) { Object object = vector.getObject(currentRow); Timestamp expectedTimestamp = null; @@ -321,21 +320,29 @@ private Timestamp getTimestampForVector(int currentRow) { return expectedTimestamp; } - @Test - public void testShouldGetObjectClass() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectClass(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcTimeStampVectorAccessor::getObjectClass, equalTo(Timestamp.class)); } - @Test - public void testShouldGetStringBeConsistentWithVarCharAccessorWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringBeConsistentWithVarCharAccessorWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); assertGetStringIsConsistentWithVarCharAccessor(null); } - @Test - public void testShouldGetStringBeConsistentWithVarCharAccessorWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringBeConsistentWithVarCharAccessorWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); // Ignore for TimeStamp vectors with TZ, as VarChar accessor won't consider their TZ - Assume.assumeTrue( + Assumptions.assumeTrue( vector instanceof TimeStampNanoVector || vector instanceof TimeStampMicroVector || vector instanceof TimeStampMilliVector @@ -346,7 +353,7 @@ public void testShouldGetStringBeConsistentWithVarCharAccessorWithCalendar() thr private void assertGetStringIsConsistentWithVarCharAccessor(Calendar calendar) throws Exception { try (VarCharVector varCharVector = - new VarCharVector("", rootAllocatorTestRule.getRootAllocator())) { + new VarCharVector("", rootAllocatorTestExtension.getRootAllocator())) { varCharVector.allocateNew(1); ArrowFlightJdbcVarCharVectorAccessor varCharVectorAccessor = new ArrowFlightJdbcVarCharVectorAccessor(varCharVector, () -> 0, (boolean wasNull) -> {}); @@ -361,8 +368,8 @@ private void assertGetStringIsConsistentWithVarCharAccessor(Calendar calendar) t Timestamp timestampFromVarChar = varCharVectorAccessor.getTimestamp(calendar); Timestamp timestamp = accessor.getTimestamp(calendar); - collector.checkThat(timestamp, is(timestampFromVarChar)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(timestamp, is(timestampFromVarChar)); + assertThat(accessor.wasNull(), is(false)); }); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java index 2641cb15c2412..24971052db1be 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java @@ -20,20 +20,20 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Time; import java.sql.Timestamp; import java.time.LocalDateTime; -import java.util.Arrays; import java.util.Calendar; -import java.util.Collection; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.driver.jdbc.accessor.impl.text.ArrowFlightJdbcVarCharVectorAccessor; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.BaseFixedWidthVector; import org.apache.arrow.vector.TimeMicroVector; import org.apache.arrow.vector.TimeMilliVector; @@ -42,27 +42,21 @@ import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.util.Text; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + public class ArrowFlightJdbcTimeVectorAccessorTest { public static final String AMERICA_VANCOUVER = "America/Vancouver"; - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private BaseFixedWidthVector vector; - private final Supplier vectorSupplier; private final AccessorTestUtils.AccessorSupplier accessorSupplier = @@ -86,56 +80,49 @@ public class ArrowFlightJdbcTimeVectorAccessorTest { }; private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); - - @Parameterized.Parameters(name = "{1}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - { - (Supplier) () -> rootAllocatorTestRule.createTimeNanoVector(), - "TimeNanoVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createTimeMicroVector(), - "TimeMicroVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createTimeMilliVector(), - "TimeMilliVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createTimeSecVector(), - "TimeSecVector" - } - }); - } - - public ArrowFlightJdbcTimeVectorAccessorTest( - Supplier vectorSupplier, String vectorType) { - this.vectorSupplier = vectorSupplier; + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); + + public static Stream data() { + return Stream.of( + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createTimeNanoVector(), + "TimeNanoVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createTimeMicroVector(), + "TimeMicroVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createTimeMilliVector(), + "TimeMilliVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createTimeSecVector(), + "TimeSecVector")); } - @Before - public void setup() { + public void setup(Supplier vectorSupplier) { this.vector = vectorSupplier.get(); } - @After + @AfterEach public void tearDown() { this.vector.close(); } - @Test - public void testShouldGetTimestampReturnValidTimestampWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnValidTimestampWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getTimestamp(null), (accessor, currentRow) -> is(getTimestampForVector(currentRow))); } - @Test - public void testShouldGetTimestampReturnValidTimestampWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnValidTimestampWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); TimeZone timeZone = TimeZone.getTimeZone(AMERICA_VANCOUVER); Calendar calendar = Calendar.getInstance(timeZone); @@ -147,21 +134,26 @@ public void testShouldGetTimestampReturnValidTimestampWithCalendar() throws Exce long offset = timeZone.getOffset(resultWithoutCalendar.getTime()); - collector.checkThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); + assertThat(accessor.wasNull(), is(false)); }); } - @Test - public void testShouldGetTimestampReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimestampReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.setNull(0); ArrowFlightJdbcTimeVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getTimestamp(null), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getTimestamp(null), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } - @Test - public void testShouldGetTimeReturnValidTimeWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimeReturnValidTimeWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, accessor -> accessor.getTime(null), @@ -171,8 +163,11 @@ public void testShouldGetTimeReturnValidTimeWithoutCalendar() throws Exception { }); } - @Test - public void testShouldGetTimeReturnValidTimeWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimeReturnValidTimeWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); TimeZone timeZone = TimeZone.getTimeZone(AMERICA_VANCOUVER); Calendar calendar = Calendar.getInstance(timeZone); @@ -184,17 +179,19 @@ public void testShouldGetTimeReturnValidTimeWithCalendar() throws Exception { long offset = timeZone.getOffset(resultWithoutCalendar.getTime()); - collector.checkThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(resultWithoutCalendar.getTime() - result.getTime(), is(offset)); + assertThat(accessor.wasNull(), is(false)); }); } - @Test - public void testShouldGetTimeReturnNull() { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetTimeReturnNull(Supplier vectorSupplier) { + setup(vectorSupplier); vector.setNull(0); ArrowFlightJdbcTimeVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); - collector.checkThat(accessor.getTime(null), CoreMatchers.equalTo(null)); - collector.checkThat(accessor.wasNull(), is(true)); + assertThat(accessor.getTime(null), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); } private Timestamp getTimestampForVector(int currentRow) { @@ -212,25 +209,37 @@ private Timestamp getTimestampForVector(int currentRow) { return expectedTimestamp; } - @Test - public void testShouldGetObjectClass() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectClass(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcTimeVectorAccessor::getObjectClass, equalTo(Time.class)); } - @Test - public void testShouldGetStringBeConsistentWithVarCharAccessorWithoutCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringBeConsistentWithVarCharAccessorWithoutCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); assertGetStringIsConsistentWithVarCharAccessor(null); } - @Test - public void testShouldGetStringBeConsistentWithVarCharAccessorWithCalendar() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringBeConsistentWithVarCharAccessorWithCalendar( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(AMERICA_VANCOUVER)); assertGetStringIsConsistentWithVarCharAccessor(calendar); } - @Test - public void testValidateGetStringTimeZoneConsistency() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testValidateGetStringTimeZoneConsistency( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { @@ -242,13 +251,13 @@ public void testValidateGetStringTimeZoneConsistency() throws Exception { // Validate with UTC Time time = accessor.getTime(null); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); - collector.checkThat(time.toString(), is(string)); + assertThat(time.toString(), is(string)); // Validate with different TZ TimeZone.setDefault(TimeZone.getTimeZone(AMERICA_VANCOUVER)); - collector.checkThat(time.toString(), not(string)); + assertThat(time.toString(), not(string)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(accessor.wasNull(), is(false)); } finally { // Set default Tz back TimeZone.setDefault(defaultTz); @@ -258,7 +267,7 @@ public void testValidateGetStringTimeZoneConsistency() throws Exception { private void assertGetStringIsConsistentWithVarCharAccessor(Calendar calendar) throws Exception { try (VarCharVector varCharVector = - new VarCharVector("", rootAllocatorTestRule.getRootAllocator())) { + new VarCharVector("", rootAllocatorTestExtension.getRootAllocator())) { varCharVector.allocateNew(1); ArrowFlightJdbcVarCharVectorAccessor varCharVectorAccessor = new ArrowFlightJdbcVarCharVectorAccessor(varCharVector, () -> 0, (boolean wasNull) -> {}); @@ -273,8 +282,8 @@ private void assertGetStringIsConsistentWithVarCharAccessor(Calendar calendar) t Time timeFromVarChar = varCharVectorAccessor.getTime(calendar); Time time = accessor.getTime(calendar); - collector.checkThat(time, is(timeFromVarChar)); - collector.checkThat(accessor.wasNull(), is(false)); + assertThat(time, is(timeFromVarChar)); + assertThat(accessor.wasNull(), is(false)); }); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcListAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcListAccessorTest.java index 599b3b98e6ea5..ad689837e2201 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcListAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcListAccessorTest.java @@ -17,39 +17,34 @@ package org.apache.arrow.driver.jdbc.accessor.impl.complex; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Array; import java.sql.ResultSet; import java.util.Arrays; -import java.util.Collection; import java.util.List; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.ValueVector; import org.apache.arrow.vector.complex.FixedSizeListVector; import org.apache.arrow.vector.complex.LargeListVector; import org.apache.arrow.vector.complex.ListVector; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class AbstractArrowFlightJdbcListAccessorTest { +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); +public class AbstractArrowFlightJdbcListAccessorTest { - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); - private final Supplier vectorSupplier; private ValueVector vector; private final AccessorTestUtils.AccessorSupplier @@ -71,49 +66,46 @@ public class AbstractArrowFlightJdbcListAccessorTest { }; final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); - - @Parameterized.Parameters(name = "{1}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - {(Supplier) () -> rootAllocatorTestRule.createListVector(), "ListVector"}, - { - (Supplier) () -> rootAllocatorTestRule.createLargeListVector(), - "LargeListVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createFixedSizeListVector(), - "FixedSizeListVector" - }, - }); - } - - public AbstractArrowFlightJdbcListAccessorTest( - Supplier vectorSupplier, String vectorType) { - this.vectorSupplier = vectorSupplier; + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); + + public static Stream data() { + return Stream.of( + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createListVector(), + "ListVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createLargeListVector(), + "LargeListVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createFixedSizeListVector(), + "FixedSizeListVector")); } - @Before - public void setup() { - this.vector = this.vectorSupplier.get(); + public void setup(Supplier vectorSupplier) { + this.vector = vectorSupplier.get(); } - @After + @AfterEach public void tearDown() { this.vector.close(); } - @Test - public void testShouldGetObjectClassReturnCorrectClass() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectClassReturnCorrectClass(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, AbstractArrowFlightJdbcListVectorAccessor::getObjectClass, (accessor, currentRow) -> equalTo(List.class)); } - @Test - public void testShouldGetObjectReturnValidList() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectReturnValidList(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, AbstractArrowFlightJdbcListVectorAccessor::getObject, @@ -121,8 +113,10 @@ public void testShouldGetObjectReturnValidList() throws Exception { equalTo(Arrays.asList(0, currentRow, currentRow * 2, currentRow * 3, currentRow * 4))); } - @Test - public void testShouldGetObjectReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectReturnNull(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); vector.clear(); vector.allocateNewSafe(); vector.setValueCount(5); @@ -133,8 +127,11 @@ public void testShouldGetObjectReturnNull() throws Exception { (accessor, currentRow) -> CoreMatchers.nullValue()); } - @Test - public void testShouldGetArrayReturnValidArray() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetArrayReturnValidArray(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { @@ -143,15 +140,17 @@ public void testShouldGetArrayReturnValidArray() throws Exception { Object[] arrayObject = (Object[]) array.getArray(); - collector.checkThat( + assertThat( arrayObject, equalTo( new Object[] {0, currentRow, currentRow * 2, currentRow * 3, currentRow * 4})); }); } - @Test - public void testShouldGetArrayReturnNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetArrayReturnNull(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); vector.clear(); vector.allocateNewSafe(); vector.setValueCount(5); @@ -160,8 +159,11 @@ public void testShouldGetArrayReturnNull() throws Exception { vector, AbstractArrowFlightJdbcListVectorAccessor::getArray, CoreMatchers.nullValue()); } - @Test - public void testShouldGetArrayReturnValidArrayPassingOffsets() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetArrayReturnValidArrayPassingOffsets(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { @@ -170,13 +172,16 @@ public void testShouldGetArrayReturnValidArrayPassingOffsets() throws Exception Object[] arrayObject = (Object[]) array.getArray(1, 3); - collector.checkThat( + assertThat( arrayObject, equalTo(new Object[] {currentRow, currentRow * 2, currentRow * 3})); }); } - @Test - public void testShouldGetArrayGetResultSetReturnValidResultSet() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetArrayGetResultSetReturnValidResultSet( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.iterate( vector, (accessor, currentRow) -> { @@ -187,10 +192,10 @@ public void testShouldGetArrayGetResultSetReturnValidResultSet() throws Exceptio int count = 0; while (rs.next()) { final int value = rs.getInt(1); - collector.checkThat(value, equalTo(currentRow * count)); + assertThat(value, equalTo(currentRow * count)); count++; } - collector.checkThat(count, equalTo(5)); + assertThat(count, equalTo(5)); } }); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcUnionVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcUnionVectorAccessorTest.java index f0e88aa8cad84..6a143d2ee888f 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcUnionVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/AbstractArrowFlightJdbcUnionVectorAccessorTest.java @@ -27,20 +27,20 @@ import org.apache.arrow.driver.jdbc.accessor.impl.ArrowFlightJdbcNullVectorAccessor; import org.apache.arrow.vector.NullVector; import org.apache.arrow.vector.ValueVector; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AbstractArrowFlightJdbcUnionVectorAccessorTest { @Mock ArrowFlightJdbcAccessor innerAccessor; @Spy AbstractArrowFlightJdbcUnionVectorAccessorMock accessor; - @Before + @BeforeEach public void setup() { when(accessor.getAccessor()).thenReturn(innerAccessor); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcDenseUnionVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcDenseUnionVectorAccessorTest.java index d9969ac9bfa87..6832ac0850d4c 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcDenseUnionVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcDenseUnionVectorAccessorTest.java @@ -18,31 +18,29 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.complex.DenseUnionVector; import org.apache.arrow.vector.holders.NullableBigIntHolder; import org.apache.arrow.vector.holders.NullableFloat8Holder; import org.apache.arrow.vector.holders.NullableTimeStampMilliHolder; import org.apache.arrow.vector.types.Types; import org.apache.arrow.vector.types.pojo.Field; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcDenseUnionVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private DenseUnionVector vector; @@ -57,11 +55,11 @@ public class ArrowFlightJdbcDenseUnionVectorAccessorTest { }); private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @Before + @BeforeEach public void setup() throws Exception { - this.vector = DenseUnionVector.empty("", rootAllocatorTestRule.getRootAllocator()); + this.vector = DenseUnionVector.empty("", rootAllocatorTestExtension.getRootAllocator()); this.vector.allocateNew(); // write some data @@ -97,7 +95,7 @@ public void setup() throws Exception { this.vector.setValueCount(5); } - @After + @AfterEach public void tearDown() { this.vector.close(); } @@ -108,7 +106,7 @@ public void getObject() throws Exception { List expected = Arrays.asList(Long.MAX_VALUE, Math.PI, new Timestamp(1625702400000L), null, null); - collector.checkThat(result, is(expected)); + assertThat(result, is(expected)); } @Test diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcMapVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcMapVectorAccessorTest.java index 1a9a5eedd59af..696e5afb71171 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcMapVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcMapVectorAccessorTest.java @@ -16,35 +16,37 @@ */ package org.apache.arrow.driver.jdbc.accessor.impl.complex; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.complex.MapVector; import org.apache.arrow.vector.complex.StructVector; import org.apache.arrow.vector.complex.impl.UnionMapWriter; import org.apache.arrow.vector.util.JsonStringHashMap; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcMapVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private MapVector vector; - @Before + @BeforeEach public void setup() { - vector = MapVector.empty("", rootAllocatorTestRule.getRootAllocator(), false); + vector = MapVector.empty("", rootAllocatorTestExtension.getRootAllocator(), false); UnionMapWriter writer = vector.getWriter(); writer.allocate(); writer.setPosition(0); // optional @@ -93,7 +95,7 @@ public void setup() { writer.setValueCount(3); } - @After + @AfterEach public void tearDown() { vector.close(); } @@ -109,14 +111,14 @@ public void testShouldGetObjectReturnValidMap() { expected.put(1, 11); expected.put(2, 22); expected.put(3, 33); - Assert.assertEquals(expected, accessor.getObject()); - Assert.assertFalse(accessor.wasNull()); + assertEquals(expected, accessor.getObject()); + assertFalse(accessor.wasNull()); cursor.next(); expected = new JsonStringHashMap<>(); expected.put(2, null); - Assert.assertEquals(expected, accessor.getObject()); - Assert.assertFalse(accessor.wasNull()); + assertEquals(expected, accessor.getObject()); + assertFalse(accessor.wasNull()); cursor.next(); expected = new JsonStringHashMap<>(); @@ -124,8 +126,8 @@ public void testShouldGetObjectReturnValidMap() { expected.put(1, 2001); expected.put(2, 2002); expected.put(3, 2003); - Assert.assertEquals(expected, accessor.getObject()); - Assert.assertFalse(accessor.wasNull()); + assertEquals(expected, accessor.getObject()); + assertFalse(accessor.wasNull()); } @Test @@ -134,8 +136,8 @@ public void testShouldGetObjectReturnNull() { ArrowFlightJdbcMapVectorAccessor accessor = new ArrowFlightJdbcMapVectorAccessor(vector, () -> 0, (boolean wasNull) -> {}); - Assert.assertNull(accessor.getObject()); - Assert.assertTrue(accessor.wasNull()); + assertNull(accessor.getObject()); + assertTrue(accessor.wasNull()); } @Test @@ -146,59 +148,59 @@ public void testShouldGetArrayReturnValidArray() throws SQLException { vector, cursor::getCurrentRow, (boolean wasNull) -> {}); Array array = accessor.getArray(); - Assert.assertNotNull(array); - Assert.assertFalse(accessor.wasNull()); + assertNotNull(array); + assertFalse(accessor.wasNull()); try (ResultSet resultSet = array.getResultSet()) { - Assert.assertTrue(resultSet.next()); + assertTrue(resultSet.next()); Map entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(1, entry.get("key")); - Assert.assertEquals(11, entry.get("value")); - Assert.assertTrue(resultSet.next()); + assertEquals(1, entry.get("key")); + assertEquals(11, entry.get("value")); + assertTrue(resultSet.next()); entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(2, entry.get("key")); - Assert.assertEquals(22, entry.get("value")); - Assert.assertTrue(resultSet.next()); + assertEquals(2, entry.get("key")); + assertEquals(22, entry.get("value")); + assertTrue(resultSet.next()); entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(3, entry.get("key")); - Assert.assertEquals(33, entry.get("value")); - Assert.assertFalse(resultSet.next()); + assertEquals(3, entry.get("key")); + assertEquals(33, entry.get("value")); + assertFalse(resultSet.next()); } cursor.next(); array = accessor.getArray(); - Assert.assertNotNull(array); - Assert.assertFalse(accessor.wasNull()); + assertNotNull(array); + assertFalse(accessor.wasNull()); try (ResultSet resultSet = array.getResultSet()) { - Assert.assertTrue(resultSet.next()); + assertTrue(resultSet.next()); Map entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(2, entry.get("key")); - Assert.assertNull(entry.get("value")); - Assert.assertFalse(resultSet.next()); + assertEquals(2, entry.get("key")); + assertNull(entry.get("value")); + assertFalse(resultSet.next()); } cursor.next(); array = accessor.getArray(); - Assert.assertNotNull(array); - Assert.assertFalse(accessor.wasNull()); + assertNotNull(array); + assertFalse(accessor.wasNull()); try (ResultSet resultSet = array.getResultSet()) { - Assert.assertTrue(resultSet.next()); + assertTrue(resultSet.next()); Map entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(0, entry.get("key")); - Assert.assertEquals(2000, entry.get("value")); - Assert.assertTrue(resultSet.next()); + assertEquals(0, entry.get("key")); + assertEquals(2000, entry.get("value")); + assertTrue(resultSet.next()); entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(1, entry.get("key")); - Assert.assertEquals(2001, entry.get("value")); - Assert.assertTrue(resultSet.next()); + assertEquals(1, entry.get("key")); + assertEquals(2001, entry.get("value")); + assertTrue(resultSet.next()); entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(2, entry.get("key")); - Assert.assertEquals(2002, entry.get("value")); - Assert.assertTrue(resultSet.next()); + assertEquals(2, entry.get("key")); + assertEquals(2002, entry.get("value")); + assertTrue(resultSet.next()); entry = resultSet.getObject(1, Map.class); - Assert.assertEquals(3, entry.get("key")); - Assert.assertEquals(2003, entry.get("value")); - Assert.assertFalse(resultSet.next()); + assertEquals(3, entry.get("key")); + assertEquals(2003, entry.get("value")); + assertFalse(resultSet.next()); } } @@ -210,7 +212,7 @@ public void testShouldGetArrayReturnNull() { ArrowFlightJdbcMapVectorAccessor accessor = new ArrowFlightJdbcMapVectorAccessor(vector, () -> 0, (boolean wasNull) -> {}); - Assert.assertNull(accessor.getArray()); - Assert.assertTrue(accessor.wasNull()); + assertNull(accessor.getArray()); + assertTrue(accessor.wasNull()); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcStructVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcStructVectorAccessorTest.java index 0dd0dff2798f4..d3cc7f8544579 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcStructVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcStructVectorAccessorTest.java @@ -18,13 +18,15 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.SQLException; import java.sql.Struct; import java.util.HashMap; import java.util.Map; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.Float8Vector; import org.apache.arrow.vector.IntVector; import org.apache.arrow.vector.complex.ListVector; @@ -37,20 +39,16 @@ import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.util.JsonStringArrayList; import org.apache.arrow.vector.util.JsonStringHashMap; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcStructVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private StructVector vector; @@ -61,14 +59,14 @@ public class ArrowFlightJdbcStructVectorAccessorTest { (StructVector) vector, getCurrentRow, (boolean wasNull) -> {}); private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @Before + @BeforeEach public void setUp() throws Exception { Map metadata = new HashMap<>(); metadata.put("k1", "v1"); FieldType type = new FieldType(true, ArrowType.Struct.INSTANCE, null, metadata); - vector = new StructVector("", rootAllocatorTestRule.getRootAllocator(), type, null); + vector = new StructVector("", rootAllocatorTestExtension.getRootAllocator(), type, null); vector.allocateNew(); IntVector intVector = @@ -87,7 +85,7 @@ public void setUp() throws Exception { vector.setValueCount(2); } - @After + @AfterEach public void tearDown() throws Exception { vector.close(); } @@ -134,7 +132,7 @@ public void testShouldGetStructReturnValidStruct() throws Exception { Object[] expected = new Object[] {100 * (currentRow + 1), 100.05 * (currentRow + 1)}; - collector.checkThat(struct.getAttributes(), equalTo(expected)); + assertThat(struct.getAttributes(), equalTo(expected)); }); } @@ -151,7 +149,7 @@ public void testShouldGetStructReturnNull() throws Exception { @Test public void testShouldGetObjectWorkWithNestedComplexData() throws SQLException { try (StructVector rootVector = - StructVector.empty("", rootAllocatorTestRule.getRootAllocator())) { + StructVector.empty("", rootAllocatorTestExtension.getRootAllocator())) { StructVector structVector = rootVector.addOrGetStruct("struct"); FieldType intFieldType = FieldType.nullable(Types.MinorType.INT.getType()); @@ -203,8 +201,8 @@ public void testShouldGetObjectWorkWithNestedComplexData() throws SQLException { ArrowFlightJdbcStructVectorAccessor accessor = new ArrowFlightJdbcStructVectorAccessor(rootVector, () -> 0, (boolean wasNull) -> {}); - Assert.assertEquals(expected, accessor.getObject()); - Assert.assertEquals(expected.toString(), accessor.getString()); + assertEquals(expected, accessor.getObject()); + assertEquals(expected.toString(), accessor.getString()); } } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcUnionVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcUnionVectorAccessorTest.java index 0600d665de414..82cd882393cfa 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcUnionVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/complex/ArrowFlightJdbcUnionVectorAccessorTest.java @@ -18,30 +18,28 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.complex.UnionVector; import org.apache.arrow.vector.holders.NullableBigIntHolder; import org.apache.arrow.vector.holders.NullableFloat8Holder; import org.apache.arrow.vector.holders.NullableTimeStampMilliHolder; import org.apache.arrow.vector.types.Types; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcUnionVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private UnionVector vector; @@ -52,11 +50,11 @@ public class ArrowFlightJdbcUnionVectorAccessorTest { (UnionVector) vector, getCurrentRow, (boolean wasNull) -> {}); private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @Before + @BeforeEach public void setup() { - this.vector = UnionVector.empty("", rootAllocatorTestRule.getRootAllocator()); + this.vector = UnionVector.empty("", rootAllocatorTestExtension.getRootAllocator()); this.vector.allocateNew(); NullableBigIntHolder nullableBigIntHolder = new NullableBigIntHolder(); @@ -84,7 +82,7 @@ public void setup() { this.vector.setValueCount(5); } - @After + @AfterEach public void tearDown() { this.vector.close(); } @@ -95,7 +93,7 @@ public void getObject() throws Exception { List expected = Arrays.asList(Long.MAX_VALUE, Math.PI, new Timestamp(1625702400000L), null, null); - collector.checkThat(result, is(expected)); + assertThat(result, is(expected)); } @Test diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorTest.java index ca6514de0ffd5..c7b050d00021c 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorTest.java @@ -18,12 +18,11 @@ import static org.hamcrest.CoreMatchers.equalTo; -import java.util.Arrays; -import java.util.Collection; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.BaseIntVector; import org.apache.arrow.vector.BigIntVector; import org.apache.arrow.vector.IntVector; @@ -33,25 +32,19 @@ import org.apache.arrow.vector.UInt2Vector; import org.apache.arrow.vector.UInt4Vector; import org.apache.arrow.vector.UInt8Vector; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class ArrowFlightJdbcBaseIntVectorAccessorTest { +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); +public class ArrowFlightJdbcBaseIntVectorAccessorTest { - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private BaseIntVector vector; - private final Supplier vectorSupplier; private final AccessorTestUtils.AccessorSupplier accessorSupplier = @@ -89,103 +82,115 @@ public class ArrowFlightJdbcBaseIntVectorAccessorTest { }; private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); - - @Parameterized.Parameters(name = "{1}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - {(Supplier) () -> rootAllocatorTestRule.createIntVector(), "IntVector"}, - { - (Supplier) () -> rootAllocatorTestRule.createSmallIntVector(), - "SmallIntVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createTinyIntVector(), - "TinyIntVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createBigIntVector(), - "BigIntVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createUInt1Vector(), "UInt1Vector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createUInt2Vector(), "UInt2Vector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createUInt4Vector(), "UInt4Vector" - }, - {(Supplier) () -> rootAllocatorTestRule.createUInt8Vector(), "UInt8Vector"} - }); - } - - public ArrowFlightJdbcBaseIntVectorAccessorTest( - Supplier vectorSupplier, String vectorType) { - this.vectorSupplier = vectorSupplier; + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); + + public static Stream data() { + return Stream.of( + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createIntVector(), + "IntVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createSmallIntVector(), + "SmallIntVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createTinyIntVector(), + "TinyIntVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createBigIntVector(), + "BigIntVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createUInt1Vector(), + "UInt1Vector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createUInt2Vector(), + "UInt2Vector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createUInt4Vector(), + "UInt4Vector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createUInt8Vector(), + "UInt8Vector")); } - @Before - public void setup() { + public void setup(Supplier vectorSupplier) { this.vector = vectorSupplier.get(); } - @After + @AfterEach public void tearDown() { this.vector.close(); } - @Test - public void testShouldConvertToByteMethodFromBaseIntVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldConvertToByteMethodFromBaseIntVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBaseIntVectorAccessor::getByte, (accessor, currentRow) -> equalTo((byte) accessor.getLong())); } - @Test - public void testShouldConvertToShortMethodFromBaseIntVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldConvertToShortMethodFromBaseIntVector( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBaseIntVectorAccessor::getShort, (accessor, currentRow) -> equalTo((short) accessor.getLong())); } - @Test - public void testShouldConvertToIntegerMethodFromBaseIntVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldConvertToIntegerMethodFromBaseIntVector( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBaseIntVectorAccessor::getInt, (accessor, currentRow) -> equalTo((int) accessor.getLong())); } - @Test - public void testShouldConvertToFloatMethodFromBaseIntVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldConvertToFloatMethodFromBaseIntVector( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBaseIntVectorAccessor::getFloat, (accessor, currentRow) -> equalTo((float) accessor.getLong())); } - @Test - public void testShouldConvertToDoubleMethodFromBaseIntVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldConvertToDoubleMethodFromBaseIntVector( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBaseIntVectorAccessor::getDouble, (accessor, currentRow) -> equalTo((double) accessor.getLong())); } - @Test - public void testShouldConvertToBooleanMethodFromBaseIntVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldConvertToBooleanMethodFromBaseIntVector( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBaseIntVectorAccessor::getBoolean, (accessor, currentRow) -> equalTo(accessor.getLong() != 0L)); } - @Test - public void testShouldGetObjectClass() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectClass(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcBaseIntVectorAccessor::getObjectClass, equalTo(Long.class)); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorUnitTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorUnitTest.java index bd415e06904b2..e629d2f6ecd1c 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorUnitTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBaseIntVectorAccessorUnitTest.java @@ -20,7 +20,7 @@ import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.util.AutoCloseables; import org.apache.arrow.vector.BigIntVector; import org.apache.arrow.vector.IntVector; @@ -31,19 +31,20 @@ import org.apache.arrow.vector.UInt4Vector; import org.apache.arrow.vector.UInt8Vector; import org.hamcrest.CoreMatchers; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) public class ArrowFlightJdbcBaseIntVectorAccessorUnitTest { - @ClassRule public static RootAllocatorTestRule rule = new RootAllocatorTestRule(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); + private static UInt4Vector int4Vector; private static UInt8Vector int8Vector; private static IntVector intVectorWithNull; @@ -51,7 +52,6 @@ public class ArrowFlightJdbcBaseIntVectorAccessorUnitTest { private static SmallIntVector smallIntVector; private static IntVector intVector; private static BigIntVector bigIntVector; - @Rule public final ErrorCollector collector = new ErrorCollector(); private final AccessorTestUtils.AccessorSupplier accessorSupplier = @@ -87,40 +87,40 @@ public class ArrowFlightJdbcBaseIntVectorAccessorUnitTest { }; private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @BeforeClass + @BeforeAll public static void setup() { - int4Vector = new UInt4Vector("ID", rule.getRootAllocator()); + int4Vector = new UInt4Vector("ID", rootAllocatorTestExtension.getRootAllocator()); int4Vector.setSafe(0, 0x80000001); int4Vector.setValueCount(1); - int8Vector = new UInt8Vector("ID", rule.getRootAllocator()); + int8Vector = new UInt8Vector("ID", rootAllocatorTestExtension.getRootAllocator()); int8Vector.setSafe(0, 0xFFFFFFFFFFFFFFFFL); int8Vector.setValueCount(1); - intVectorWithNull = new IntVector("ID", rule.getRootAllocator()); + intVectorWithNull = new IntVector("ID", rootAllocatorTestExtension.getRootAllocator()); intVectorWithNull.setNull(0); intVectorWithNull.setValueCount(1); - tinyIntVector = new TinyIntVector("ID", rule.getRootAllocator()); + tinyIntVector = new TinyIntVector("ID", rootAllocatorTestExtension.getRootAllocator()); tinyIntVector.setSafe(0, 0xAA); tinyIntVector.setValueCount(1); - smallIntVector = new SmallIntVector("ID", rule.getRootAllocator()); + smallIntVector = new SmallIntVector("ID", rootAllocatorTestExtension.getRootAllocator()); smallIntVector.setSafe(0, 0xAABB); smallIntVector.setValueCount(1); - intVector = new IntVector("ID", rule.getRootAllocator()); + intVector = new IntVector("ID", rootAllocatorTestExtension.getRootAllocator()); intVector.setSafe(0, 0xAABBCCDD); intVector.setValueCount(1); - bigIntVector = new BigIntVector("ID", rule.getRootAllocator()); + bigIntVector = new BigIntVector("ID", rootAllocatorTestExtension.getRootAllocator()); bigIntVector.setSafe(0, 0xAABBCCDDEEFFAABBL); bigIntVector.setValueCount(1); } - @AfterClass + @AfterAll public static void tearDown() throws Exception { AutoCloseables.close( bigIntVector, @@ -130,7 +130,7 @@ public static void tearDown() throws Exception { int4Vector, int8Vector, intVectorWithNull, - rule); + rootAllocatorTestExtension); } @Test diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBitVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBitVectorAccessorTest.java index 65010d4d8ce82..20c086b26dbdc 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBitVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcBitVectorAccessorTest.java @@ -23,39 +23,38 @@ import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils.AccessorIterator; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils.CheckedFunction; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.BitVector; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcBitVectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); + private final AccessorTestUtils.AccessorSupplier accessorSupplier = (vector, getCurrentRow) -> new ArrowFlightJdbcBitVectorAccessor( (BitVector) vector, getCurrentRow, (boolean wasNull) -> {}); private final AccessorIterator accessorIterator = - new AccessorIterator<>(collector, accessorSupplier); + new AccessorIterator<>(accessorSupplier); private BitVector vector; private BitVector vectorWithNull; private boolean[] arrayToAssert; - @Before + @BeforeEach public void setup() { this.arrayToAssert = new boolean[] {false, true}; - this.vector = rootAllocatorTestRule.createBitVector(); - this.vectorWithNull = rootAllocatorTestRule.createBitVectorForNullTests(); + this.vector = rootAllocatorTestExtension.createBitVector(); + this.vectorWithNull = rootAllocatorTestExtension.createBitVectorForNullTests(); } - @After + @AfterEach public void tearDown() { this.vector.close(); this.vectorWithNull.close(); diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcDecimalVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcDecimalVectorAccessorTest.java index f779f7ede3be2..668c50a843386 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcDecimalVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcDecimalVectorAccessorTest.java @@ -20,34 +20,27 @@ import static org.hamcrest.CoreMatchers.is; import java.math.BigDecimal; -import java.util.Arrays; -import java.util.Collection; import java.util.function.Supplier; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.Decimal256Vector; import org.apache.arrow.vector.DecimalVector; import org.apache.arrow.vector.ValueVector; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@RunWith(Parameterized.class) -public class ArrowFlightJdbcDecimalVectorAccessorTest { +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); +public class ArrowFlightJdbcDecimalVectorAccessorTest { - @Rule public final ErrorCollector collector = new ErrorCollector(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); - private final Supplier vectorSupplier; private ValueVector vector; private ValueVector vectorWithNull; @@ -67,30 +60,19 @@ public class ArrowFlightJdbcDecimalVectorAccessorTest { }; private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); - - @Parameterized.Parameters(name = "{1}") - public static Collection data() { - return Arrays.asList( - new Object[][] { - { - (Supplier) () -> rootAllocatorTestRule.createDecimalVector(), - "DecimalVector" - }, - { - (Supplier) () -> rootAllocatorTestRule.createDecimal256Vector(), - "Decimal256Vector" - }, - }); - } - - public ArrowFlightJdbcDecimalVectorAccessorTest( - Supplier vectorSupplier, String vectorType) { - this.vectorSupplier = vectorSupplier; + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); + + public static Stream data() { + return Stream.of( + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createDecimalVector(), + "DecimalVector"), + Arguments.of( + (Supplier) () -> rootAllocatorTestExtension.createDecimal256Vector(), + "Decimal256Vector")); } - @Before - public void setup() { + public void setup(Supplier vectorSupplier) { this.vector = vectorSupplier.get(); this.vectorWithNull = vectorSupplier.get(); @@ -98,182 +80,247 @@ public void setup() { this.vectorWithNull.setValueCount(5); } - @After + @AfterEach public void tearDown() { this.vector.close(); this.vectorWithNull.close(); } - @Test - public void testShouldGetBigDecimalFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBigDecimalFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getBigDecimal, (accessor, currentRow) -> CoreMatchers.notNullValue()); } - @Test - public void testShouldGetDoubleMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDoubleMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getDouble, (accessor, currentRow) -> equalTo(accessor.getBigDecimal().doubleValue())); } - @Test - public void testShouldGetFloatMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetFloatMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getFloat, (accessor, currentRow) -> equalTo(accessor.getBigDecimal().floatValue())); } - @Test - public void testShouldGetLongMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetLongMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getLong, (accessor, currentRow) -> equalTo(accessor.getBigDecimal().longValue())); } - @Test - public void testShouldGetIntMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetIntMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getInt, (accessor, currentRow) -> equalTo(accessor.getBigDecimal().intValue())); } - @Test - public void testShouldGetShortMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetShortMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getShort, (accessor, currentRow) -> equalTo(accessor.getBigDecimal().shortValue())); } - @Test - public void testShouldGetByteMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetByteMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getByte, (accessor, currentRow) -> equalTo(accessor.getBigDecimal().byteValue())); } - @Test - public void testShouldGetStringMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getString, (accessor, currentRow) -> equalTo(accessor.getBigDecimal().toString())); } - @Test - public void testShouldGetBooleanMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBooleanMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getBoolean, (accessor, currentRow) -> equalTo(!accessor.getBigDecimal().equals(BigDecimal.ZERO))); } - @Test - public void testShouldGetObjectMethodFromDecimalVector() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectMethodFromDecimalVector(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getObject, (accessor, currentRow) -> equalTo(accessor.getBigDecimal())); } - @Test - public void testShouldGetObjectClass() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectClass(Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vector, ArrowFlightJdbcDecimalVectorAccessor::getObjectClass, (accessor, currentRow) -> equalTo(BigDecimal.class)); } - @Test - public void testShouldGetBigDecimalMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBigDecimalMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getBigDecimal, (accessor, currentRow) -> CoreMatchers.nullValue()); } - @Test - public void testShouldGetObjectMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getObject, (accessor, currentRow) -> CoreMatchers.nullValue()); } - @Test - public void testShouldGetStringMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetStringMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getString, (accessor, currentRow) -> CoreMatchers.nullValue()); } - @Test - public void testShouldGetByteMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetByteMethodFromDecimalVectorWithNull(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getByte, (accessor, currentRow) -> is((byte) 0)); } - @Test - public void testShouldGetShortMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetShortMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getShort, (accessor, currentRow) -> is((short) 0)); } - @Test - public void testShouldGetIntMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetIntMethodFromDecimalVectorWithNull(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getInt, (accessor, currentRow) -> is(0)); } - @Test - public void testShouldGetLongMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetLongMethodFromDecimalVectorWithNull(Supplier vectorSupplier) + throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getLong, (accessor, currentRow) -> is((long) 0)); } - @Test - public void testShouldGetFloatMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetFloatMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getFloat, (accessor, currentRow) -> is(0.0f)); } - @Test - public void testShouldGetDoubleMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetDoubleMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getDouble, (accessor, currentRow) -> is(0.0D)); } - @Test - public void testShouldGetBooleanMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBooleanMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, ArrowFlightJdbcDecimalVectorAccessor::getBoolean, (accessor, currentRow) -> is(false)); } - @Test - public void testShouldGetBigDecimalWithScaleMethodFromDecimalVectorWithNull() throws Exception { + @ParameterizedTest + @MethodSource("data") + public void testShouldGetBigDecimalWithScaleMethodFromDecimalVectorWithNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); accessorIterator.assertAccessorGetter( vectorWithNull, accessor -> accessor.getBigDecimal(2), diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat4VectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat4VectorAccessorTest.java index 4d939cd740bbe..89ebc5336dae3 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat4VectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat4VectorAccessorTest.java @@ -18,30 +18,26 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigDecimal; import java.math.RoundingMode; import java.sql.SQLException; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.Float4Vector; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcFloat4VectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); - - @Rule public ExpectedException exceptionCollector = ExpectedException.none(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private Float4Vector vector; @@ -52,14 +48,14 @@ public class ArrowFlightJdbcFloat4VectorAccessorTest { (Float4Vector) vector, getCurrentRow, (boolean wasNull) -> {}); private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @Before + @BeforeEach public void setup() { - this.vector = rootAllocatorTestRule.createFloat4Vector(); + this.vector = rootAllocatorTestExtension.createFloat4Vector(); } - @After + @AfterEach public void tearDown() { this.vector.close(); } @@ -91,7 +87,7 @@ public void testShouldGetStringMethodFromFloat4Vector() throws Exception { @Test public void testShouldGetStringMethodFromFloat4VectorWithNull() throws Exception { try (final Float4Vector float4Vector = - new Float4Vector("ID", rootAllocatorTestRule.getRootAllocator())) { + new Float4Vector("ID", rootAllocatorTestExtension.getRootAllocator())) { float4Vector.setNull(0); float4Vector.setValueCount(1); @@ -103,7 +99,7 @@ public void testShouldGetStringMethodFromFloat4VectorWithNull() throws Exception @Test public void testShouldGetFloatMethodFromFloat4VectorWithNull() throws Exception { try (final Float4Vector float4Vector = - new Float4Vector("ID", rootAllocatorTestRule.getRootAllocator())) { + new Float4Vector("ID", rootAllocatorTestExtension.getRootAllocator())) { float4Vector.setNull(0); float4Vector.setValueCount(1); @@ -115,7 +111,7 @@ public void testShouldGetFloatMethodFromFloat4VectorWithNull() throws Exception @Test public void testShouldGetBigDecimalMethodFromFloat4VectorWithNull() throws Exception { try (final Float4Vector float4Vector = - new Float4Vector("ID", rootAllocatorTestRule.getRootAllocator())) { + new Float4Vector("ID", rootAllocatorTestExtension.getRootAllocator())) { float4Vector.setNull(0); float4Vector.setValueCount(1); @@ -129,7 +125,7 @@ public void testShouldGetBigDecimalMethodFromFloat4VectorWithNull() throws Excep @Test public void testShouldGetObjectMethodFromFloat4VectorWithNull() throws Exception { try (final Float4Vector float4Vector = - new Float4Vector("ID", rootAllocatorTestRule.getRootAllocator())) { + new Float4Vector("ID", rootAllocatorTestExtension.getRootAllocator())) { float4Vector.setNull(0); float4Vector.setValueCount(1); @@ -193,9 +189,10 @@ public void testShouldGetBigDecimalMethodFromFloat4Vector() throws Exception { (accessor, currentRow) -> { float value = accessor.getFloat(); if (Float.isInfinite(value) || Float.isNaN(value)) { - exceptionCollector.expect(SQLException.class); + assertThrows(SQLException.class, accessor::getBigDecimal); + } else { + assertThat(accessor.getBigDecimal(), is(BigDecimal.valueOf(value))); } - collector.checkThat(accessor.getBigDecimal(), is(BigDecimal.valueOf(value))); }); } @@ -206,11 +203,12 @@ public void testShouldGetBigDecimalWithScaleMethodFromFloat4Vector() throws Exce (accessor, currentRow) -> { float value = accessor.getFloat(); if (Float.isInfinite(value) || Float.isNaN(value)) { - exceptionCollector.expect(SQLException.class); + assertThrows(SQLException.class, () -> accessor.getBigDecimal(9)); + } else { + assertThat( + accessor.getBigDecimal(9), + is(BigDecimal.valueOf(value).setScale(9, RoundingMode.HALF_UP))); } - collector.checkThat( - accessor.getBigDecimal(9), - is(BigDecimal.valueOf(value).setScale(9, RoundingMode.HALF_UP))); }); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat8VectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat8VectorAccessorTest.java index f2d7d1ca66f13..90870e95384ad 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat8VectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/numeric/ArrowFlightJdbcFloat8VectorAccessorTest.java @@ -18,30 +18,26 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.math.BigDecimal; import java.math.RoundingMode; import java.sql.SQLException; import org.apache.arrow.driver.jdbc.utils.AccessorTestUtils; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.vector.Float8Vector; import org.hamcrest.CoreMatchers; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class ArrowFlightJdbcFloat8VectorAccessorTest { - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - - @Rule public final ErrorCollector collector = new ErrorCollector(); - - @Rule public ExpectedException exceptionCollector = ExpectedException.none(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); private Float8Vector vector; private Float8Vector vectorWithNull; @@ -53,15 +49,15 @@ public class ArrowFlightJdbcFloat8VectorAccessorTest { (Float8Vector) vector, getCurrentRow, (boolean wasNull) -> {}); private final AccessorTestUtils.AccessorIterator - accessorIterator = new AccessorTestUtils.AccessorIterator<>(collector, accessorSupplier); + accessorIterator = new AccessorTestUtils.AccessorIterator<>(accessorSupplier); - @Before + @BeforeEach public void setup() { - this.vector = rootAllocatorTestRule.createFloat8Vector(); - this.vectorWithNull = rootAllocatorTestRule.createFloat8VectorForNullTests(); + this.vector = rootAllocatorTestExtension.createFloat8Vector(); + this.vectorWithNull = rootAllocatorTestExtension.createFloat8VectorForNullTests(); } - @After + @AfterEach public void tearDown() { this.vector.close(); this.vectorWithNull.close(); @@ -146,9 +142,10 @@ public void testShouldGetBigDecimalMethodFromFloat8Vector() throws Exception { (accessor, currentRow) -> { double value = accessor.getDouble(); if (Double.isInfinite(value) || Double.isNaN(value)) { - exceptionCollector.expect(SQLException.class); + assertThrows(SQLException.class, accessor::getBigDecimal); + } else { + assertThat(accessor.getBigDecimal(), is(BigDecimal.valueOf(value))); } - collector.checkThat(accessor.getBigDecimal(), is(BigDecimal.valueOf(value))); }); } @@ -185,11 +182,12 @@ public void testShouldGetBigDecimalWithScaleMethodFromFloat4Vector() throws Exce (accessor, currentRow) -> { double value = accessor.getDouble(); if (Double.isInfinite(value) || Double.isNaN(value)) { - exceptionCollector.expect(SQLException.class); + assertThrows(SQLException.class, () -> accessor.getBigDecimal(9)); + } else { + assertThat( + accessor.getBigDecimal(9), + is(BigDecimal.valueOf(value).setScale(9, RoundingMode.HALF_UP))); } - collector.checkThat( - accessor.getBigDecimal(9), - is(BigDecimal.valueOf(value).setScale(9, RoundingMode.HALF_UP))); }); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/text/ArrowFlightJdbcVarCharVectorAccessorTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/text/ArrowFlightJdbcVarCharVectorAccessorTest.java index 700bf4ba5982e..a2f6fd586fa5b 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/text/ArrowFlightJdbcVarCharVectorAccessorTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/text/ArrowFlightJdbcVarCharVectorAccessorTest.java @@ -22,6 +22,9 @@ import static org.apache.commons.io.IOUtils.toCharArray; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import java.io.InputStream; @@ -38,24 +41,20 @@ import org.apache.arrow.driver.jdbc.accessor.impl.calendar.ArrowFlightJdbcDateVectorAccessor; import org.apache.arrow.driver.jdbc.accessor.impl.calendar.ArrowFlightJdbcTimeStampVectorAccessor; import org.apache.arrow.driver.jdbc.accessor.impl.calendar.ArrowFlightJdbcTimeVectorAccessor; -import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestRule; +import org.apache.arrow.driver.jdbc.utils.RootAllocatorTestExtension; import org.apache.arrow.driver.jdbc.utils.ThrowableAssertionUtils; import org.apache.arrow.vector.DateMilliVector; import org.apache.arrow.vector.TimeMilliVector; import org.apache.arrow.vector.TimeStampVector; import org.apache.arrow.vector.util.Text; -import org.junit.Assert; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ArrowFlightJdbcVarCharVectorAccessorTest { private ArrowFlightJdbcVarCharVectorAccessor accessor; @@ -63,16 +62,13 @@ public class ArrowFlightJdbcVarCharVectorAccessorTest { new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); private final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSSXXX"); - @ClassRule - public static RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); @Mock private ArrowFlightJdbcVarCharVectorAccessor.Getter getter; - @Rule public ErrorCollector collector = new ErrorCollector(); - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Before + @BeforeEach public void setUp() { IntSupplier currentRowSupplier = () -> 0; accessor = @@ -85,7 +81,7 @@ public void testShouldGetStringFromNullReturnNull() { when(getter.get(0)).thenReturn(null); final String result = accessor.getString(); - collector.checkThat(result, equalTo(null)); + assertThat(result, equalTo(null)); } @Test @@ -95,8 +91,8 @@ public void testShouldGetStringReturnValidString() { final String result = accessor.getString(); - collector.checkThat(result, instanceOf(String.class)); - collector.checkThat(result, equalTo(value.toString())); + assertThat(result, instanceOf(String.class)); + assertThat(result, equalTo(value.toString())); } @Test @@ -106,35 +102,32 @@ public void testShouldGetObjectReturnValidString() { final String result = accessor.getObject(); - collector.checkThat(result, instanceOf(String.class)); - collector.checkThat(result, equalTo(value.toString())); + assertThat(result, instanceOf(String.class)); + assertThat(result, equalTo(value.toString())); } @Test - public void testShouldGetByteThrowsExceptionForNonNumericValue() throws Exception { + public void testShouldGetByteThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for byte."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getByte(); + assertThrows(SQLException.class, () -> accessor.getByte()); } @Test - public void testShouldGetByteThrowsExceptionForOutOfRangePositiveValue() throws Exception { + public void testShouldGetByteThrowsExceptionForOutOfRangePositiveValue() { Text value = new Text("128"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getByte(); + assertThrows(SQLException.class, () -> accessor.getByte()); } @Test - public void testShouldGetByteThrowsExceptionForOutOfRangeNegativeValue() throws Exception { + public void testShouldGetByteThrowsExceptionForOutOfRangeNegativeValue() { Text value = new Text("-129"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getByte(); + assertThrows(SQLException.class, () -> accessor.getByte()); } @Test @@ -144,8 +137,8 @@ public void testShouldGetByteReturnValidPositiveByte() throws Exception { byte result = accessor.getByte(); - collector.checkThat(result, instanceOf(Byte.class)); - collector.checkThat(result, equalTo((byte) 127)); + assertThat(result, instanceOf(Byte.class)); + assertThat(result, equalTo((byte) 127)); } @Test @@ -155,35 +148,32 @@ public void testShouldGetByteReturnValidNegativeByte() throws Exception { byte result = accessor.getByte(); - collector.checkThat(result, instanceOf(Byte.class)); - collector.checkThat(result, equalTo((byte) -128)); + assertThat(result, instanceOf(Byte.class)); + assertThat(result, equalTo((byte) -128)); } @Test - public void testShouldGetShortThrowsExceptionForNonNumericValue() throws Exception { + public void testShouldGetShortThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for short."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getShort(); + assertThrows(SQLException.class, () -> accessor.getShort()); } @Test - public void testShouldGetShortThrowsExceptionForOutOfRangePositiveValue() throws Exception { + public void testShouldGetShortThrowsExceptionForOutOfRangePositiveValue() { Text value = new Text("32768"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getShort(); + assertThrows(SQLException.class, () -> accessor.getShort()); } @Test - public void testShouldGetShortThrowsExceptionForOutOfRangeNegativeValue() throws Exception { + public void testShouldGetShortThrowsExceptionForOutOfRangeNegativeValue() { Text value = new Text("-32769"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getShort(); + assertThrows(SQLException.class, () -> accessor.getShort()); } @Test @@ -193,8 +183,8 @@ public void testShouldGetShortReturnValidPositiveShort() throws Exception { short result = accessor.getShort(); - collector.checkThat(result, instanceOf(Short.class)); - collector.checkThat(result, equalTo((short) 32767)); + assertThat(result, instanceOf(Short.class)); + assertThat(result, equalTo((short) 32767)); } @Test @@ -204,35 +194,32 @@ public void testShouldGetShortReturnValidNegativeShort() throws Exception { short result = accessor.getShort(); - collector.checkThat(result, instanceOf(Short.class)); - collector.checkThat(result, equalTo((short) -32768)); + assertThat(result, instanceOf(Short.class)); + assertThat(result, equalTo((short) -32768)); } @Test - public void testShouldGetIntThrowsExceptionForNonNumericValue() throws Exception { + public void testShouldGetIntThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for int."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getInt(); + assertThrows(SQLException.class, () -> accessor.getInt()); } @Test - public void testShouldGetIntThrowsExceptionForOutOfRangePositiveValue() throws Exception { + public void testShouldGetIntThrowsExceptionForOutOfRangePositiveValue() { Text value = new Text("2147483648"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getInt(); + assertThrows(SQLException.class, () -> accessor.getInt()); } @Test - public void testShouldGetIntThrowsExceptionForOutOfRangeNegativeValue() throws Exception { + public void testShouldGetIntThrowsExceptionForOutOfRangeNegativeValue() { Text value = new Text("-2147483649"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getInt(); + assertThrows(SQLException.class, () -> accessor.getInt()); } @Test @@ -242,8 +229,8 @@ public void testShouldGetIntReturnValidPositiveInteger() throws Exception { int result = accessor.getInt(); - collector.checkThat(result, instanceOf(Integer.class)); - collector.checkThat(result, equalTo(2147483647)); + assertThat(result, instanceOf(Integer.class)); + assertThat(result, equalTo(2147483647)); } @Test @@ -253,35 +240,32 @@ public void testShouldGetIntReturnValidNegativeInteger() throws Exception { int result = accessor.getInt(); - collector.checkThat(result, instanceOf(Integer.class)); - collector.checkThat(result, equalTo(-2147483648)); + assertThat(result, instanceOf(Integer.class)); + assertThat(result, equalTo(-2147483648)); } @Test - public void testShouldGetLongThrowsExceptionForNonNumericValue() throws Exception { + public void testShouldGetLongThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for long."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getLong(); + assertThrows(SQLException.class, () -> accessor.getLong()); } @Test - public void testShouldGetLongThrowsExceptionForOutOfRangePositiveValue() throws Exception { + public void testShouldGetLongThrowsExceptionForOutOfRangePositiveValue() { Text value = new Text("9223372036854775808"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getLong(); + assertThrows(SQLException.class, () -> accessor.getLong()); } @Test - public void testShouldGetLongThrowsExceptionForOutOfRangeNegativeValue() throws Exception { + public void testShouldGetLongThrowsExceptionForOutOfRangeNegativeValue() { Text value = new Text("-9223372036854775809"); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getLong(); + assertThrows(SQLException.class, () -> accessor.getLong()); } @Test @@ -291,8 +275,8 @@ public void testShouldGetLongReturnValidPositiveLong() throws Exception { long result = accessor.getLong(); - collector.checkThat(result, instanceOf(Long.class)); - collector.checkThat(result, equalTo(9223372036854775807L)); + assertThat(result, instanceOf(Long.class)); + assertThat(result, equalTo(9223372036854775807L)); } @Test @@ -302,27 +286,24 @@ public void testShouldGetLongReturnValidNegativeLong() throws Exception { long result = accessor.getLong(); - collector.checkThat(result, instanceOf(Long.class)); - collector.checkThat(result, equalTo(-9223372036854775808L)); + assertThat(result, instanceOf(Long.class)); + assertThat(result, equalTo(-9223372036854775808L)); } @Test - public void testShouldBigDecimalWithParametersThrowsExceptionForNonNumericValue() - throws Exception { + public void testShouldBigDecimalWithParametersThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for BigDecimal."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getBigDecimal(1); + assertThrows(SQLException.class, () -> accessor.getBigDecimal(1)); } @Test - public void testShouldGetBigDecimalThrowsExceptionForNonNumericValue() throws Exception { + public void testShouldGetBigDecimalThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for BigDecimal."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getBigDecimal(); + assertThrows(SQLException.class, () -> accessor.getBigDecimal()); } @Test @@ -332,8 +313,8 @@ public void testShouldGetBigDecimalReturnValidPositiveBigDecimal() throws Except BigDecimal result = accessor.getBigDecimal(); - collector.checkThat(result, instanceOf(BigDecimal.class)); - collector.checkThat(result, equalTo(new BigDecimal("9223372036854775807000.999"))); + assertThat(result, instanceOf(BigDecimal.class)); + assertThat(result, equalTo(new BigDecimal("9223372036854775807000.999"))); } @Test @@ -343,17 +324,16 @@ public void testShouldGetBigDecimalReturnValidNegativeBigDecimal() throws Except BigDecimal result = accessor.getBigDecimal(); - collector.checkThat(result, instanceOf(BigDecimal.class)); - collector.checkThat(result, equalTo(new BigDecimal("-9223372036854775807000.999"))); + assertThat(result, instanceOf(BigDecimal.class)); + assertThat(result, equalTo(new BigDecimal("-9223372036854775807000.999"))); } @Test - public void testShouldGetDoubleThrowsExceptionForNonNumericValue() throws Exception { + public void testShouldGetDoubleThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for double."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getDouble(); + assertThrows(SQLException.class, () -> accessor.getDouble()); } @Test @@ -363,8 +343,8 @@ public void testShouldGetDoubleReturnValidPositiveDouble() throws Exception { double result = accessor.getDouble(); - collector.checkThat(result, instanceOf(Double.class)); - collector.checkThat(result, equalTo(1.7976931348623157E308D)); + assertThat(result, instanceOf(Double.class)); + assertThat(result, equalTo(1.7976931348623157E308D)); } @Test @@ -374,8 +354,8 @@ public void testShouldGetDoubleReturnValidNegativeDouble() throws Exception { double result = accessor.getDouble(); - collector.checkThat(result, instanceOf(Double.class)); - collector.checkThat(result, equalTo(-1.7976931348623157E308D)); + assertThat(result, instanceOf(Double.class)); + assertThat(result, equalTo(-1.7976931348623157E308D)); } @Test @@ -385,8 +365,8 @@ public void testShouldGetDoubleWorkWithPositiveInfinity() throws Exception { double result = accessor.getDouble(); - collector.checkThat(result, instanceOf(Double.class)); - collector.checkThat(result, equalTo(Double.POSITIVE_INFINITY)); + assertThat(result, instanceOf(Double.class)); + assertThat(result, equalTo(Double.POSITIVE_INFINITY)); } @Test @@ -396,8 +376,8 @@ public void testShouldGetDoubleWorkWithNegativeInfinity() throws Exception { double result = accessor.getDouble(); - collector.checkThat(result, instanceOf(Double.class)); - collector.checkThat(result, equalTo(Double.NEGATIVE_INFINITY)); + assertThat(result, instanceOf(Double.class)); + assertThat(result, equalTo(Double.NEGATIVE_INFINITY)); } @Test @@ -407,17 +387,16 @@ public void testShouldGetDoubleWorkWithNaN() throws Exception { double result = accessor.getDouble(); - collector.checkThat(result, instanceOf(Double.class)); - collector.checkThat(result, equalTo(Double.NaN)); + assertThat(result, instanceOf(Double.class)); + assertThat(result, equalTo(Double.NaN)); } @Test - public void testShouldGetFloatThrowsExceptionForNonNumericValue() throws Exception { + public void testShouldGetFloatThrowsExceptionForNonNumericValue() { Text value = new Text("Invalid value for float."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getFloat(); + assertThrows(SQLException.class, () -> accessor.getFloat()); } @Test @@ -427,8 +406,8 @@ public void testShouldGetFloatReturnValidPositiveFloat() throws Exception { float result = accessor.getFloat(); - collector.checkThat(result, instanceOf(Float.class)); - collector.checkThat(result, equalTo(3.4028235E38F)); + assertThat(result, instanceOf(Float.class)); + assertThat(result, equalTo(3.4028235E38F)); } @Test @@ -438,8 +417,8 @@ public void testShouldGetFloatReturnValidNegativeFloat() throws Exception { float result = accessor.getFloat(); - collector.checkThat(result, instanceOf(Float.class)); - collector.checkThat(result, equalTo(-3.4028235E38F)); + assertThat(result, instanceOf(Float.class)); + assertThat(result, equalTo(-3.4028235E38F)); } @Test @@ -449,8 +428,8 @@ public void testShouldGetFloatWorkWithPositiveInfinity() throws Exception { float result = accessor.getFloat(); - collector.checkThat(result, instanceOf(Float.class)); - collector.checkThat(result, equalTo(Float.POSITIVE_INFINITY)); + assertThat(result, instanceOf(Float.class)); + assertThat(result, equalTo(Float.POSITIVE_INFINITY)); } @Test @@ -460,8 +439,8 @@ public void testShouldGetFloatWorkWithNegativeInfinity() throws Exception { float result = accessor.getFloat(); - collector.checkThat(result, instanceOf(Float.class)); - collector.checkThat(result, equalTo(Float.NEGATIVE_INFINITY)); + assertThat(result, instanceOf(Float.class)); + assertThat(result, equalTo(Float.NEGATIVE_INFINITY)); } @Test @@ -471,17 +450,16 @@ public void testShouldGetFloatWorkWithNaN() throws Exception { float result = accessor.getFloat(); - collector.checkThat(result, instanceOf(Float.class)); - collector.checkThat(result, equalTo(Float.NaN)); + assertThat(result, instanceOf(Float.class)); + assertThat(result, equalTo(Float.NaN)); } @Test - public void testShouldGetDateThrowsExceptionForNonDateValue() throws Exception { + public void testShouldGetDateThrowsExceptionForNonDateValue() { Text value = new Text("Invalid value for date."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getDate(null); + assertThrows(SQLException.class, () -> accessor.getDate(null)); } @Test @@ -491,13 +469,12 @@ public void testShouldGetDateReturnValidDateWithoutCalendar() throws Exception { Date result = accessor.getDate(null); - collector.checkThat(result, instanceOf(Date.class)); + assertThat(result, instanceOf(Date.class)); Calendar calendar = Calendar.getInstance(); calendar.setTime(result); - collector.checkThat( - dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T00:00:00.000Z")); + assertThat(dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T00:00:00.000Z")); } @Test @@ -511,17 +488,15 @@ public void testShouldGetDateReturnValidDateWithCalendar() throws Exception { calendar = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC")); calendar.setTime(result); - collector.checkThat( - dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T03:00:00.000Z")); + assertThat(dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T03:00:00.000Z")); } @Test - public void testShouldGetTimeThrowsExceptionForNonTimeValue() throws Exception { + public void testShouldGetTimeThrowsExceptionForNonTimeValue() { Text value = new Text("Invalid value for time."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getTime(null); + assertThrows(SQLException.class, () -> accessor.getTime(null)); } @Test @@ -534,7 +509,7 @@ public void testShouldGetTimeReturnValidDateWithoutCalendar() throws Exception { Calendar calendar = Calendar.getInstance(); calendar.setTime(result); - collector.checkThat(timeFormat.format(calendar.getTime()), equalTo("02:30:00.000Z")); + assertThat(timeFormat.format(calendar.getTime()), equalTo("02:30:00.000Z")); } @Test @@ -548,16 +523,15 @@ public void testShouldGetTimeReturnValidDateWithCalendar() throws Exception { calendar = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC")); calendar.setTime(result); - collector.checkThat(timeFormat.format(calendar.getTime()), equalTo("05:30:00.000Z")); + assertThat(timeFormat.format(calendar.getTime()), equalTo("05:30:00.000Z")); } @Test - public void testShouldGetTimestampThrowsExceptionForNonTimeValue() throws Exception { + public void testShouldGetTimestampThrowsExceptionForNonTimeValue() { Text value = new Text("Invalid value for timestamp."); when(getter.get(0)).thenReturn(value.copyBytes()); - thrown.expect(SQLException.class); - accessor.getTimestamp(null); + assertThrows(SQLException.class, () -> accessor.getTimestamp(null)); } @Test @@ -570,8 +544,7 @@ public void testShouldGetTimestampReturnValidDateWithoutCalendar() throws Except Calendar calendar = Calendar.getInstance(); calendar.setTime(result); - collector.checkThat( - dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T02:30:00.000Z")); + assertThat(dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T02:30:00.000Z")); } @Test @@ -585,14 +558,13 @@ public void testShouldGetTimestampReturnValidDateWithCalendar() throws Exception calendar = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC")); calendar.setTime(result); - collector.checkThat( - dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T05:30:00.000Z")); + assertThat(dateTimeFormat.format(calendar.getTime()), equalTo("2021-07-02T05:30:00.000Z")); } private void assertGetBoolean(Text value, boolean expectedResult) throws SQLException { when(getter.get(0)).thenReturn(value == null ? null : value.copyBytes()); boolean result = accessor.getBoolean(); - collector.checkThat(result, equalTo(expectedResult)); + assertThat(result, equalTo(expectedResult)); } private void assertGetBooleanForSQLException(Text value) { @@ -633,8 +605,8 @@ public void testShouldGetBytesReturnValidByteArray() { final byte[] result = accessor.getBytes(); - collector.checkThat(result, instanceOf(byte[].class)); - collector.checkThat(result, equalTo(value.toString().getBytes(UTF_8))); + assertThat(result, instanceOf(byte[].class)); + assertThat(result, equalTo(value.toString().getBytes(UTF_8))); } @Test @@ -645,7 +617,7 @@ public void testShouldGetUnicodeStreamReturnValidInputStream() throws Exception try (final InputStream result = accessor.getUnicodeStream()) { byte[] resultBytes = toByteArray(result); - collector.checkThat(new String(resultBytes, UTF_8), equalTo(value.toString())); + assertThat(new String(resultBytes, UTF_8), equalTo(value.toString())); } } @@ -658,7 +630,7 @@ public void testShouldGetAsciiStreamReturnValidInputStream() throws Exception { try (final InputStream result = accessor.getAsciiStream()) { byte[] resultBytes = toByteArray(result); - Assert.assertArrayEquals(valueAscii, resultBytes); + assertArrayEquals(valueAscii, resultBytes); } } @@ -670,13 +642,14 @@ public void testShouldGetCharacterStreamReturnValidReader() throws Exception { try (Reader result = accessor.getCharacterStream()) { char[] resultChars = toCharArray(result); - collector.checkThat(new String(resultChars), equalTo(value.toString())); + assertThat(new String(resultChars), equalTo(value.toString())); } } @Test public void testShouldGetTimeStampBeConsistentWithTimeStampAccessor() throws Exception { - try (TimeStampVector timeStampVector = rootAllocatorTestRule.createTimeStampMilliVector()) { + try (TimeStampVector timeStampVector = + rootAllocatorTestExtension.createTimeStampMilliVector()) { ArrowFlightJdbcTimeStampVectorAccessor timeStampVectorAccessor = new ArrowFlightJdbcTimeStampVectorAccessor( timeStampVector, () -> 0, (boolean wasNull) -> {}); @@ -685,13 +658,13 @@ public void testShouldGetTimeStampBeConsistentWithTimeStampAccessor() throws Exc when(getter.get(0)).thenReturn(value.copyBytes()); Timestamp timestamp = accessor.getTimestamp(null); - collector.checkThat(timestamp, equalTo(timeStampVectorAccessor.getTimestamp(null))); + assertThat(timestamp, equalTo(timeStampVectorAccessor.getTimestamp(null))); } } @Test public void testShouldGetTimeBeConsistentWithTimeAccessor() throws Exception { - try (TimeMilliVector timeVector = rootAllocatorTestRule.createTimeMilliVector()) { + try (TimeMilliVector timeVector = rootAllocatorTestExtension.createTimeMilliVector()) { ArrowFlightJdbcTimeVectorAccessor timeVectorAccessor = new ArrowFlightJdbcTimeVectorAccessor(timeVector, () -> 0, (boolean wasNull) -> {}); @@ -699,13 +672,13 @@ public void testShouldGetTimeBeConsistentWithTimeAccessor() throws Exception { when(getter.get(0)).thenReturn(value.copyBytes()); Time time = accessor.getTime(null); - collector.checkThat(time, equalTo(timeVectorAccessor.getTime(null))); + assertThat(time, equalTo(timeVectorAccessor.getTime(null))); } } @Test public void testShouldGetDateBeConsistentWithDateAccessor() throws Exception { - try (DateMilliVector dateVector = rootAllocatorTestRule.createDateMilliVector()) { + try (DateMilliVector dateVector = rootAllocatorTestExtension.createDateMilliVector()) { ArrowFlightJdbcDateVectorAccessor dateVectorAccessor = new ArrowFlightJdbcDateVectorAccessor(dateVector, () -> 0, (boolean wasNull) -> {}); @@ -713,13 +686,13 @@ public void testShouldGetDateBeConsistentWithDateAccessor() throws Exception { when(getter.get(0)).thenReturn(value.copyBytes()); Date date = accessor.getDate(null); - collector.checkThat(date, equalTo(dateVectorAccessor.getDate(null))); + assertThat(date, equalTo(dateVectorAccessor.getDate(null))); } } @Test public void testShouldGetObjectClassReturnString() { final Class clazz = accessor.getObjectClass(); - collector.checkThat(clazz, equalTo(String.class)); + assertThat(clazz, equalTo(String.class)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java index 2af2d0117b3ad..4f16a4fa60932 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerBuilderTest.java @@ -16,37 +16,39 @@ */ package org.apache.arrow.driver.jdbc.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Optional; -import org.apache.arrow.driver.jdbc.FlightServerTestRule; +import org.apache.arrow.driver.jdbc.FlightServerTestExtension; import org.apache.arrow.driver.jdbc.utils.CoreMockedSqlProducers; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.memory.RootAllocator; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; /** Test the behavior of ArrowFlightSqlClientHandler.Builder */ public class ArrowFlightSqlClientHandlerBuilderTest { - @ClassRule - public static final FlightServerTestRule FLIGHT_SERVER_TEST_RULE = - FlightServerTestRule.createStandardTestRule(CoreMockedSqlProducers.getLegacyProducer()); + + @RegisterExtension + public static final FlightServerTestExtension FLIGHT_SERVER_TEST_EXTENSION = + FlightServerTestExtension.createStandardTestExtension( + CoreMockedSqlProducers.getLegacyProducer()); private static BufferAllocator allocator; - @BeforeClass + @BeforeAll public static void setup() { allocator = new RootAllocator(Long.MAX_VALUE); } - @AfterClass + @AfterAll public static void tearDown() { allocator.close(); } @@ -56,11 +58,11 @@ public void testRetainCookiesOnAuthOff() throws Exception { // Arrange final ArrowFlightSqlClientHandler.Builder rootBuilder = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withBufferAllocator(allocator) - .withUsername(FlightServerTestRule.DEFAULT_USER) - .withPassword(FlightServerTestRule.DEFAULT_PASSWORD) + .withUsername(FlightServerTestExtension.DEFAULT_USER) + .withPassword(FlightServerTestExtension.DEFAULT_PASSWORD) .withEncryption(false) .withRetainCookies(true) .withRetainAuth(false); @@ -81,11 +83,11 @@ public void testRetainCookiesOffAuthOff() throws Exception { // Arrange final ArrowFlightSqlClientHandler.Builder rootBuilder = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withBufferAllocator(allocator) - .withUsername(FlightServerTestRule.DEFAULT_USER) - .withPassword(FlightServerTestRule.DEFAULT_PASSWORD) + .withUsername(FlightServerTestExtension.DEFAULT_USER) + .withPassword(FlightServerTestExtension.DEFAULT_PASSWORD) .withEncryption(false) .withRetainCookies(false) .withRetainAuth(false); @@ -106,11 +108,11 @@ public void testRetainCookiesOnAuthOn() throws Exception { // Arrange final ArrowFlightSqlClientHandler.Builder rootBuilder = new ArrowFlightSqlClientHandler.Builder() - .withHost(FLIGHT_SERVER_TEST_RULE.getHost()) - .withPort(FLIGHT_SERVER_TEST_RULE.getPort()) + .withHost(FLIGHT_SERVER_TEST_EXTENSION.getHost()) + .withPort(FLIGHT_SERVER_TEST_EXTENSION.getPort()) .withBufferAllocator(allocator) - .withUsername(FlightServerTestRule.DEFAULT_USER) - .withPassword(FlightServerTestRule.DEFAULT_PASSWORD) + .withUsername(FlightServerTestExtension.DEFAULT_USER) + .withPassword(FlightServerTestExtension.DEFAULT_PASSWORD) .withEncryption(false) .withRetainCookies(true) .withRetainAuth(true); diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/ClientAuthenticationUtilsTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/ClientAuthenticationUtilsTest.java index d0a8761482e47..0d1498abe4ae1 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/ClientAuthenticationUtilsTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/utils/ClientAuthenticationUtilsTest.java @@ -16,6 +16,7 @@ */ package org.apache.arrow.driver.jdbc.client.utils; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import java.io.IOException; @@ -30,15 +31,14 @@ import java.util.Collections; import java.util.Enumeration; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ClientAuthenticationUtilsTest { @Mock KeyStore keyStoreMock; @@ -68,7 +68,7 @@ public void testGetKeyStoreInstance() KeyStore receiveKeyStore = ClientAuthenticationUtils.getKeyStoreInstance("test1"); Mockito.verify(keyStoreMock).load(null, null); - Assert.assertEquals(receiveKeyStore, keyStoreMock); + assertEquals(receiveKeyStore, keyStoreMock); } } @@ -81,7 +81,7 @@ public void testGetDefaultKeyStoreInstancePassword() .when(() -> ClientAuthenticationUtils.getDefaultKeyStoreInstance("changeit")) .thenReturn(keyStoreMock); KeyStore receiveKeyStore = ClientAuthenticationUtils.getDefaultKeyStoreInstance("changeit"); - Assert.assertEquals(receiveKeyStore, keyStoreMock); + assertEquals(receiveKeyStore, keyStoreMock); } } @@ -94,7 +94,7 @@ public void testGetDefaultKeyStoreInstanceNoPassword() .when(() -> ClientAuthenticationUtils.getDefaultKeyStoreInstance(null)) .thenReturn(keyStoreMock); KeyStore receiveKeyStore = ClientAuthenticationUtils.getDefaultKeyStoreInstance(null); - Assert.assertEquals(receiveKeyStore, keyStoreMock); + assertEquals(receiveKeyStore, keyStoreMock); } } @@ -124,7 +124,7 @@ public void testGetCertificateInputStreamFromMacSystem() InputStream inputStream = ClientAuthenticationUtils.getCertificateInputStreamFromSystem("changeit"); - Assert.assertEquals(inputStream, mock); + assertEquals(inputStream, mock); } } @@ -150,7 +150,7 @@ public void testGetCertificateInputStreamFromWindowsSystem() InputStream inputStream = ClientAuthenticationUtils.getCertificateInputStreamFromSystem("test"); - Assert.assertEquals(inputStream, mock); + assertEquals(inputStream, mock); } } @@ -177,9 +177,9 @@ public void testGetCertificateInputStreamFromLinuxSystem() InputStream inputStream = ClientAuthenticationUtils.getCertificateInputStreamFromSystem("changeit"); - Assert.assertEquals(inputStream, mock); + assertEquals(inputStream, mock); inputStream = ClientAuthenticationUtils.getCertificateInputStreamFromSystem(null); - Assert.assertEquals(inputStream, mock); + assertEquals(inputStream, mock); } } @@ -212,10 +212,10 @@ private void setOperatingSystemMock( boolean isWindows, boolean isMac) { clientAuthenticationUtilsMockedStatic.when(ClientAuthenticationUtils::isMac).thenReturn(isMac); - Assert.assertEquals(ClientAuthenticationUtils.isMac(), isMac); + assertEquals(ClientAuthenticationUtils.isMac(), isMac); clientAuthenticationUtilsMockedStatic .when(ClientAuthenticationUtils::isWindows) .thenReturn(isWindows); - Assert.assertEquals(ClientAuthenticationUtils.isWindows(), isWindows); + assertEquals(ClientAuthenticationUtils.isWindows(), isWindows); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/AccessorTestUtils.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/AccessorTestUtils.java index 71ed8d3a3131f..6285cf5d25506 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/AccessorTestUtils.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/AccessorTestUtils.java @@ -17,6 +17,7 @@ package org.apache.arrow.driver.jdbc.utils; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.SQLException; import java.util.ArrayList; @@ -28,7 +29,6 @@ import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessor; import org.apache.arrow.vector.ValueVector; import org.hamcrest.Matcher; -import org.junit.rules.ErrorCollector; public class AccessorTestUtils { @FunctionalInterface @@ -70,11 +70,9 @@ public int getCurrentRow() { } public static class AccessorIterator { - private final ErrorCollector collector; private final AccessorSupplier accessorSupplier; - public AccessorIterator(ErrorCollector collector, AccessorSupplier accessorSupplier) { - this.collector = collector; + public AccessorIterator(AccessorSupplier accessorSupplier) { this.accessorSupplier = accessorSupplier; } @@ -113,8 +111,8 @@ public void assertAccessorGetter( R object = getter.apply(accessor); boolean wasNull = accessor.wasNull(); - collector.checkThat(object, matcherGetter.get(accessor, currentRow)); - collector.checkThat(wasNull, is(accessor.getObject() == null)); + assertThat(object, matcherGetter.get(accessor, currentRow)); + assertThat(wasNull, is(accessor.getObject() == null)); }); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java index 56c5f0c755b70..4a46b5f5bedb5 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionConfigImplTest.java @@ -17,7 +17,6 @@ package org.apache.arrow.driver.jdbc.utils; import static java.lang.Runtime.getRuntime; -import static java.util.Arrays.asList; import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.CATALOG; import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.HOST; import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.PASSWORD; @@ -26,94 +25,83 @@ import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.USER; import static org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty.USE_ENCRYPTION; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; -import java.util.List; import java.util.Properties; import java.util.Random; import java.util.function.Function; +import java.util.stream.Stream; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(Parameterized.class) public final class ArrowFlightConnectionConfigImplTest { private static final Random RANDOM = new Random(12L); - private final Properties properties = new Properties(); + private Properties properties; private ArrowFlightConnectionConfigImpl arrowFlightConnectionConfig; - @Rule public final ErrorCollector collector = new ErrorCollector(); - - @Parameter public ArrowFlightConnectionProperty property; - - @Parameter(value = 1) + public ArrowFlightConnectionProperty property; public Object value; - - @Parameter(value = 2) public Function arrowFlightConnectionConfigFunction; - @Before + @BeforeEach public void setUp() { + properties = new Properties(); arrowFlightConnectionConfig = new ArrowFlightConnectionConfigImpl(properties); - properties.put(property.camelName(), value); } - @Test - public void testGetProperty() { - collector.checkThat( - arrowFlightConnectionConfigFunction.apply(arrowFlightConnectionConfig), is(value)); + @ParameterizedTest + @MethodSource("provideParameters") + public void testGetProperty( + ArrowFlightConnectionProperty property, + Object value, + Function configFunction) { + properties.put(property.camelName(), value); + arrowFlightConnectionConfigFunction = configFunction; + assertThat(configFunction.apply(arrowFlightConnectionConfig), is(value)); + assertThat(arrowFlightConnectionConfigFunction.apply(arrowFlightConnectionConfig), is(value)); } - @Parameters(name = "<{0}> as <{1}>") - public static List provideParameters() { - return asList( - new Object[][] { - { + public static Stream provideParameters() { + return Stream.of( + Arguments.of( HOST, "host", - (Function) ArrowFlightConnectionConfigImpl::getHost - }, - { + (Function) + ArrowFlightConnectionConfigImpl::getHost), + Arguments.of( PORT, RANDOM.nextInt(Short.toUnsignedInt(Short.MAX_VALUE)), - (Function) ArrowFlightConnectionConfigImpl::getPort - }, - { + (Function) + ArrowFlightConnectionConfigImpl::getPort), + Arguments.of( USER, "user", - (Function) ArrowFlightConnectionConfigImpl::getUser - }, - { + (Function) + ArrowFlightConnectionConfigImpl::getUser), + Arguments.of( PASSWORD, "password", (Function) - ArrowFlightConnectionConfigImpl::getPassword - }, - { + ArrowFlightConnectionConfigImpl::getPassword), + Arguments.of( USE_ENCRYPTION, RANDOM.nextBoolean(), (Function) - ArrowFlightConnectionConfigImpl::useEncryption - }, - { + ArrowFlightConnectionConfigImpl::useEncryption), + Arguments.of( THREAD_POOL_SIZE, RANDOM.nextInt(getRuntime().availableProcessors()), (Function) - ArrowFlightConnectionConfigImpl::threadPoolSize - }, - { + ArrowFlightConnectionConfigImpl::threadPoolSize), + Arguments.of( CATALOG, "catalog", (Function) - ArrowFlightConnectionConfigImpl::getCatalog - }, - }); + ArrowFlightConnectionConfigImpl::getCatalog)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionPropertyTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionPropertyTest.java index cc403784a2e14..5929b9f94a5ef 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionPropertyTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ArrowFlightConnectionPropertyTest.java @@ -17,71 +17,76 @@ package org.apache.arrow.driver.jdbc.utils; import static org.apache.arrow.util.AutoCloseables.close; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.MockitoAnnotations.openMocks; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.arrow.driver.jdbc.utils.ArrowFlightConnectionConfigImpl.ArrowFlightConnectionProperty; -import org.junit.After; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameter; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(Parameterized.class) +@ExtendWith(MockitoExtension.class) public final class ArrowFlightConnectionPropertyTest { @Mock public Properties properties; private AutoCloseable mockitoResource; - @Parameter public ArrowFlightConnectionProperty arrowFlightConnectionProperty; + public ArrowFlightConnectionProperty arrowFlightConnectionProperty; - @Before + @BeforeEach public void setUp() { mockitoResource = openMocks(this); } - @After + @AfterEach public void tearDown() throws Exception { close(mockitoResource); } - @Test - public void testWrapIsUnsupported() { + @ParameterizedTest + @MethodSource("provideParameters") + public void testWrapIsUnsupported(ArrowFlightConnectionProperty property) { + this.arrowFlightConnectionProperty = property; ThrowableAssertionUtils.simpleAssertThrowableClass( UnsupportedOperationException.class, () -> arrowFlightConnectionProperty.wrap(properties)); } - @Test - public void testRequiredPropertyThrows() { - Assume.assumeTrue(arrowFlightConnectionProperty.required()); + @ParameterizedTest + @MethodSource("provideParameters") + public void testRequiredPropertyThrows(ArrowFlightConnectionProperty property) { + this.arrowFlightConnectionProperty = property; + assumeTrue(arrowFlightConnectionProperty.required()); ThrowableAssertionUtils.simpleAssertThrowableClass( IllegalStateException.class, () -> arrowFlightConnectionProperty.get(new Properties())); } - @Test - public void testOptionalPropertyReturnsDefault() { - Assume.assumeTrue(!arrowFlightConnectionProperty.required()); - Assert.assertEquals( + @ParameterizedTest + @MethodSource("provideParameters") + public void testOptionalPropertyReturnsDefault(ArrowFlightConnectionProperty property) { + this.arrowFlightConnectionProperty = property; + assumeTrue(!arrowFlightConnectionProperty.required()); + assertEquals( arrowFlightConnectionProperty.defaultValue(), arrowFlightConnectionProperty.get(new Properties())); } - @Parameters - public static List provideParameters() { + public static List provideParameters() { final ArrowFlightConnectionProperty[] arrowFlightConnectionProperties = ArrowFlightConnectionProperty.values(); - final List parameters = new ArrayList<>(arrowFlightConnectionProperties.length); + final List parameters = new ArrayList<>(arrowFlightConnectionProperties.length); for (final ArrowFlightConnectionProperty arrowFlightConnectionProperty : arrowFlightConnectionProperties) { - parameters.add(new Object[] {arrowFlightConnectionProperty}); + parameters.add(Arguments.of(arrowFlightConnectionProperty)); } return parameters; } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConnectionWrapperTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConnectionWrapperTest.java index a7dd6bdc6b696..b481ef43522ef 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConnectionWrapperTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConnectionWrapperTest.java @@ -23,6 +23,8 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -37,16 +39,14 @@ import org.apache.arrow.driver.jdbc.ArrowFlightConnection; import org.apache.arrow.util.AutoCloseables; import org.apache.calcite.avatica.AvaticaConnection; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public final class ConnectionWrapperTest { private static final String SCHEMA_NAME = "SCHEMA"; @@ -66,28 +66,27 @@ public final class ConnectionWrapperTest { @Mock public AvaticaConnection underlyingConnection; private ConnectionWrapper connectionWrapper; - @Rule public final ErrorCollector collector = new ErrorCollector(); - @Before + @BeforeEach public void setUp() { connectionWrapper = new ConnectionWrapper(underlyingConnection); } - @After + @AfterEach public void tearDown() throws Exception { AutoCloseables.close(connectionWrapper, underlyingConnection); } @Test public void testUnwrappingUnderlyingConnectionShouldReturnUnderlyingConnection() { - collector.checkThat( - collector.checkSucceeds(() -> connectionWrapper.unwrap(Object.class)), + assertThat( + assertDoesNotThrow(() -> connectionWrapper.unwrap(Object.class)), is(sameInstance(underlyingConnection))); - collector.checkThat( - collector.checkSucceeds(() -> connectionWrapper.unwrap(Connection.class)), + assertThat( + assertDoesNotThrow(() -> connectionWrapper.unwrap(Connection.class)), is(sameInstance(underlyingConnection))); - collector.checkThat( - collector.checkSucceeds(() -> connectionWrapper.unwrap(AvaticaConnection.class)), + assertThat( + assertDoesNotThrow(() -> connectionWrapper.unwrap(AvaticaConnection.class)), is(sameInstance(underlyingConnection))); ThrowableAssertionUtils.simpleAssertThrowableClass( ClassCastException.class, () -> connectionWrapper.unwrap(ArrowFlightConnection.class)); @@ -98,16 +97,16 @@ public void testUnwrappingUnderlyingConnectionShouldReturnUnderlyingConnection() @Test public void testCreateStatementShouldCreateStatementFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.createStatement(), is(sameInstance(verify(underlyingConnection, times(1)).createStatement()))); - collector.checkThat( + assertThat( connectionWrapper.createStatement( RESULT_SET_TYPE, RESULT_SET_CONCURRENCY, RESULT_SET_HOLDABILITY), is( verify(underlyingConnection, times(1)) .createStatement(RESULT_SET_TYPE, RESULT_SET_CONCURRENCY, RESULT_SET_HOLDABILITY))); - collector.checkThat( + assertThat( connectionWrapper.createStatement(RESULT_SET_TYPE, RESULT_SET_CONCURRENCY), is( verify(underlyingConnection, times(1)) @@ -117,12 +116,12 @@ public void testCreateStatementShouldCreateStatementFromUnderlyingConnection() @Test public void testPrepareStatementShouldPrepareStatementFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.prepareStatement(PLACEHOLDER_QUERY), is( sameInstance( verify(underlyingConnection, times(1)).prepareStatement(PLACEHOLDER_QUERY)))); - collector.checkThat( + assertThat( connectionWrapper.prepareStatement(PLACEHOLDER_QUERY, COLUMN_INDICES), is( allOf( @@ -130,7 +129,7 @@ public void testPrepareStatementShouldPrepareStatementFromUnderlyingConnection() verify(underlyingConnection, times(1)) .prepareStatement(PLACEHOLDER_QUERY, COLUMN_INDICES)), nullValue()))); - collector.checkThat( + assertThat( connectionWrapper.prepareStatement(PLACEHOLDER_QUERY, COLUMN_NAMES), is( allOf( @@ -138,7 +137,7 @@ public void testPrepareStatementShouldPrepareStatementFromUnderlyingConnection() verify(underlyingConnection, times(1)) .prepareStatement(PLACEHOLDER_QUERY, COLUMN_NAMES)), nullValue()))); - collector.checkThat( + assertThat( connectionWrapper.prepareStatement( PLACEHOLDER_QUERY, RESULT_SET_TYPE, RESULT_SET_CONCURRENCY), is( @@ -148,7 +147,7 @@ public void testPrepareStatementShouldPrepareStatementFromUnderlyingConnection() .prepareStatement( PLACEHOLDER_QUERY, RESULT_SET_TYPE, RESULT_SET_CONCURRENCY)), nullValue()))); - collector.checkThat( + assertThat( connectionWrapper.prepareStatement(PLACEHOLDER_QUERY, GENERATED_KEYS), is( allOf( @@ -160,10 +159,10 @@ public void testPrepareStatementShouldPrepareStatementFromUnderlyingConnection() @Test public void testPrepareCallShouldPrepareCallFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.prepareCall(PLACEHOLDER_QUERY), is(sameInstance(verify(underlyingConnection, times(1)).prepareCall(PLACEHOLDER_QUERY)))); - collector.checkThat( + assertThat( connectionWrapper.prepareCall(PLACEHOLDER_QUERY, RESULT_SET_TYPE, RESULT_SET_CONCURRENCY), is( verify(underlyingConnection, times(1)) @@ -172,7 +171,7 @@ public void testPrepareCallShouldPrepareCallFromUnderlyingConnection() throws SQ @Test public void testNativeSqlShouldGetNativeSqlFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.nativeSQL(PLACEHOLDER_QUERY), is(sameInstance(verify(underlyingConnection, times(1)).nativeSQL(PLACEHOLDER_QUERY)))); } @@ -187,7 +186,7 @@ public void testSetAutoCommitShouldSetAutoCommitInUnderlyingConnection() throws @Test public void testGetAutoCommitShouldGetAutoCommitFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getAutoCommit(), is(verify(underlyingConnection, times(1)).getAutoCommit())); } @@ -212,13 +211,12 @@ public void testCloseShouldCloseUnderlyingConnection() throws SQLException { @Test public void testIsClosedShouldGetStatusFromUnderlyingConnection() throws SQLException { - collector.checkThat( - connectionWrapper.isClosed(), is(verify(underlyingConnection, times(1)).isClosed())); + assertThat(connectionWrapper.isClosed(), is(verify(underlyingConnection, times(1)).isClosed())); } @Test public void testGetMetadataShouldGetMetadataFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getMetaData(), is(verify(underlyingConnection, times(1)).getMetaData())); } @@ -232,8 +230,7 @@ public void testSetReadOnlyShouldSetUnderlyingConnectionAsReadOnly() throws SQLE @Test public void testSetIsReadOnlyShouldGetStatusFromUnderlyingConnection() throws SQLException { - collector.checkThat( - connectionWrapper.isReadOnly(), is(verify(underlyingConnection).isReadOnly())); + assertThat(connectionWrapper.isReadOnly(), is(verify(underlyingConnection).isReadOnly())); } @Test @@ -245,7 +242,7 @@ public void testSetCatalogShouldSetCatalogInUnderlyingConnection() throws SQLExc @Test public void testGetCatalogShouldGetCatalogFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getCatalog(), is(allOf(sameInstance(verify(underlyingConnection, times(1)).getCatalog()), nullValue()))); } @@ -259,14 +256,14 @@ public void setTransactionIsolationShouldSetUnderlyingTransactionIsolation() thr @Test public void getTransactionIsolationShouldGetUnderlyingConnectionIsolation() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getTransactionIsolation(), is(equalTo(verify(underlyingConnection, times(1)).getTransactionIsolation()))); } @Test public void getWarningShouldGetWarningsFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getWarnings(), is(allOf(sameInstance(verify(underlyingConnection, times(1)).getWarnings()), nullValue()))); } @@ -280,7 +277,7 @@ public void testClearWarningShouldClearWarningsFromUnderlyingConnection() throws @Test public void getTypeMapShouldGetTypeMapFromUnderlyingConnection() throws SQLException { when(underlyingConnection.getTypeMap()).thenReturn(null); - collector.checkThat( + assertThat( connectionWrapper.getTypeMap(), is(verify(underlyingConnection, times(1)).getTypeMap())); } @@ -298,19 +295,19 @@ public void testSetHoldabilityShouldSetUnderlyingConnection() throws SQLExceptio @Test public void testGetHoldabilityShouldGetHoldabilityFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getHoldability(), is(equalTo(verify(underlyingConnection, times(1)).getHoldability()))); } @Test public void testSetSavepointShouldSetSavepointInUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.setSavepoint(), is( allOf( sameInstance(verify(underlyingConnection, times(1)).setSavepoint()), nullValue()))); - collector.checkThat( + assertThat( connectionWrapper.setSavepoint(SAVEPOINT_NAME), is(sameInstance(verify(underlyingConnection, times(1)).setSavepoint(SAVEPOINT_NAME)))); } @@ -330,28 +327,28 @@ public void testReleaseSavepointShouldReleaseSavepointFromUnderlyingConnection() @Test public void testCreateClobShouldCreateClobFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.createClob(), is(allOf(sameInstance(verify(underlyingConnection, times(1)).createClob()), nullValue()))); } @Test public void testCreateBlobShouldCreateBlobFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.createBlob(), is(allOf(sameInstance(verify(underlyingConnection, times(1)).createBlob()), nullValue()))); } @Test public void testCreateNClobShouldCreateNClobFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.createNClob(), is(allOf(sameInstance(verify(underlyingConnection, times(1)).createNClob()), nullValue()))); } @Test public void testCreateSQLXMLShouldCreateSQLXMLFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.createSQLXML(), is( allOf( @@ -360,7 +357,7 @@ public void testCreateSQLXMLShouldCreateSQLXMLFromUnderlyingConnection() throws @Test public void testIsValidShouldReturnWhetherUnderlyingConnectionIsValid() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.isValid(TIMEOUT), is(verify(underlyingConnection, times(1)).isValid(TIMEOUT))); } @@ -374,13 +371,13 @@ public void testSetClientInfoShouldSetClientInfoInUnderlyingConnection() @Test public void testGetClientInfoShouldGetClientInfoFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getClientInfo(CLIENT_INFO), is( allOf( sameInstance(verify(underlyingConnection, times(1)).getClientInfo(CLIENT_INFO)), nullValue()))); - collector.checkThat( + assertThat( connectionWrapper.getClientInfo(), is( allOf( @@ -391,7 +388,7 @@ public void testGetClientInfoShouldGetClientInfoFromUnderlyingConnection() throw @Test public void testCreateArrayOfShouldCreateArrayFromUnderlyingConnection() throws SQLException { final Object[] elements = range(0, 100).boxed().toArray(); - collector.checkThat( + assertThat( connectionWrapper.createArrayOf(TYPE_NAME, elements), is( allOf( @@ -403,7 +400,7 @@ public void testCreateArrayOfShouldCreateArrayFromUnderlyingConnection() throws @Test public void testCreateStructShouldCreateStructFromUnderlyingConnection() throws SQLException { final Object[] attributes = range(0, 120).boxed().toArray(); - collector.checkThat( + assertThat( connectionWrapper.createStruct(TYPE_NAME, attributes), is( allOf( @@ -420,7 +417,7 @@ public void testSetSchemaShouldSetSchemaInUnderlyingConnection() throws SQLExcep @Test public void testGetSchemaShouldGetSchemaFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getSchema(), is(allOf(sameInstance(verify(underlyingConnection, times(1)).getSchema()), nullValue()))); } @@ -441,7 +438,7 @@ public void testSetNetworkTimeoutShouldSetNetworkTimeoutInUnderlyingConnection() @Test public void testGetNetworkTimeoutShouldGetNetworkTimeoutFromUnderlyingConnection() throws SQLException { - collector.checkThat( + assertThat( connectionWrapper.getNetworkTimeout(), is(equalTo(verify(underlyingConnection, times(1)).getNetworkTimeout()))); } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConvertUtilsTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConvertUtilsTest.java index fcf4e4f1ef955..f6f549b5ed3d8 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConvertUtilsTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ConvertUtilsTest.java @@ -17,6 +17,7 @@ package org.apache.arrow.driver.jdbc.utils; import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; import com.google.common.collect.ImmutableList; import java.util.List; @@ -26,14 +27,10 @@ import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.calcite.avatica.ColumnMetaData; import org.apache.calcite.avatica.proto.Common; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.Test; public class ConvertUtilsTest { - @Rule public ErrorCollector collector = new ErrorCollector(); - @Test public void testShouldSetOnColumnMetaDataBuilder() { @@ -89,27 +86,20 @@ public void testShouldConvertArrowFieldsToColumnMetaDataList() { private void assertColumnMetaData( final List expected, final List actual) { - collector.checkThat(expected.size(), equalTo(actual.size())); + assertThat(expected.size(), equalTo(actual.size())); int size = expected.size(); for (int i = 0; i < size; i++) { final ColumnMetaData expectedColumnMetaData = expected.get(i); final ColumnMetaData actualColumnMetaData = actual.get(i); - collector.checkThat( - expectedColumnMetaData.catalogName, equalTo(actualColumnMetaData.catalogName)); - collector.checkThat( - expectedColumnMetaData.schemaName, equalTo(actualColumnMetaData.schemaName)); - collector.checkThat( - expectedColumnMetaData.tableName, equalTo(actualColumnMetaData.tableName)); - collector.checkThat(expectedColumnMetaData.readOnly, equalTo(actualColumnMetaData.readOnly)); - collector.checkThat( - expectedColumnMetaData.autoIncrement, equalTo(actualColumnMetaData.autoIncrement)); - collector.checkThat( - expectedColumnMetaData.precision, equalTo(actualColumnMetaData.precision)); - collector.checkThat(expectedColumnMetaData.scale, equalTo(actualColumnMetaData.scale)); - collector.checkThat( - expectedColumnMetaData.caseSensitive, equalTo(actualColumnMetaData.caseSensitive)); - collector.checkThat( - expectedColumnMetaData.searchable, equalTo(actualColumnMetaData.searchable)); + assertThat(expectedColumnMetaData.catalogName, equalTo(actualColumnMetaData.catalogName)); + assertThat(expectedColumnMetaData.schemaName, equalTo(actualColumnMetaData.schemaName)); + assertThat(expectedColumnMetaData.tableName, equalTo(actualColumnMetaData.tableName)); + assertThat(expectedColumnMetaData.readOnly, equalTo(actualColumnMetaData.readOnly)); + assertThat(expectedColumnMetaData.autoIncrement, equalTo(actualColumnMetaData.autoIncrement)); + assertThat(expectedColumnMetaData.precision, equalTo(actualColumnMetaData.precision)); + assertThat(expectedColumnMetaData.scale, equalTo(actualColumnMetaData.scale)); + assertThat(expectedColumnMetaData.caseSensitive, equalTo(actualColumnMetaData.caseSensitive)); + assertThat(expectedColumnMetaData.searchable, equalTo(actualColumnMetaData.searchable)); } } @@ -120,17 +110,14 @@ private void assertBuilder( final Integer precision = flightSqlColumnMetaData.getPrecision(); final Integer scale = flightSqlColumnMetaData.getScale(); - collector.checkThat( - flightSqlColumnMetaData.getCatalogName(), equalTo(builder.getCatalogName())); - collector.checkThat(flightSqlColumnMetaData.getSchemaName(), equalTo(builder.getSchemaName())); - collector.checkThat(flightSqlColumnMetaData.getTableName(), equalTo(builder.getTableName())); - collector.checkThat( - flightSqlColumnMetaData.isAutoIncrement(), equalTo(builder.getAutoIncrement())); - collector.checkThat( - flightSqlColumnMetaData.isCaseSensitive(), equalTo(builder.getCaseSensitive())); - collector.checkThat(flightSqlColumnMetaData.isSearchable(), equalTo(builder.getSearchable())); - collector.checkThat(flightSqlColumnMetaData.isReadOnly(), equalTo(builder.getReadOnly())); - collector.checkThat(precision == null ? 0 : precision, equalTo(builder.getPrecision())); - collector.checkThat(scale == null ? 0 : scale, equalTo(builder.getScale())); + assertThat(flightSqlColumnMetaData.getCatalogName(), equalTo(builder.getCatalogName())); + assertThat(flightSqlColumnMetaData.getSchemaName(), equalTo(builder.getSchemaName())); + assertThat(flightSqlColumnMetaData.getTableName(), equalTo(builder.getTableName())); + assertThat(flightSqlColumnMetaData.isAutoIncrement(), equalTo(builder.getAutoIncrement())); + assertThat(flightSqlColumnMetaData.isCaseSensitive(), equalTo(builder.getCaseSensitive())); + assertThat(flightSqlColumnMetaData.isSearchable(), equalTo(builder.getSearchable())); + assertThat(flightSqlColumnMetaData.isReadOnly(), equalTo(builder.getReadOnly())); + assertThat(precision == null ? 0 : precision, equalTo(builder.getPrecision())); + assertThat(scale == null ? 0 : scale, equalTo(builder.getScale())); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/CoreMockedSqlProducers.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/CoreMockedSqlProducers.java index 2e4092db69045..8197d7d95f09a 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/CoreMockedSqlProducers.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/CoreMockedSqlProducers.java @@ -19,6 +19,8 @@ import static java.lang.String.format; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertAll; import com.google.common.collect.ImmutableList; import java.sql.Date; @@ -50,7 +52,6 @@ import org.apache.arrow.vector.types.pojo.FieldType; import org.apache.arrow.vector.types.pojo.Schema; import org.apache.arrow.vector.util.Text; -import org.junit.rules.ErrorCollector; /** Standard {@link MockFlightSqlProducer} instances for tests. */ // TODO Remove this once all tests are refactor to use only the queries they need. @@ -286,11 +287,10 @@ private static void addLegacyCancellationSqlCmdSupport(final MockFlightSqlProduc * MockFlightSqlProducer}. * * @param resultSet the result set. - * @param collector the {@link ErrorCollector} to use. * @throws SQLException on error. */ - public static void assertLegacyRegularSqlResultSet( - final ResultSet resultSet, final ErrorCollector collector) throws SQLException { + public static void assertLegacyRegularSqlResultSet(final ResultSet resultSet) + throws SQLException { final int expectedRowCount = 50_000; final long[] expectedIds = new long[expectedRowCount]; @@ -324,12 +324,16 @@ public static void assertLegacyRegularSqlResultSet( actualHireDates.add((Date) resultSet.getObject(5)); actualLastSales.add((Timestamp) resultSet.getObject(6)); } - collector.checkThat(actualRowCount, is(equalTo(expectedRowCount))); - collector.checkThat(actualIds, is(expectedIds)); - collector.checkThat(actualNames, is(expectedNames)); - collector.checkThat(actualAges, is(expectedAges)); - collector.checkThat(actualSalaries, is(expectedSalaries)); - collector.checkThat(actualHireDates, is(expectedHireDates)); - collector.checkThat(actualLastSales, is(expectedLastSales)); + + final int finalActualRowCount = actualRowCount; + assertAll( + "ResultSet values are as expected", + () -> assertThat(finalActualRowCount, is(equalTo(expectedRowCount))), + () -> assertThat(actualIds, is(expectedIds)), + () -> assertThat(actualNames, is(expectedNames)), + () -> assertThat(actualAges, is(expectedAges)), + () -> assertThat(actualSalaries, is(expectedSalaries)), + () -> assertThat(actualHireDates, is(expectedHireDates)), + () -> assertThat(actualLastSales, is(expectedLastSales))); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/DateTimeUtilsTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/DateTimeUtilsTest.java index 8c05271c0af41..9c6635202349b 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/DateTimeUtilsTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/DateTimeUtilsTest.java @@ -17,18 +17,16 @@ package org.apache.arrow.driver.jdbc.utils; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Timestamp; import java.time.Instant; import java.util.Calendar; import java.util.TimeZone; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; +import org.junit.jupiter.api.Test; public class DateTimeUtilsTest { - @ClassRule public static final ErrorCollector collector = new ErrorCollector(); private final TimeZone defaultTimezone = TimeZone.getTimeZone("UTC"); private final TimeZone alternateTimezone = TimeZone.getTimeZone("America/Vancouver"); private final long positiveEpochMilli = 959817600000L; // 2000-06-01 00:00:00 UTC @@ -48,7 +46,7 @@ public void testShouldGetOffsetWithSameTimeZone() { final long actual = DateTimeUtils.applyCalendarOffset(epochMillis, Calendar.getInstance(defaultTimezone)); - collector.checkThat(actual, is(expected)); + assertThat(actual, is(expected)); } finally { // Reset Timezone TimeZone.setDefault(currentTimezone); @@ -69,7 +67,7 @@ public void testShouldGetOffsetWithDifferentTimeZone() { final long actualEpochMillis = DateTimeUtils.applyCalendarOffset(epochMillis, Calendar.getInstance(defaultTimezone)); - collector.checkThat(actualEpochMillis, is(expectedEpochMillis)); + assertThat(actualEpochMillis, is(expectedEpochMillis)); } finally { // Reset Timezone TimeZone.setDefault(currentTimezone); @@ -84,7 +82,7 @@ public void testShouldGetTimestampPositive() { final Timestamp expected = Timestamp.from(instant); final Timestamp actual = DateTimeUtils.getTimestampValue(epochMilli); - collector.checkThat(expected, is(actual)); + assertThat(expected, is(actual)); } @Test @@ -95,6 +93,6 @@ public void testShouldGetTimestampNegative() { final Timestamp expected = Timestamp.from(instant); final Timestamp actual = DateTimeUtils.getTimestampValue(epochMilli); - collector.checkThat(expected, is(actual)); + assertThat(expected, is(actual)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueTest.java index 9404d1d8ac294..f40610a0320ab 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/FlightEndpointDataQueueTest.java @@ -18,34 +18,33 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.mockito.Mockito.mock; import java.util.concurrent.CompletionService; import org.apache.arrow.driver.jdbc.client.CloseableEndpointStreamPair; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; /** Tests for {@link FlightEndpointDataQueue}. */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class FlightEndpointDataQueueTest { - @Rule public final ErrorCollector collector = new ErrorCollector(); @Mock private CompletionService mockedService; private FlightEndpointDataQueue queue; - @Before + @BeforeEach public void setUp() { queue = new FlightEndpointDataQueue(mockedService); } @Test public void testNextShouldRetrieveNullIfEmpty() throws Exception { - collector.checkThat(queue.next(), is(nullValue())); + assertThat(queue.next(), is(nullValue())); } @Test @@ -64,7 +63,7 @@ public void testEnqueueShouldThrowExceptionUponClose() throws Exception { @Test public void testCheckOpen() throws Exception { - collector.checkSucceeds( + assertDoesNotThrow( () -> { queue.checkOpen(); return true; @@ -76,8 +75,8 @@ public void testCheckOpen() throws Exception { @Test public void testShouldCloseQueue() throws Exception { - collector.checkThat(queue.isClosed(), is(false)); + assertThat(queue.isClosed(), is(false)); queue.close(); - collector.checkThat(queue.isClosed(), is(true)); + assertThat(queue.isClosed(), is(true)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ResultSetTestUtils.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ResultSetTestUtils.java index 20d1315d7a1a3..bcefbf68bc25b 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ResultSetTestUtils.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/ResultSetTestUtils.java @@ -18,25 +18,19 @@ import static java.util.stream.IntStream.range; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.function.Function; -import org.apache.arrow.util.Preconditions; -import org.junit.rules.ErrorCollector; /** * Utility class for testing that require asserting that the values in a {@link ResultSet} are * expected. */ public final class ResultSetTestUtils { - private final ErrorCollector collector; - - public ResultSetTestUtils(final ErrorCollector collector) { - this.collector = Preconditions.checkNotNull(collector, "Error collector cannot be null."); - } /** * Checks that the values (rows and columns) in the provided {@link ResultSet} are expected. @@ -44,21 +38,15 @@ public ResultSetTestUtils(final ErrorCollector collector) { * @param resultSet the {@code ResultSet} to assert. * @param expectedResults the rows and columns representing the only values the {@code resultSet} * is expected to have. - * @param collector the {@link ErrorCollector} to use for asserting that the {@code resultSet} has - * the expected values. * @param the type to be found in the expected results for the {@code resultSet}. * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. */ - public static void testData( - final ResultSet resultSet, - final List> expectedResults, - final ErrorCollector collector) + public static void testData(final ResultSet resultSet, final List> expectedResults) throws SQLException { testData( resultSet, range(1, resultSet.getMetaData().getColumnCount() + 1).toArray(), - expectedResults, - collector); + expectedResults); } /** @@ -68,8 +56,6 @@ public static void testData( * @param columnNames the column names to fetch in the {@code ResultSet} for comparison. * @param expectedResults the rows and columns representing the only values the {@code resultSet} * is expected to have. - * @param collector the {@link ErrorCollector} to use for asserting that the {@code resultSet} has - * the expected values. * @param the type to be found in the expected results for the {@code resultSet}. * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. */ @@ -77,8 +63,7 @@ public static void testData( public static void testData( final ResultSet resultSet, final List columnNames, - final List> expectedResults, - final ErrorCollector collector) + final List> expectedResults) throws SQLException { testData( resultSet, @@ -88,13 +73,12 @@ public static void testData( try { columns.add((T) resultSet.getObject(columnName)); } catch (final SQLException e) { - collector.addError(e); + throw new RuntimeException(e); } } return columns; }, - expectedResults, - collector); + expectedResults); } /** @@ -104,17 +88,12 @@ public static void testData( * @param columnIndices the column indices to fetch in the {@code ResultSet} for comparison. * @param expectedResults the rows and columns representing the only values the {@code resultSet} * is expected to have. - * @param collector the {@link ErrorCollector} to use for asserting that the {@code resultSet} has - * the expected values. * @param the type to be found in the expected results for the {@code resultSet}. * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. */ @SuppressWarnings("unchecked") public static void testData( - final ResultSet resultSet, - final int[] columnIndices, - final List> expectedResults, - final ErrorCollector collector) + final ResultSet resultSet, final int[] columnIndices, final List> expectedResults) throws SQLException { testData( resultSet, @@ -124,13 +103,12 @@ public static void testData( try { columns.add((T) resultSet.getObject(columnIndex)); } catch (final SQLException e) { - collector.addError(e); + throw new RuntimeException(e); } } return columns; }, - expectedResults, - collector); + expectedResults); } /** @@ -140,89 +118,18 @@ public static void testData( * @param dataConsumer the column indices to fetch in the {@code ResultSet} for comparison. * @param expectedResults the rows and columns representing the only values the {@code resultSet} * is expected to have. - * @param collector the {@link ErrorCollector} to use for asserting that the {@code resultSet} has - * the expected values. * @param the type to be found in the expected results for the {@code resultSet}. * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. */ public static void testData( final ResultSet resultSet, final Function> dataConsumer, - final List> expectedResults, - final ErrorCollector collector) + final List> expectedResults) throws SQLException { final List> actualResults = new ArrayList<>(); while (resultSet.next()) { actualResults.add(dataConsumer.apply(resultSet)); } - collector.checkThat(actualResults, is(expectedResults)); - } - - /** - * Checks that the values (rows and columns) in the provided {@link ResultSet} are expected. - * - * @param resultSet the {@code ResultSet} to assert. - * @param expectedResults the rows and columns representing the only values the {@code resultSet} - * is expected to have. - * @param the type to be found in the expected results for the {@code resultSet}. - * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. - */ - public void testData(final ResultSet resultSet, final List> expectedResults) - throws SQLException { - testData(resultSet, expectedResults, collector); - } - - /** - * Checks that the values (rows and columns) in the provided {@link ResultSet} are expected. - * - * @param resultSet the {@code ResultSet} to assert. - * @param columnNames the column names to fetch in the {@code ResultSet} for comparison. - * @param expectedResults the rows and columns representing the only values the {@code resultSet} - * is expected to have. - * @param the type to be found in the expected results for the {@code resultSet}. - * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. - */ - @SuppressWarnings("unchecked") - public void testData( - final ResultSet resultSet, - final List columnNames, - final List> expectedResults) - throws SQLException { - testData(resultSet, columnNames, expectedResults, collector); - } - - /** - * Checks that the values (rows and columns) in the provided {@link ResultSet} are expected. - * - * @param resultSet the {@code ResultSet} to assert. - * @param columnIndices the column indices to fetch in the {@code ResultSet} for comparison. - * @param expectedResults the rows and columns representing the only values the {@code resultSet} - * is expected to have. - * @param the type to be found in the expected results for the {@code resultSet}. - * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. - */ - @SuppressWarnings("unchecked") - public void testData( - final ResultSet resultSet, final int[] columnIndices, final List> expectedResults) - throws SQLException { - testData(resultSet, columnIndices, expectedResults, collector); - } - - /** - * Checks that the values (rows and columns) in the provided {@link ResultSet} are expected. - * - * @param resultSet the {@code ResultSet} to assert. - * @param dataConsumer the column indices to fetch in the {@code ResultSet} for comparison. - * @param expectedResults the rows and columns representing the only values the {@code resultSet} - * is expected to have. - * @param the type to be found in the expected results for the {@code resultSet}. - * @throws SQLException if querying the {@code ResultSet} fails at some point unexpectedly. - */ - public void testData( - final ResultSet resultSet, - final Function> dataConsumer, - final List> expectedResults) - throws SQLException { - testData(resultSet, dataConsumer, expectedResults, collector); + assertThat(actualResults, is(expectedResults)); } } diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/RootAllocatorTestRule.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/RootAllocatorTestExtension.java similarity index 98% rename from java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/RootAllocatorTestRule.java rename to java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/RootAllocatorTestExtension.java index 8e834616380b9..347e92a16c4e5 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/RootAllocatorTestRule.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/RootAllocatorTestExtension.java @@ -60,11 +60,12 @@ import org.apache.arrow.vector.complex.impl.UnionFixedSizeListWriter; import org.apache.arrow.vector.complex.impl.UnionLargeListWriter; import org.apache.arrow.vector.complex.impl.UnionListWriter; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; -public class RootAllocatorTestRule implements TestRule, AutoCloseable { +public class RootAllocatorTestExtension + implements BeforeAllCallback, AfterAllCallback, AutoCloseable { public static final byte MAX_VALUE = Byte.MAX_VALUE; private final BufferAllocator rootAllocator = new RootAllocator(); @@ -72,17 +73,17 @@ public class RootAllocatorTestRule implements TestRule, AutoCloseable { private final Random random = new Random(10); @Override - public Statement apply(Statement base, Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - try { - base.evaluate(); - } finally { - close(); - } - } - }; + public void beforeAll(ExtensionContext context) { + // no-op + } + + @Override + public void afterAll(ExtensionContext context) { + try { + close(); + } catch (Exception e) { + throw new RuntimeException(e); + } } public BufferAllocator getRootAllocator() { diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/SqlTypesTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/SqlTypesTest.java index bd8ea1c4d101b..00af3c96ba054 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/SqlTypesTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/SqlTypesTest.java @@ -18,7 +18,7 @@ import static org.apache.arrow.driver.jdbc.utils.SqlTypes.getSqlTypeIdFromArrowType; import static org.apache.arrow.driver.jdbc.utils.SqlTypes.getSqlTypeNameFromArrowType; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.sql.Types; import org.apache.arrow.vector.types.DateUnit; @@ -27,7 +27,7 @@ import org.apache.arrow.vector.types.TimeUnit; import org.apache.arrow.vector.types.UnionMode; import org.apache.arrow.vector.types.pojo.ArrowType; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SqlTypesTest { diff --git a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/VectorSchemaRootTransformerTest.java b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/VectorSchemaRootTransformerTest.java index a2cb8e4e8f497..a4499ab0aa1c1 100644 --- a/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/VectorSchemaRootTransformerTest.java +++ b/java/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/utils/VectorSchemaRootTransformerTest.java @@ -16,6 +16,11 @@ */ package org.apache.arrow.driver.jdbc.utils; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + import com.google.common.collect.ImmutableList; import java.util.List; import java.util.stream.Collectors; @@ -29,20 +34,22 @@ import org.apache.arrow.vector.types.pojo.ArrowType; import org.apache.arrow.vector.types.pojo.Field; import org.apache.arrow.vector.types.pojo.Schema; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; public class VectorSchemaRootTransformerTest { - @Rule public RootAllocatorTestRule rootAllocatorTestRule = new RootAllocatorTestRule(); - private final BufferAllocator rootAllocator = rootAllocatorTestRule.getRootAllocator(); + @RegisterExtension + public static RootAllocatorTestExtension rootAllocatorTestExtension = + new RootAllocatorTestExtension(); + + private final BufferAllocator rootAllocator = rootAllocatorTestExtension.getRootAllocator(); @Test public void testTransformerBuilderWorksCorrectly() throws Exception { - final VarBinaryVector field1 = rootAllocatorTestRule.createVarBinaryVector("FIELD_1"); - final VarBinaryVector field2 = rootAllocatorTestRule.createVarBinaryVector("FIELD_2"); - final VarBinaryVector field3 = rootAllocatorTestRule.createVarBinaryVector("FIELD_3"); + final VarBinaryVector field1 = rootAllocatorTestExtension.createVarBinaryVector("FIELD_1"); + final VarBinaryVector field2 = rootAllocatorTestExtension.createVarBinaryVector("FIELD_2"); + final VarBinaryVector field3 = rootAllocatorTestExtension.createVarBinaryVector("FIELD_3"); try (final VectorSchemaRoot originalRoot = VectorSchemaRoot.of(field1, field2, field3); final VectorSchemaRoot clonedRoot = cloneVectorSchemaRoot(originalRoot)) { @@ -65,11 +72,11 @@ public void testTransformerBuilderWorksCorrectly() throws Exception { Field.nullable("FIELD_2_RENAMED", new ArrowType.Binary()), Field.nullable("FIELD_1_RENAMED", new ArrowType.Binary()))); try (final VectorSchemaRoot transformedRoot = createVectorSchemaRoot(transformedSchema)) { - Assert.assertSame(transformedRoot, transformer.transform(clonedRoot, transformedRoot)); - Assert.assertEquals(transformedSchema, transformedRoot.getSchema()); + assertSame(transformedRoot, transformer.transform(clonedRoot, transformedRoot)); + assertEquals(transformedSchema, transformedRoot.getSchema()); final int rowCount = originalRoot.getRowCount(); - Assert.assertEquals(rowCount, transformedRoot.getRowCount()); + assertEquals(rowCount, transformedRoot.getRowCount()); final VarBinaryVector originalField1 = (VarBinaryVector) originalRoot.getVector("FIELD_1"); final VarBinaryVector originalField2 = (VarBinaryVector) originalRoot.getVector("FIELD_2"); @@ -84,10 +91,10 @@ public void testTransformerBuilderWorksCorrectly() throws Exception { final FieldVector emptyField = transformedRoot.getVector("EMPTY_FIELD"); for (int i = 0; i < rowCount; i++) { - Assert.assertArrayEquals(originalField1.getObject(i), transformedField1.getObject(i)); - Assert.assertArrayEquals(originalField2.getObject(i), transformedField2.getObject(i)); - Assert.assertArrayEquals(originalField3.getObject(i), transformedField3.getObject(i)); - Assert.assertNull(emptyField.getObject(i)); + assertArrayEquals(originalField1.getObject(i), transformedField1.getObject(i)); + assertArrayEquals(originalField2.getObject(i), transformedField2.getObject(i)); + assertArrayEquals(originalField3.getObject(i), transformedField3.getObject(i)); + assertNull(emptyField.getObject(i)); } } } diff --git a/java/flight/flight-sql-jdbc-driver/src/test/java/org/apache/arrow/driver/jdbc/ITDriverJarValidation.java b/java/flight/flight-sql-jdbc-driver/src/test/java/org/apache/arrow/driver/jdbc/ITDriverJarValidation.java index 570f8cf8a1c58..c258b568112a9 100644 --- a/java/flight/flight-sql-jdbc-driver/src/test/java/org/apache/arrow/driver/jdbc/ITDriverJarValidation.java +++ b/java/flight/flight-sql-jdbc-driver/src/test/java/org/apache/arrow/driver/jdbc/ITDriverJarValidation.java @@ -16,8 +16,9 @@ */ package org.apache.arrow.driver.jdbc; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import com.google.common.collect.ImmutableSet; import java.io.File; @@ -29,12 +30,8 @@ import java.util.concurrent.TimeUnit; import java.util.jar.JarEntry; import java.util.jar.JarFile; -import org.junit.ClassRule; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.junit.rules.TestRule; -import org.junit.rules.Timeout; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; /** * Check the content of the JDBC driver jar @@ -79,13 +76,8 @@ private static JarFile getJdbcJarFile() throws IOException { return connection.getJarFile(); } - @ClassRule - public static final TestRule CLASS_TIMEOUT = - Timeout.builder().withTimeout(2, TimeUnit.MINUTES).build(); - - @Rule public ErrorCollector collector = new ErrorCollector(); - @Test + @Timeout(value = 2, unit = TimeUnit.MINUTES) public void validateShadedJar() throws IOException { // Validate the content of the jar to enforce all 3rd party dependencies have // been shaded @@ -100,7 +92,7 @@ public void validateShadedJar() throws IOException { try { checkEntryAllowed(entry.getName()); } catch (AssertionError e) { - collector.addError(e); + fail(e.getMessage()); } } } @@ -113,7 +105,7 @@ public void validateShadedJar() throws IOException { * allowed prefixes * * @param name the jar entry name - * @throws AssertionException if the entry is not allowed + * @throws AssertionError if the entry is not allowed */ private void checkEntryAllowed(String name) { // Check if there's a matching file entry first diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java index 9f008c8d9e88f..8387834947283 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSql.java @@ -25,6 +25,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -67,7 +68,6 @@ import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; @@ -216,7 +216,7 @@ public void testGetTablesResultNoSchema() throws Exception { try (final FlightStream stream = sqlClient.getStream( sqlClient.getTables(null, null, null, null, false).getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> { MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_TABLES_SCHEMA_NO_SCHEMA)); @@ -268,7 +268,7 @@ public void testGetTablesResultFilteredNoSchema() throws Exception { .get(0) .getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_TABLES_SCHEMA_NO_SCHEMA)), @@ -293,7 +293,7 @@ public void testGetTablesResultFilteredWithSchema() throws Exception { .getEndpoints() .get(0) .getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_TABLES_SCHEMA)), @@ -447,7 +447,7 @@ public void testGetTablesResultFilteredWithSchema() throws Exception { @Test public void testSimplePreparedStatementSchema() throws Exception { try (final PreparedStatement preparedStatement = sqlClient.prepare("SELECT * FROM intTable")) { - Assertions.assertAll( + assertAll( () -> { final Schema actualSchema = preparedStatement.getResultSetSchema(); MatcherAssert.assertThat(actualSchema, is(SCHEMA_INT_TABLE)); @@ -464,7 +464,7 @@ public void testSimplePreparedStatementResults() throws Exception { try (final PreparedStatement preparedStatement = sqlClient.prepare("SELECT * FROM intTable"); final FlightStream stream = sqlClient.getStream(preparedStatement.execute().getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), () -> MatcherAssert.assertThat( @@ -489,7 +489,7 @@ public void testSimplePreparedStatementResultsWithParameterBinding() throws Exce FlightStream stream = sqlClient.getStream(flightInfo.getEndpoints().get(0).getTicket()); - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), () -> MatcherAssert.assertThat( @@ -530,7 +530,7 @@ public void testSimplePreparedStatementUpdateResults() throws SQLException { deletePrepare.setParameters(deleteRoot); deletedRows = deletePrepare.executeUpdate(); } - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(updatedRows, is(10L)), () -> MatcherAssert.assertThat(deletedRows, is(10L))); } @@ -547,7 +547,7 @@ public void testSimplePreparedStatementUpdateResultsWithoutParameters() throws S final long deletedRows = deletePrepare.executeUpdate(); - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(updatedRows, is(1L)), () -> MatcherAssert.assertThat(deletedRows, is(1L))); } @@ -556,7 +556,7 @@ public void testSimplePreparedStatementUpdateResultsWithoutParameters() throws S @Test public void testSimplePreparedStatementClosesProperly() { final PreparedStatement preparedStatement = sqlClient.prepare("SELECT * FROM intTable"); - Assertions.assertAll( + assertAll( () -> { MatcherAssert.assertThat(preparedStatement.isClosed(), is(false)); }, @@ -577,7 +577,7 @@ public void testGetCatalogsSchema() { public void testGetCatalogsResults() throws Exception { try (final FlightStream stream = sqlClient.getStream(sqlClient.getCatalogs().getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_CATALOGS_SCHEMA)), @@ -600,7 +600,7 @@ public void testGetTableTypesSchema() { public void testGetTableTypesResult() throws Exception { try (final FlightStream stream = sqlClient.getStream(sqlClient.getTableTypes().getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> { MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_TABLE_TYPES_SCHEMA)); @@ -630,7 +630,7 @@ public void testGetSchemasSchema() { public void testGetSchemasResult() throws Exception { try (final FlightStream stream = sqlClient.getStream(sqlClient.getSchemas(null, null).getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> { MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_SCHEMAS_SCHEMA)); @@ -663,11 +663,11 @@ public void testGetPrimaryKey() { final List> results = getResults(stream); - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(results.size(), is(1)), () -> { final List result = results.get(0); - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(result.get(0), is("")), () -> MatcherAssert.assertThat(result.get(1), is("APP")), () -> MatcherAssert.assertThat(result.get(2), is("INTTABLE")), @@ -688,7 +688,7 @@ public void testGetSqlInfoSchema() { public void testGetSqlInfoResults() throws Exception { final FlightInfo info = sqlClient.getSqlInfo(); try (final FlightStream stream = sqlClient.getStream(info.getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_SQL_INFO_SCHEMA)), @@ -703,7 +703,7 @@ public void testGetSqlInfoResultsWithSingleArg() throws Exception { final FlightSql.SqlInfo arg = FlightSql.SqlInfo.FLIGHT_SQL_SERVER_NAME; final FlightInfo info = sqlClient.getSqlInfo(arg); try (final FlightStream stream = sqlClient.getStream(info.getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_SQL_INFO_SCHEMA)), @@ -732,7 +732,7 @@ public void testGetSqlInfoResultsWithManyArgs() throws Exception { }; final FlightInfo info = sqlClient.getSqlInfo(args); try (final FlightStream stream = sqlClient.getStream(info.getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_SQL_INFO_SCHEMA)), @@ -771,13 +771,13 @@ public void testGetCommandExportedKeys() throws Exception { is("3")); // delete_rule final List assertions = new ArrayList<>(); - Assertions.assertEquals(1, results.size()); + assertEquals(1, results.size()); for (int i = 0; i < matchers.size(); i++) { final String actual = results.get(0).get(i); final Matcher expected = matchers.get(i); assertions.add(() -> MatcherAssert.assertThat(actual, expected)); } - Assertions.assertAll(assertions); + assertAll(assertions); } } @@ -809,14 +809,14 @@ public void testGetCommandImportedKeys() throws Exception { is("3"), // update_rule is("3")); // delete_rule - Assertions.assertEquals(1, results.size()); + assertEquals(1, results.size()); final List assertions = new ArrayList<>(); for (int i = 0; i < matchers.size(); i++) { final String actual = results.get(0).get(i); final Matcher expected = matchers.get(i); assertions.add(() -> MatcherAssert.assertThat(actual, expected)); } - Assertions.assertAll(assertions); + assertAll(assertions); } } @@ -1334,14 +1334,14 @@ public void testGetCommandCrossReference() throws Exception { is("3"), // update_rule is("3")); // delete_rule - Assertions.assertEquals(1, results.size()); + assertEquals(1, results.size()); final List assertions = new ArrayList<>(); for (int i = 0; i < matchers.size(); i++) { final String actual = results.get(0).get(i); final Matcher expected = matchers.get(i); assertions.add(() -> MatcherAssert.assertThat(actual, expected)); } - Assertions.assertAll(assertions); + assertAll(assertions); } } @@ -1363,7 +1363,7 @@ public void testCreateStatementResults() throws Exception { try (final FlightStream stream = sqlClient.getStream( sqlClient.execute("SELECT * FROM intTable").getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> { MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)); }, @@ -1376,7 +1376,7 @@ public void testCreateStatementResults() throws Exception { @Test public void testExecuteUpdate() { - Assertions.assertAll( + assertAll( () -> { long insertedCount = sqlClient.executeUpdate( @@ -1404,7 +1404,7 @@ public void testQueryWithNoResultsShouldNotHang() throws Exception { sqlClient.prepare("SELECT * FROM intTable WHERE 1 = 0"); final FlightStream stream = sqlClient.getStream(preparedStatement.execute().getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), () -> { final List> result = getResults(stream); @@ -1419,7 +1419,7 @@ public void testCancelFlightInfo() { CancelFlightInfoRequest request = new CancelFlightInfoRequest(info); FlightRuntimeException fre = assertThrows(FlightRuntimeException.class, () -> sqlClient.cancelFlightInfo(request)); - Assertions.assertEquals(FlightStatusCode.UNIMPLEMENTED, fre.status().code()); + assertEquals(FlightStatusCode.UNIMPLEMENTED, fre.status().code()); } @Test diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java index 8e54e22ab28fe..36d621ad64c6a 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStateless.java @@ -18,7 +18,8 @@ import static org.apache.arrow.flight.sql.util.FlightStreamUtils.getResults; import static org.apache.arrow.util.AutoCloseables.close; -import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.jupiter.api.Assertions.assertAll; import org.apache.arrow.flight.FlightClient; import org.apache.arrow.flight.FlightEndpoint; @@ -35,7 +36,6 @@ import org.apache.arrow.vector.types.pojo.Schema; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -88,7 +88,7 @@ public void testSimplePreparedStatementResultsWithParameterBinding() throws Exce for (FlightEndpoint endpoint : flightInfo.getEndpoints()) { try (FlightStream stream = sqlClient.getStream(endpoint.getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(stream.getSchema(), is(SCHEMA_INT_TABLE)), () -> MatcherAssert.assertThat( diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStreams.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStreams.java index f4e636af91462..71c0dc88e4ec2 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStreams.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/test/TestFlightSqlStreams.java @@ -23,6 +23,7 @@ import static org.apache.arrow.util.AutoCloseables.close; import static org.apache.arrow.vector.types.Types.MinorType.INT; import static org.hamcrest.CoreMatchers.is; +import static org.junit.jupiter.api.Assertions.assertAll; import com.google.common.collect.ImmutableList; import com.google.protobuf.Any; @@ -54,7 +55,6 @@ import org.apache.arrow.vector.util.Text; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -243,7 +243,7 @@ public void testGetTablesResultNoSchema() throws Exception { try (final FlightStream stream = sqlClient.getStream( sqlClient.getTables(null, null, null, null, false).getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_TABLES_SCHEMA_NO_SCHEMA)), @@ -262,7 +262,7 @@ public void testGetTablesResultNoSchema() throws Exception { public void testGetTableTypesResult() throws Exception { try (final FlightStream stream = sqlClient.getStream(sqlClient.getTableTypes().getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_TABLE_TYPES_SCHEMA)), @@ -281,7 +281,7 @@ public void testGetTableTypesResult() throws Exception { public void testGetSqlInfoResults() throws Exception { final FlightInfo info = sqlClient.getSqlInfo(); try (final FlightStream stream = sqlClient.getStream(info.getEndpoints().get(0).getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat( stream.getSchema(), is(FlightSqlProducer.Schemas.GET_SQL_INFO_SCHEMA)), @@ -316,7 +316,7 @@ public void testExecuteQuery() throws Exception { .getEndpoints() .get(0) .getTicket())) { - Assertions.assertAll( + assertAll( () -> MatcherAssert.assertThat(stream.getSchema(), is(FlightSqlTestProducer.FIXED_SCHEMA)), () -> diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskCreationTest.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskCreationTest.java index 70f11985a357a..3e7552a0a39f3 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskCreationTest.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskCreationTest.java @@ -21,9 +21,9 @@ import static org.apache.arrow.flight.sql.util.AdhocTestOption.OPTION_B; import static org.apache.arrow.flight.sql.util.AdhocTestOption.OPTION_C; import static org.apache.arrow.flight.sql.util.SqlInfoOptionsUtils.createBitmaskFromEnums; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -47,6 +47,6 @@ public static List provideParameters() { @MethodSource("provideParameters") public void testShouldBuildBitmaskFromEnums( AdhocTestOption[] adhocTestOptions, long expectedBitmask) { - Assertions.assertEquals(createBitmaskFromEnums(adhocTestOptions), expectedBitmask); + assertEquals(createBitmaskFromEnums(adhocTestOptions), expectedBitmask); } } diff --git a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskParsingTest.java b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskParsingTest.java index 45406bd0f8e58..f3bac067edcb2 100644 --- a/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskParsingTest.java +++ b/java/flight/flight-sql/src/test/java/org/apache/arrow/flight/sql/util/SqlInfoOptionsUtilsBitmaskParsingTest.java @@ -23,11 +23,11 @@ import static org.apache.arrow.flight.sql.util.AdhocTestOption.OPTION_B; import static org.apache.arrow.flight.sql.util.AdhocTestOption.OPTION_C; import static org.apache.arrow.flight.sql.util.SqlInfoOptionsUtils.doesBitmaskTranslateToEnum; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.EnumSet; import java.util.List; import java.util.Set; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -55,6 +55,6 @@ public void testShouldFilterOutEnumsBasedOnBitmask( stream(AdhocTestOption.values()) .filter(enumInstance -> doesBitmaskTranslateToEnum(enumInstance, bitmask)) .collect(toCollection(() -> EnumSet.noneOf(AdhocTestOption.class))); - Assertions.assertEquals(actualOptions, expectedOptions); + assertEquals(actualOptions, expectedOptions); } }