http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/remote/KerberosConnectionTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/KerberosConnectionTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/remote/KerberosConnectionTest.java deleted file mode 100644 index ad98569..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/KerberosConnectionTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.remote; - -import org.apache.calcite.avatica.remote.KerberosConnection.RenewalTask; - -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.File; -import java.util.Locale; -import java.util.Map.Entry; - -import javax.security.auth.Subject; -import javax.security.auth.login.Configuration; -import javax.security.auth.login.LoginContext; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.nullable; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Test case for KerberosConnection - */ -public class KerberosConnectionTest { - - @Test(expected = NullPointerException.class) public void testNullArgs() { - new KerberosConnection(null, null); - } - - @Test public void testThreadConfiguration() { - KerberosConnection krbUtil = new KerberosConnection("foo", new File("/bar.keytab")); - Subject subject = new Subject(); - LoginContext context = Mockito.mock(LoginContext.class); - - Entry<RenewalTask, Thread> entry = krbUtil.createRenewalThread(context, subject, 10); - assertNotNull("RenewalTask should not be null", entry.getKey()); - Thread t = entry.getValue(); - assertTrue("Thread name should contain 'Avatica', but is '" + t.getName() + "'", - t.getName().contains("Avatica")); - assertTrue(t.isDaemon()); - assertNotNull(t.getUncaughtExceptionHandler()); - } - - @Test public void noPreviousContextOnLogin() throws Exception { - KerberosConnection krbUtil = mock(KerberosConnection.class); - Subject subject = new Subject(); - Subject loggedInSubject = new Subject(); - Configuration conf = mock(Configuration.class); - LoginContext context = mock(LoginContext.class); - - // Call the real login(LoginContext, Configuration, Subject) method - when(krbUtil.login(nullable(LoginContext.class), any(Configuration.class), any(Subject.class))) - .thenCallRealMethod(); - // Return a fake LoginContext - when(krbUtil.createLoginContext(conf)).thenReturn(context); - // Return a fake Subject from that fake LoginContext - when(context.getSubject()).thenReturn(loggedInSubject); - - Entry<LoginContext, Subject> pair = krbUtil.login(null, conf, subject); - - // Verify we get the fake LoginContext and Subject - assertEquals(context, pair.getKey()); - assertEquals(loggedInSubject, pair.getValue()); - - // login should be called on the LoginContext - verify(context).login(); - } - - @Test public void previousContextLoggedOut() throws Exception { - KerberosConnection krbUtil = mock(KerberosConnection.class); - Subject subject = new Subject(); - Subject loggedInSubject = new Subject(); - Configuration conf = mock(Configuration.class); - LoginContext originalContext = mock(LoginContext.class); - LoginContext context = mock(LoginContext.class); - - // Call the real login(LoginContext, Configuration, Subject) method - when(krbUtil.login(any(LoginContext.class), any(Configuration.class), any(Subject.class))) - .thenCallRealMethod(); - // Return a fake LoginContext - when(krbUtil.createLoginContext(conf)).thenReturn(context); - // Return a fake Subject from that fake LoginContext - when(context.getSubject()).thenReturn(loggedInSubject); - - Entry<LoginContext, Subject> pair = krbUtil.login(originalContext, conf, subject); - - // Verify we get the fake LoginContext and Subject - assertEquals(context, pair.getKey()); - assertEquals(loggedInSubject, pair.getValue()); - - verify(originalContext).logout(); - - // login should be called on the LoginContext - verify(context).login(); - } - - @Test public void testTicketRenewalTime() { - RenewalTask renewal = mock(RenewalTask.class); - when(renewal.shouldRenew(any(long.class), any(long.class), any(long.class))) - .thenCallRealMethod(); - - long start = 0; - long end = 200; - long now = 100; - assertFalse(renewal.shouldRenew(start, end, now)); - - // Renewal should happen at 80% - start = 0; - end = 100; - now = 80; - assertTrue(renewal.shouldRenew(start, end, now)); - - start = 5000; - // One day - end = start + 1000 * 60 * 60 * 24; - // Ten minutes prior to expiration - now = end - 1000 * 60 * 10; - assertTrue( - String.format(Locale.ROOT, "start=%d, end=%d, now=%d", start, end, now), - renewal.shouldRenew(start, end, now)); - } -} - -// End KerberosConnectionTest.java
http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/remote/MetaDataOperationTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/MetaDataOperationTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/remote/MetaDataOperationTest.java deleted file mode 100644 index c64b32c..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/MetaDataOperationTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.remote; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@link MetaDataOperation} - */ -public class MetaDataOperationTest { - - @Test - public void testProtobufSerialization() { - for (MetaDataOperation metadataOp : MetaDataOperation.values()) { - assertEquals(metadataOp, MetaDataOperation.fromProto(metadataOp.toProto())); - } - } - -} - -// End MetaDataOperationTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufHandlerTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufHandlerTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufHandlerTest.java deleted file mode 100644 index afb15c3..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufHandlerTest.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.remote; - -import org.apache.calcite.avatica.Meta; -import org.apache.calcite.avatica.Meta.Frame; -import org.apache.calcite.avatica.metrics.noop.NoopMetricsSystem; -import org.apache.calcite.avatica.proto.Common; -import org.apache.calcite.avatica.proto.Common.ColumnValue; -import org.apache.calcite.avatica.proto.Requests; -import org.apache.calcite.avatica.proto.Responses; -import org.apache.calcite.avatica.remote.Handler.HandlerResponse; -import org.apache.calcite.avatica.remote.Service.FetchRequest; -import org.apache.calcite.avatica.remote.Service.FetchResponse; -import org.apache.calcite.avatica.remote.Service.RpcMetadataResponse; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -/** - * Test basic serialization of objects with protocol buffers. - */ -public class ProtobufHandlerTest { - - // Mocks - private Service service; - private ProtobufTranslation translation; - - // Real objects - private ProtobufHandler handler; - - @Before - public void setupMocks() { - // Mocks - service = Mockito.mock(Service.class); - translation = Mockito.mock(ProtobufTranslation.class); - - // Real objects - handler = new ProtobufHandler(service, translation, NoopMetricsSystem.getInstance()); - } - - @Test - public void testFetch() throws Exception { - final String connectionId = "cnxn1"; - final int statementId = 30; - final long offset = 10; - final int fetchMaxRowCount = 100; - final List<Common.TypedValue> values = new ArrayList<>(); - - values.add(Common.TypedValue.newBuilder().setType(Common.Rep.BOOLEAN).setBoolValue(true) - .build()); - values.add(Common.TypedValue.newBuilder().setType(Common.Rep.STRING) - .setStringValue("my_string").build()); - - Requests.FetchRequest protoRequest = Requests.FetchRequest.newBuilder() - .setConnectionId(connectionId).setStatementId(statementId) - .setOffset(offset).setFetchMaxRowCount(fetchMaxRowCount) - .build(); - byte[] serializedRequest = protoRequest.toByteArray(); - - FetchRequest request = new FetchRequest().deserialize(protoRequest); - - List<Object> frameRows = new ArrayList<>(); - frameRows.add(new Object[] {true, "my_string"}); - - Meta.Frame frame = Frame.create(0, true, frameRows); - RpcMetadataResponse metadata = new RpcMetadataResponse("localhost:8765"); - FetchResponse response = new FetchResponse(frame, false, false, metadata); - - when(translation.parseRequest(serializedRequest)).thenReturn(request); - when(service.apply(request)).thenReturn(response); - when(translation.serializeResponse(response)) - .thenReturn(response.serialize().toByteArray()); - - HandlerResponse<byte[]> handlerResponse = handler.apply(serializedRequest); - byte[] serializedResponse = handlerResponse.getResponse(); - assertEquals(200, handlerResponse.getStatusCode()); - - Responses.FetchResponse protoResponse = Responses.FetchResponse.parseFrom(serializedResponse); - - Common.Frame protoFrame = protoResponse.getFrame(); - - assertEquals(frame.offset, protoFrame.getOffset()); - assertEquals(frame.done, protoFrame.getDone()); - - List<Common.Row> rows = protoFrame.getRowsList(); - assertEquals(1, rows.size()); - Common.Row row = rows.get(0); - List<Common.ColumnValue> columnValues = row.getValueList(); - assertEquals(2, columnValues.size()); - - Iterator<Common.ColumnValue> iter = columnValues.iterator(); - assertTrue(iter.hasNext()); - Common.ColumnValue column = iter.next(); - assertTrue("The Column should have contained a scalar: " + column, - column.hasField(ColumnValue.getDescriptor() - .findFieldByNumber(ColumnValue.SCALAR_VALUE_FIELD_NUMBER))); - - Common.TypedValue value = column.getScalarValue(); - assertEquals(Common.Rep.BOOLEAN, value.getType()); - assertEquals(true, value.getBoolValue()); - - assertTrue(iter.hasNext()); - column = iter.next(); - assertTrue("The Column should have contained a scalar: " + column, - column.hasField(ColumnValue.getDescriptor() - .findFieldByNumber(ColumnValue.SCALAR_VALUE_FIELD_NUMBER))); - value = column.getScalarValue(); - assertEquals(Common.Rep.STRING, value.getType()); - assertEquals("my_string", value.getStringValue()); - } - -} - -// End ProtobufHandlerTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufSerializationTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufSerializationTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufSerializationTest.java deleted file mode 100644 index 39787dd..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufSerializationTest.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.remote; - -import org.apache.calcite.avatica.AvaticaUtils; -import org.apache.calcite.avatica.ColumnMetaData.Rep; -import org.apache.calcite.avatica.Meta.Signature; -import org.apache.calcite.avatica.Meta.StatementHandle; -import org.apache.calcite.avatica.proto.Common.WireMessage; -import org.apache.calcite.avatica.proto.Requests; -import org.apache.calcite.avatica.remote.Service.Request; - -import com.google.protobuf.UnsafeByteOperations; - -import org.junit.Assert; -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; - -import static org.junit.Assert.assertEquals; - -/** - * Protobuf serialization tests. - */ -public class ProtobufSerializationTest { - - private Signature getSignature() { - return null; - } - - private List<TypedValue> getTypedValues() { - List<TypedValue> paramValues = - Arrays.asList(TypedValue.create(Rep.BOOLEAN.name(), Boolean.TRUE), - TypedValue.create(Rep.STRING.name(), "string")); - return paramValues; - } - - @Test public void testExecuteSerialization() throws Exception { - Service.ExecuteRequest executeRequest = new Service.ExecuteRequest( - new StatementHandle("connection", 12345, getSignature()), getTypedValues(), 0); - - Requests.ExecuteRequest pbExecuteRequest = executeRequest.serialize(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); - pbExecuteRequest.writeTo(baos); - - byte[] serialized = baos.toByteArray(); - baos.reset(); - WireMessage wireMsg = WireMessage.newBuilder().setName(Requests.ExecuteRequest.class.getName()) - .setWrappedMessage(UnsafeByteOperations.unsafeWrap(serialized)).build(); - wireMsg.writeTo(baos); - serialized = baos.toByteArray(); - - ProtobufTranslation translator = new ProtobufTranslationImpl(); - - Request newRequest = translator.parseRequest(serialized); - - Assert.assertEquals(executeRequest, newRequest); - } - - @Test public void testPrepareSerialization() throws Exception { - final String sql = "SELECT * FROM FOO"; - final String connectionId = UUID.randomUUID().toString(); - - for (long maxRowCount : Arrays.asList(-1L, 0L, 1L, Long.MAX_VALUE)) { - Service.PrepareRequest prepareReq = new Service.PrepareRequest(connectionId, sql, - maxRowCount); - - Requests.PrepareRequest prepareProtoReq = prepareReq.serialize(); - assertEquals(maxRowCount, prepareProtoReq.getMaxRowCount()); - assertEquals(maxRowCount, prepareProtoReq.getMaxRowsTotal()); - - assertEquals(prepareReq, prepareReq.deserialize(prepareProtoReq)); - } - } - - @Test public void testPrepareDeserialization() throws Exception { - final String sql = "SELECT * FROM FOO"; - final String connectionId = UUID.randomUUID().toString(); - final long maxRowCount = 200L; - - // The "current" serialization strategy. - Requests.PrepareRequest protoPrepare = Requests.PrepareRequest.newBuilder(). - setConnectionId(connectionId).setSql(sql).setMaxRowsTotal(maxRowCount).build(); - - Service.PrepareRequest prepareReq = new Service.PrepareRequest().deserialize(protoPrepare); - assertEquals(maxRowCount, prepareReq.maxRowCount); - - // The "old" serialization strategy. - protoPrepare = Requests.PrepareRequest.newBuilder(). - setConnectionId(connectionId).setSql(sql).setMaxRowCount(maxRowCount).build(); - - prepareReq = new Service.PrepareRequest().deserialize(protoPrepare); - assertEquals(maxRowCount, prepareReq.maxRowCount); - - // Both the new and old provided should default to the new - protoPrepare = Requests.PrepareRequest.newBuilder(). - setConnectionId(connectionId).setSql(sql).setMaxRowCount(500L) - .setMaxRowsTotal(maxRowCount).build(); - - prepareReq = new Service.PrepareRequest().deserialize(protoPrepare); - assertEquals(maxRowCount, prepareReq.maxRowCount); - } - - @Test public void testPrepareAndExecuteSerialization() throws Exception { - final String sql = "SELECT * FROM FOO"; - final int statementId = 12345; - final String connectionId = UUID.randomUUID().toString(); - - for (long maxRowCount : Arrays.asList(-1L, 0L, 1L, Long.MAX_VALUE)) { - Service.PrepareAndExecuteRequest prepareAndExecuteReq = - new Service.PrepareAndExecuteRequest(connectionId, statementId, sql, maxRowCount); - - Requests.PrepareAndExecuteRequest prepareAndExecuteProtoReq = - prepareAndExecuteReq.serialize(); - assertEquals(maxRowCount, prepareAndExecuteProtoReq.getMaxRowCount()); - assertEquals(maxRowCount, prepareAndExecuteProtoReq.getMaxRowsTotal()); - assertEquals(AvaticaUtils.toSaturatedInt(maxRowCount), - prepareAndExecuteProtoReq.getFirstFrameMaxSize()); - - assertEquals(prepareAndExecuteReq, - prepareAndExecuteReq.deserialize(prepareAndExecuteProtoReq)); - } - - int maxRowsInFirstFrame = 50; - for (long maxRowCount : Arrays.asList(-1L, 0L, 1L, Long.MAX_VALUE)) { - Service.PrepareAndExecuteRequest prepareAndExecuteReq = - new Service.PrepareAndExecuteRequest(connectionId, statementId, sql, maxRowCount, - maxRowsInFirstFrame); - - Requests.PrepareAndExecuteRequest prepareAndExecuteProtoReq = - prepareAndExecuteReq.serialize(); - assertEquals(maxRowCount, prepareAndExecuteProtoReq.getMaxRowCount()); - assertEquals(maxRowCount, prepareAndExecuteProtoReq.getMaxRowsTotal()); - assertEquals(maxRowsInFirstFrame, prepareAndExecuteProtoReq.getFirstFrameMaxSize()); - - assertEquals(prepareAndExecuteReq, - prepareAndExecuteReq.deserialize(prepareAndExecuteProtoReq)); - } - } - - @Test public void testPrepareAndExecuteDeserialization() throws Exception { - final String sql = "SELECT * FROM FOO"; - final String connectionId = UUID.randomUUID().toString(); - final long maxRowCount = 200L; - final int maxRowsInFirstFrame = 50; - - // The "current" serialization strategy (maxRowsTotal and firstFrameMaxSize) - Requests.PrepareAndExecuteRequest protoPrepare = Requests.PrepareAndExecuteRequest.newBuilder(). - setConnectionId(connectionId).setSql(sql).setMaxRowsTotal(maxRowCount). - setFirstFrameMaxSize(maxRowsInFirstFrame).build(); - - Service.PrepareAndExecuteRequest prepareAndExecuteReq = new Service.PrepareAndExecuteRequest(). - deserialize(protoPrepare); - assertEquals(maxRowCount, prepareAndExecuteReq.maxRowCount); - assertEquals(maxRowsInFirstFrame, prepareAndExecuteReq.maxRowsInFirstFrame); - - // The "old" serialization strategy (maxRowCount) - protoPrepare = Requests.PrepareAndExecuteRequest.newBuilder(). - setConnectionId(connectionId).setSql(sql).setMaxRowCount(maxRowCount).build(); - - prepareAndExecuteReq = new Service.PrepareAndExecuteRequest().deserialize(protoPrepare); - assertEquals(maxRowCount, prepareAndExecuteReq.maxRowCount); - assertEquals(AvaticaUtils.toSaturatedInt(maxRowCount), - prepareAndExecuteReq.maxRowsInFirstFrame); - - // Both the new and old provided should default to the new (firstFrameMaxSize should be the - // the same as what ultimately is set to maxRowCount) - protoPrepare = Requests.PrepareAndExecuteRequest.newBuilder(). - setConnectionId(connectionId).setSql(sql).setMaxRowCount(500L) - .setMaxRowsTotal(maxRowCount).build(); - - prepareAndExecuteReq = new Service.PrepareAndExecuteRequest().deserialize(protoPrepare); - assertEquals(maxRowCount, prepareAndExecuteReq.maxRowCount); - assertEquals(AvaticaUtils.toSaturatedInt(maxRowCount), - prepareAndExecuteReq.maxRowsInFirstFrame); - - // Same as previous example, but explicitly setting maxRowsInFirstFrame too - protoPrepare = Requests.PrepareAndExecuteRequest.newBuilder(). - setConnectionId(connectionId).setSql(sql).setMaxRowCount(500L) - .setMaxRowsTotal(maxRowCount).setFirstFrameMaxSize(maxRowsInFirstFrame).build(); - - prepareAndExecuteReq = new Service.PrepareAndExecuteRequest().deserialize(protoPrepare); - assertEquals(maxRowCount, prepareAndExecuteReq.maxRowCount); - assertEquals(maxRowsInFirstFrame, prepareAndExecuteReq.maxRowsInFirstFrame); - } - - @Test public void testFetchRequestSerialization() throws Exception { - final String connectionId = UUID.randomUUID().toString(); - final int statementId = 12345; - final long offset = 0L; - - for (int maxRowCount : Arrays.asList(-1, 0, 1, Integer.MAX_VALUE)) { - Service.FetchRequest fetchReq = new Service.FetchRequest(connectionId, statementId, - offset, maxRowCount); - - Requests.FetchRequest fetchProtoReq = fetchReq.serialize(); - assertEquals(maxRowCount, fetchProtoReq.getFetchMaxRowCount()); - assertEquals(maxRowCount, fetchProtoReq.getFrameMaxSize()); - - assertEquals(fetchReq, fetchReq.deserialize(fetchProtoReq)); - } - } - - @Test public void testFetchRequestDeserialization() throws Exception { - final String connectionId = UUID.randomUUID().toString(); - final int statementId = 12345; - final long offset = 0L; - final int maxSize = 200; - - // The "current" serialization strategy. - Requests.FetchRequest protoFetch = Requests.FetchRequest.newBuilder(). - setConnectionId(connectionId).setStatementId(statementId). - setOffset(offset).setFrameMaxSize(maxSize).build(); - - Service.FetchRequest fetchReq = new Service.FetchRequest().deserialize(protoFetch); - assertEquals(maxSize, fetchReq.fetchMaxRowCount); - - // The "old" serialization strategy. - protoFetch = Requests.FetchRequest.newBuilder(). - setConnectionId(connectionId).setStatementId(statementId). - setOffset(offset).setFetchMaxRowCount(maxSize).build(); - - fetchReq = new Service.FetchRequest().deserialize(protoFetch); - assertEquals(maxSize, fetchReq.fetchMaxRowCount); - - // Both the new and old provided should default to the new - protoFetch = Requests.FetchRequest.newBuilder(). - setConnectionId(connectionId).setStatementId(statementId). - setOffset(offset).setFetchMaxRowCount(100).setFrameMaxSize(maxSize).build(); - - fetchReq = new Service.FetchRequest().deserialize(protoFetch); - assertEquals(maxSize, fetchReq.fetchMaxRowCount); - } -} - -// End ProtobufSerializationTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufServiceTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufServiceTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufServiceTest.java deleted file mode 100644 index a29ee34..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufServiceTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.remote; - -import org.apache.calcite.avatica.proto.Requests; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -/** - * Test class for ProtobufService. - */ -public class ProtobufServiceTest { - - @Test public void testCastProtobufMessage() { - final Requests.CommitRequest commitReq = - Requests.CommitRequest.newBuilder().setConnectionId("cnxn1").build(); - final Requests.RollbackRequest rollbackReq = - Requests.RollbackRequest.newBuilder().setConnectionId("cnxn1").build(); - - assertEquals(commitReq, - ProtobufService.castProtobufMessage(commitReq, Requests.CommitRequest.class)); - assertEquals(rollbackReq, - ProtobufService.castProtobufMessage(rollbackReq, Requests.RollbackRequest.class)); - - try { - ProtobufService.castProtobufMessage(commitReq, Requests.RollbackRequest.class); - fail("Should have seen IllegalArgumentException casting CommitRequest into RollbackRequest"); - } catch (IllegalArgumentException e) { - // Expected - } - - try { - ProtobufService.castProtobufMessage(rollbackReq, Requests.CommitRequest.class); - fail("Should have seen IllegalArgumentException casting RollbackRequest into CommitRequest"); - } catch (IllegalArgumentException e) { - // Expected - } - } -} - -// End ProtobufServiceTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufTranslationImplTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufTranslationImplTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufTranslationImplTest.java deleted file mode 100644 index ebb2df4..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/ProtobufTranslationImplTest.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.remote; - -import org.apache.calcite.avatica.AvaticaParameter; -import org.apache.calcite.avatica.AvaticaSeverity; -import org.apache.calcite.avatica.ColumnMetaData; -import org.apache.calcite.avatica.ColumnMetaData.ArrayType; -import org.apache.calcite.avatica.ColumnMetaData.Rep; -import org.apache.calcite.avatica.ColumnMetaData.ScalarType; -import org.apache.calcite.avatica.ConnectionPropertiesImpl; -import org.apache.calcite.avatica.Meta; -import org.apache.calcite.avatica.Meta.Frame; -import org.apache.calcite.avatica.Meta.Signature; -import org.apache.calcite.avatica.Meta.Style; -import org.apache.calcite.avatica.MetaImpl; -import org.apache.calcite.avatica.QueryState; -import org.apache.calcite.avatica.remote.Service.CatalogsRequest; -import org.apache.calcite.avatica.remote.Service.CloseConnectionRequest; -import org.apache.calcite.avatica.remote.Service.CloseConnectionResponse; -import org.apache.calcite.avatica.remote.Service.CloseStatementRequest; -import org.apache.calcite.avatica.remote.Service.CloseStatementResponse; -import org.apache.calcite.avatica.remote.Service.ColumnsRequest; -import org.apache.calcite.avatica.remote.Service.CommitRequest; -import org.apache.calcite.avatica.remote.Service.CommitResponse; -import org.apache.calcite.avatica.remote.Service.ConnectionSyncRequest; -import org.apache.calcite.avatica.remote.Service.ConnectionSyncResponse; -import org.apache.calcite.avatica.remote.Service.CreateStatementRequest; -import org.apache.calcite.avatica.remote.Service.CreateStatementResponse; -import org.apache.calcite.avatica.remote.Service.DatabasePropertyRequest; -import org.apache.calcite.avatica.remote.Service.DatabasePropertyResponse; -import org.apache.calcite.avatica.remote.Service.ErrorResponse; -import org.apache.calcite.avatica.remote.Service.ExecuteBatchResponse; -import org.apache.calcite.avatica.remote.Service.ExecuteResponse; -import org.apache.calcite.avatica.remote.Service.FetchRequest; -import org.apache.calcite.avatica.remote.Service.FetchResponse; -import org.apache.calcite.avatica.remote.Service.OpenConnectionRequest; -import org.apache.calcite.avatica.remote.Service.OpenConnectionResponse; -import org.apache.calcite.avatica.remote.Service.PrepareAndExecuteBatchRequest; -import org.apache.calcite.avatica.remote.Service.PrepareAndExecuteRequest; -import org.apache.calcite.avatica.remote.Service.PrepareRequest; -import org.apache.calcite.avatica.remote.Service.PrepareResponse; -import org.apache.calcite.avatica.remote.Service.Request; -import org.apache.calcite.avatica.remote.Service.Response; -import org.apache.calcite.avatica.remote.Service.ResultSetResponse; -import org.apache.calcite.avatica.remote.Service.RollbackRequest; -import org.apache.calcite.avatica.remote.Service.RollbackResponse; -import org.apache.calcite.avatica.remote.Service.RpcMetadataResponse; -import org.apache.calcite.avatica.remote.Service.SchemasRequest; -import org.apache.calcite.avatica.remote.Service.SyncResultsRequest; -import org.apache.calcite.avatica.remote.Service.SyncResultsResponse; -import org.apache.calcite.avatica.remote.Service.TableTypesRequest; -import org.apache.calcite.avatica.remote.Service.TablesRequest; -import org.apache.calcite.avatica.remote.Service.TypeInfoRequest; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.sql.DatabaseMetaData; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -/** - * Tests serialization of requests and response objects. - * - * @param <T> The object class being tested - */ -@RunWith(Parameterized.class) -public class ProtobufTranslationImplTest<T> { - - /** - * Simple function definition that acts as an identity. - * - * @param <A> Argument type - */ - private interface IdentityFunction<A> { - A apply(A obj) throws IOException; - } - - /** - * Identity function that accepts a request, serializes it to protobuf, and converts it back. - */ - private static class RequestFunc implements IdentityFunction<Request> { - private final ProtobufTranslation translation; - - public RequestFunc(ProtobufTranslation translation) { - this.translation = translation; - } - - public Request apply(Request request) throws IOException { - // Serialize and then re-parse the request - return translation.parseRequest(translation.serializeRequest(request)); - } - } - - /** - * Identity function that accepts a response, serializes it to protobuf, and converts it back. - */ - private static class ResponseFunc implements IdentityFunction<Response> { - private final ProtobufTranslation translation; - - public ResponseFunc(ProtobufTranslation translation) { - this.translation = translation; - } - - public Response apply(Response response) throws IOException { - // Serialize and then re-pare the response - return translation.parseResponse(translation.serializeResponse(response)); - } - } - - @Parameters - public static List<Object[]> parameters() { - List<Object[]> params = new ArrayList<>(); - - // The impl we're testing - ProtobufTranslationImpl translation = new ProtobufTranslationImpl(); - - // Identity transformation for Requests - RequestFunc requestFunc = new RequestFunc(translation); - // Identity transformation for Responses - ResponseFunc responseFunc = new ResponseFunc(translation); - - List<Request> requests = getRequests(); - List<Request> requestsWithNulls = getRequestsWithNulls(); - List<Response> responses = getResponses(); - - // Requests - for (Request request : requests) { - params.add(new Object[] {request, requestFunc}); - } - - // Requests with nulls in parameters - for (Request request : requestsWithNulls) { - params.add(new Object[] {request, requestFunc}); - } - - // Responses - for (Response response : responses) { - params.add(new Object[] {response, responseFunc}); - } - - return params; - } - - /** - * Generates a collection of Requests whose serialization will be tested. - */ - private static List<Request> getRequests() { - LinkedList<Request> requests = new LinkedList<>(); - - requests.add(new CatalogsRequest()); - requests.add(new DatabasePropertyRequest()); - requests.add(new SchemasRequest("connectionId", "catalog", "schemaPattern")); - requests.add( - new TablesRequest("connectionId", "catalog", "schemaPattern", "tableNamePattern", - Arrays.asList("STRING", "BOOLEAN", "INT"))); - requests.add(new TableTypesRequest()); - requests.add( - new ColumnsRequest("connectionId", "catalog", "schemaPattern", "tableNamePattern", - "columnNamePattern")); - requests.add(new TypeInfoRequest()); - requests.add( - new PrepareAndExecuteRequest("connectionId", Integer.MAX_VALUE, "sql", - Long.MAX_VALUE)); - requests.add(new PrepareRequest("connectionId", "sql", Long.MAX_VALUE)); - - List<TypedValue> paramValues = - Arrays.asList(TypedValue.create(Rep.BOOLEAN.name(), Boolean.TRUE), - TypedValue.create(Rep.STRING.name(), "string")); - FetchRequest fetchRequest = new FetchRequest("connectionId", Integer.MAX_VALUE, - Long.MAX_VALUE, Integer.MAX_VALUE); - requests.add(fetchRequest); - - requests.add(new CreateStatementRequest("connectionId")); - requests.add(new CloseStatementRequest("connectionId", Integer.MAX_VALUE)); - Map<String, String> info = new HashMap<>(); - info.put("param1", "value1"); - info.put("param2", "value2"); - requests.add(new OpenConnectionRequest("connectionId", info)); - requests.add(new CloseConnectionRequest("connectionId")); - requests.add( - new ConnectionSyncRequest("connectionId", - new ConnectionPropertiesImpl(Boolean.FALSE, Boolean.FALSE, - Integer.MAX_VALUE, "catalog", "schema"))); - - requests.add(new SyncResultsRequest("connectionId", 12345, getSqlQueryState(), 150)); - requests.add(new SyncResultsRequest("connectionId2", 54321, getMetadataQueryState1(), 0)); - requests.add(new SyncResultsRequest("connectionId3", 5, getMetadataQueryState2(), 10)); - - requests.add(new CommitRequest("connectionId")); - requests.add(new RollbackRequest("connectionId")); - - // ExecuteBatchRequest omitted because of the special protobuf conversion it does - - List<String> commands = Arrays.asList("command1", "command2", "command3"); - requests.add(new PrepareAndExecuteBatchRequest("connectionId", 12345, commands)); - - return requests; - } - - private static QueryState getSqlQueryState() { - return new QueryState("SELECT * from TABLE"); - } - - private static QueryState getMetadataQueryState1() { - return new QueryState(MetaDataOperation.GET_COLUMNS, new Object[] { - "", - null, - "%", - "%" - }); - } - - private static QueryState getMetadataQueryState2() { - return new QueryState(MetaDataOperation.GET_CATALOGS, new Object[0]); - } - - private static List<Request> getRequestsWithNulls() { - LinkedList<Request> requests = new LinkedList<>(); - - // We're pretty fast and loose on what can be null. - requests.add(new SchemasRequest(null, null, null)); - // Repeated fields default to an empty list - requests.add(new TablesRequest(null, null, null, null, Collections.<String>emptyList())); - requests.add(new ColumnsRequest(null, null, null, null, null)); - requests.add(new PrepareAndExecuteRequest(null, 0, null, 0)); - requests.add(new PrepareRequest(null, null, 0)); - requests.add(new CreateStatementRequest(null)); - requests.add(new CloseStatementRequest(null, 0)); - requests.add(new OpenConnectionRequest(null, null)); - requests.add(new CloseConnectionRequest(null)); - requests.add(new ConnectionSyncRequest(null, null)); - - return requests; - } - - private static ColumnMetaData getArrayColumnMetaData(ScalarType componentType, int index, - String name) { - ArrayType arrayType = ColumnMetaData.array(componentType, "Array", Rep.ARRAY); - return new ColumnMetaData( - index, false, true, false, false, DatabaseMetaData.columnNullable, - true, -1, name, name, null, - 0, 0, null, null, arrayType, true, false, false, - "ARRAY"); - } - - /** - * Generates a collection of Responses whose serialization will be tested. - */ - private static List<Response> getResponses() { - final RpcMetadataResponse rpcMetadata = new RpcMetadataResponse("localhost:8765"); - LinkedList<Response> responses = new LinkedList<>(); - - // Nested classes (Signature, ColumnMetaData, CursorFactory, etc) are implicitly getting tested) - - // Stub out the metadata for a row - ScalarType arrayComponentType = ColumnMetaData.scalar(Types.INTEGER, "integer", Rep.INTEGER); - ColumnMetaData arrayColumnMetaData = getArrayColumnMetaData(arrayComponentType, 2, "counts"); - List<ColumnMetaData> columns = - Arrays.asList(MetaImpl.columnMetaData("str", 0, String.class, true), - MetaImpl.columnMetaData("count", 1, Integer.class, true), - arrayColumnMetaData); - List<AvaticaParameter> params = - Arrays.asList( - new AvaticaParameter(false, 10, 0, Types.VARCHAR, "VARCHAR", - String.class.getName(), "str")); - Meta.CursorFactory cursorFactory = Meta.CursorFactory.create(Style.LIST, Object.class, - Arrays.asList("str", "count", "counts")); - // The row values - List<Object> rows = new ArrayList<>(); - rows.add(new Object[] {"str_value1", 50, Arrays.asList(1, 2, 3)}); - rows.add(new Object[] {"str_value2", 100, Arrays.asList(1)}); - - // Create the signature and frame using the metadata and values - Signature signature = Signature.create(columns, "sql", params, cursorFactory, - Meta.StatementType.SELECT); - Frame frame = Frame.create(Integer.MAX_VALUE, true, rows); - - // And then create a ResultSetResponse - ResultSetResponse results1 = new ResultSetResponse("connectionId", Integer.MAX_VALUE, true, - signature, frame, Long.MAX_VALUE, rpcMetadata); - responses.add(results1); - - responses.add(new CloseStatementResponse(rpcMetadata)); - - ConnectionPropertiesImpl connProps = new ConnectionPropertiesImpl(false, true, - Integer.MAX_VALUE, "catalog", "schema"); - responses.add(new ConnectionSyncResponse(connProps, rpcMetadata)); - - responses.add(new OpenConnectionResponse(rpcMetadata)); - responses.add(new CloseConnectionResponse(rpcMetadata)); - - responses.add(new CreateStatementResponse("connectionId", Integer.MAX_VALUE, rpcMetadata)); - - Map<Meta.DatabaseProperty, Object> propertyMap = new HashMap<>(); - for (Meta.DatabaseProperty prop : Meta.DatabaseProperty.values()) { - propertyMap.put(prop, prop.defaultValue); - } - responses.add(new DatabasePropertyResponse(propertyMap, rpcMetadata)); - - responses.add( - new ExecuteResponse(Arrays.asList(results1, results1, results1), false, rpcMetadata)); - responses.add(new FetchResponse(frame, false, false, rpcMetadata)); - responses.add(new FetchResponse(frame, true, true, rpcMetadata)); - responses.add(new FetchResponse(frame, false, true, rpcMetadata)); - responses.add( - new PrepareResponse( - new Meta.StatementHandle("connectionId", Integer.MAX_VALUE, signature), - rpcMetadata)); - - StringWriter sw = new StringWriter(); - new Exception().printStackTrace(new PrintWriter(sw)); - responses.add( - new ErrorResponse(Collections.singletonList(sw.toString()), "Test Error Message", - ErrorResponse.UNKNOWN_ERROR_CODE, ErrorResponse.UNKNOWN_SQL_STATE, - AvaticaSeverity.WARNING, rpcMetadata)); - - // No more results, statement not missing - responses.add(new SyncResultsResponse(false, false, rpcMetadata)); - // Missing statement, no results - responses.add(new SyncResultsResponse(false, true, rpcMetadata)); - // More results, no missing statement - responses.add(new SyncResultsResponse(true, false, rpcMetadata)); - - // Some tests to make sure ErrorResponse doesn't fail. - responses.add(new ErrorResponse((List<String>) null, null, 0, null, null, null)); - responses.add( - new ErrorResponse(Arrays.asList("stacktrace1", "stacktrace2"), null, 0, null, null, null)); - - responses.add(new CommitResponse()); - responses.add(new RollbackResponse()); - - long[] updateCounts = new long[]{1, 0, 1, 1}; - responses.add( - new ExecuteBatchResponse("connectionId", 12345, updateCounts, false, rpcMetadata)); - - return responses; - } - - private final T object; - private final IdentityFunction<T> function; - - public ProtobufTranslationImplTest(T object, IdentityFunction<T> func) { - this.object = object; - this.function = func; - } - - @Test - public void testSerialization() throws Exception { - // Function acts as opposite sides of the transport. - // An object (a request or response) starts on one side - // of the transport, serialized, "sent" over the transport - // and then reconstituted. The object on either side should - // be equivalent. - assertEquals(object, this.function.apply(object)); - } -} - -// End ProtobufTranslationImplTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/remote/TypedValueTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/TypedValueTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/remote/TypedValueTest.java deleted file mode 100644 index 7606a87..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/remote/TypedValueTest.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.remote; - -import org.apache.calcite.avatica.ColumnMetaData.Rep; -import org.apache.calcite.avatica.proto.Common; -import org.apache.calcite.avatica.util.Base64; -import org.apache.calcite.avatica.util.ByteString; -import org.apache.calcite.avatica.util.DateTimeUtils; - -import org.junit.Test; - -import java.math.BigDecimal; -import java.util.Calendar; - -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.assertNotNull; -import static org.junit.Assert.assertThat; - -import static java.nio.charset.StandardCharsets.UTF_8; - -/** - * Test serialization of TypedValue. - */ -public class TypedValueTest { - - private void serializeAndEqualityCheck(TypedValue value) { - TypedValue copy = TypedValue.fromProto(value.toProto()); - - assertEquals(value.type, copy.type); - assertEquals(value.value, copy.value); - } - - @Test public void testBoolean() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_BOOLEAN, true)); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.BOOLEAN, Boolean.TRUE)); - } - - @Test public void testByte() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_BYTE, (byte) 4)); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.BYTE, Byte.valueOf((byte) 4))); - } - - @Test public void testShort() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_SHORT, (short) 42)); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.SHORT, Short.valueOf((short) 42))); - } - - @Test public void testInteger() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_INT, (int) 42000)); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.INTEGER, Integer.valueOf((int) 42000))); - } - - @Test public void testLong() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_LONG, Long.MAX_VALUE)); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.LONG, Long.valueOf(Long.MAX_VALUE))); - } - - @Test public void testFloat() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_FLOAT, 3.14159f)); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.FLOAT, Float.valueOf(3.14159f))); - } - - @Test public void testDouble() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_DOUBLE, Double.MAX_VALUE)); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.DOUBLE, Double.valueOf(Double.MAX_VALUE))); - } - - @Test public void testDecimal() { - final BigDecimal decimal = new BigDecimal("1.2345"); - final TypedValue decimalTypedValue = TypedValue.ofLocal(Rep.NUMBER, decimal); - serializeAndEqualityCheck(decimalTypedValue); - - final Common.TypedValue protoTypedValue = decimalTypedValue.toProto(); - assertEquals(Common.Rep.BIG_DECIMAL, protoTypedValue.getType()); - final String strValue = protoTypedValue.getStringValue(); - assertNotNull(strValue); - assertEquals(decimal.toPlainString(), strValue); - } - - @Test public void testChar() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_CHAR, 'c')); - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.CHARACTER, Character.valueOf('c'))); - } - - @Test public void testString() { - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.STRING, "qwertyasdf")); - } - - @Test public void testByteString() { - serializeAndEqualityCheck( - TypedValue.ofLocal(Rep.BYTE_STRING, - new ByteString("qwertyasdf".getBytes(UTF_8)))); - } - - @Test public void testBase64() { - byte[] bytes = "qwertyasdf".getBytes(UTF_8); - // Plain bytes get put into protobuf for simplicitly - Common.TypedValue proto = Common.TypedValue.newBuilder().setBytesValue( - com.google.protobuf.ByteString.copyFrom(bytes)) - .setType(Common.Rep.BYTE_STRING).build(); - - // But we should get back a b64-string to make sure TypedValue doesn't get confused. - Object deserializedObj = TypedValue.getSerialFromProto(proto); - assertThat(deserializedObj, is(instanceOf(String.class))); - assertEquals(new ByteString(bytes).toBase64String(), (String) deserializedObj); - - // But we should get a non-b64 byte array as the JDBC representation - deserializedObj = - TypedValue.protoToJdbc(proto, DateTimeUtils.calendar()); - assertThat(deserializedObj, is(instanceOf(byte[].class))); - assertArrayEquals(bytes, (byte[]) deserializedObj); - } - - @Test public void testSqlDate() { - // days since epoch - serializeAndEqualityCheck(TypedValue.ofLocal(Rep.JAVA_SQL_DATE, 25)); - } - - @Test public void testUtilDate() { - serializeAndEqualityCheck( - TypedValue.ofLocal(Rep.JAVA_UTIL_DATE, System.currentTimeMillis())); - } - - @Test public void testSqlTime() { - // millis since epoch - serializeAndEqualityCheck( - TypedValue.ofLocal(Rep.JAVA_SQL_TIME, 42 * 1024 * 1024)); - } - - @Test public void testSqlTimestamp() { - serializeAndEqualityCheck( - TypedValue.ofLocal(Rep.JAVA_SQL_TIMESTAMP, 42L * 1024 * 1024 * 1024)); - } - - @Test public void testLegacyDecimalParsing() { - final BigDecimal decimal = new BigDecimal("123451234512345"); - final Calendar calendar = DateTimeUtils.calendar(); - - // CALCITE-1103 Decimals were (incorrectly) getting serialized as normal "numbers" which - // caused them to use the numberValue field. TypedValue should still be able to handle - // values like this (but large values will be truncated and return bad values). - Common.TypedValue oldProtoStyle = Common.TypedValue.newBuilder().setType(Common.Rep.NUMBER) - .setNumberValue(decimal.longValue()).build(); - - TypedValue fromProtoTv = TypedValue.fromProto(oldProtoStyle); - Object o = fromProtoTv.toJdbc(calendar); - assertEquals(decimal, o); - } - - @Test public void testProtobufBytesNotSentAsBase64() { - final byte[] bytes = "asdf".getBytes(UTF_8); - final byte[] b64Bytes = Base64.encodeBytes(bytes).getBytes(UTF_8); - TypedValue tv = TypedValue.ofLocal(Rep.BYTE_STRING, new ByteString(bytes)); - // JSON encodes it as base64 - assertEquals(new String(b64Bytes, UTF_8), tv.value); - - // Get the protobuf variant - Common.TypedValue protoTv = tv.toProto(); - Common.Rep protoRep = protoTv.getType(); - assertEquals(Common.Rep.BYTE_STRING, protoRep); - - // The pb variant should have the native bytes of the original value - com.google.protobuf.ByteString protoByteString = protoTv.getBytesValue(); - assertNotNull(protoByteString); - assertArrayEquals(bytes, protoByteString.toByteArray()); - - // We should have the b64 string as a backwards compatibility feature - assertEquals(new String(b64Bytes, UTF_8), - protoTv.getStringValue()); - } - - @Test public void testLegacyBase64StringEncodingForBytes() { - // CALCITE-1103 CALCITE-1209 We observed that binary data was being - // serialized as base-64 encoded strings instead of the native binary - // data type in protobufs. We need to still handle older clients sending - // data in this form. - final byte[] bytes = "asdf".getBytes(UTF_8); - final String base64Str = Base64.encodeBytes(bytes); - Common.TypedValue.Builder builder = Common.TypedValue.newBuilder(); - builder.setStringValue(base64Str); - builder.setType(Common.Rep.BYTE_STRING); - Common.TypedValue protoTv = builder.build(); - - TypedValue tv = TypedValue.fromProto(protoTv); - assertEquals(Rep.BYTE_STRING, tv.type); - assertEquals(base64Str, tv.value); - } -} - -// End TypedValueTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaClientRuntimeExceptionTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaClientRuntimeExceptionTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaClientRuntimeExceptionTest.java deleted file mode 100644 index 411f29c..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaClientRuntimeExceptionTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.test; - -import org.apache.calcite.avatica.AvaticaClientRuntimeException; -import org.apache.calcite.avatica.AvaticaSeverity; -import org.apache.calcite.avatica.remote.Service.RpcMetadataResponse; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -/** - * Test class for {@link AvaticaClientRuntimeException}. - */ -public class AvaticaClientRuntimeExceptionTest { - - @Test public void testGetters() { - final String errorMsg = "My error message"; - final int errorCode = 10; - final String sqlState = "abc12"; - final AvaticaSeverity severity = AvaticaSeverity.ERROR; - final List<String> stacktraces = Arrays.asList("my stack trace"); - final RpcMetadataResponse metadata = new RpcMetadataResponse("localhost:8765"); - AvaticaClientRuntimeException e = new AvaticaClientRuntimeException(errorMsg, errorCode, - sqlState, severity, stacktraces, metadata); - assertEquals(errorMsg, e.getMessage()); - assertEquals(errorCode, e.getErrorCode()); - assertEquals(severity, e.getSeverity()); - assertEquals(stacktraces, e.getServerExceptions()); - assertEquals(metadata, e.getRpcMetadata()); - } - -} - -// End AvaticaClientRuntimeExceptionTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSeverityTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSeverityTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSeverityTest.java deleted file mode 100644 index 945f959..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSeverityTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.test; - -import org.apache.calcite.avatica.AvaticaSeverity; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * Tests for {@link AvaticaSeverity}. - */ -public class AvaticaSeverityTest { - - @Test - public void testProtobufSerialization() { - for (AvaticaSeverity severity : AvaticaSeverity.values()) { - assertEquals(severity, AvaticaSeverity.fromProto(severity.toProto())); - } - } - -} - -// End AvaticaSeverityTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSqlExceptionTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSqlExceptionTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSqlExceptionTest.java deleted file mode 100644 index 3d7b5b0..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaSqlExceptionTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.test; - -import org.apache.calcite.avatica.AvaticaSqlException; - -import org.junit.Test; - -import java.util.Arrays; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Tests for {@link AvaticaSqlException}. - */ -public class AvaticaSqlExceptionTest { - - @Test public void testGetters() { - final String msg = "My query failed!"; - final int code = 42; - final String sql = "SELECT foo FROM bar;"; - final String stacktrace = "My Stack Trace"; - final String server = "localhost:8765"; - - AvaticaSqlException e = new AvaticaSqlException(msg, sql, code, Arrays.asList(stacktrace), - server); - assertTrue(e.getMessage().contains(msg)); - assertEquals(code, e.getErrorCode()); - assertEquals(sql, e.getSQLState()); - assertEquals(1, e.getStackTraces().size()); - assertEquals(stacktrace, e.getStackTraces().get(0)); - assertEquals(server, e.getRemoteServer()); - } - -} - -// End AvaticaSqlExceptionTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaUtilsTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaUtilsTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaUtilsTest.java deleted file mode 100644 index b1a422c..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/test/AvaticaUtilsTest.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.test; - -import org.apache.calcite.avatica.AvaticaUtils; -import org.apache.calcite.avatica.ConnectionConfigImpl; -import org.apache.calcite.avatica.ConnectionProperty; -import org.apache.calcite.avatica.util.ByteString; - -import org.junit.Test; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Properties; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - -/** - * Unit test for Avatica utilities. - */ -public class AvaticaUtilsTest { - @Test public void testInstantiatePlugin() { - final String s = - AvaticaUtils.instantiatePlugin(String.class, "java.lang.String"); - assertThat(s, is("")); - - // No default constructor or INSTANCE member - try { - final Integer i = - AvaticaUtils.instantiatePlugin(Integer.class, "java.lang.Integer"); - fail("expected error, got " + i); - } catch (Throwable e) { - assertThat(e.getMessage(), - is("Property 'java.lang.Integer' not valid for plugin type java.lang.Integer")); - } - - final BigInteger b = - AvaticaUtils.instantiatePlugin(BigInteger.class, "java.math.BigInteger#ONE"); - assertThat(b, is(BigInteger.ONE)); - - try { - final BigInteger b2 = - AvaticaUtils.instantiatePlugin(BigInteger.class, - "java.math.BigInteger.ONE"); - fail("expected error, got " + b2); - } catch (Throwable e) { - assertThat(e.getMessage(), - is("Property 'java.math.BigInteger.ONE' not valid for plugin type java.math.BigInteger")); - } - } - - /** Unit test for - * {@link org.apache.calcite.avatica.AvaticaUtils#unique(java.lang.String)}. */ - @Test public void testUnique() { - // Below, the "probably" comments indicate the strings that will be - // generated the first time you run the test. - final Set<String> list = new LinkedHashSet<>(); - list.add(AvaticaUtils.unique("a")); // probably "a" - assertThat(list.size(), is(1)); - list.add(AvaticaUtils.unique("a")); // probably "a_1" - assertThat(list.size(), is(2)); - list.add(AvaticaUtils.unique("b")); // probably "b" - assertThat(list.size(), is(3)); - list.add(AvaticaUtils.unique("a_1")); // probably "a_1_3" - assertThat(list.size(), is(4)); - list.add(AvaticaUtils.unique("A")); // probably "A" - assertThat(list.size(), is(5)); - list.add(AvaticaUtils.unique("a")); // probably "a_5" - assertThat(list.size(), is(6)); - } - - /** Tests connect string properties. */ - @Test public void testConnectionProperty() { - final ConnectionPropertyImpl n = new ConnectionPropertyImpl("N", - BigDecimal.valueOf(100), ConnectionProperty.Type.NUMBER); - - final Properties properties = new Properties(); - ConnectionConfigImpl.PropEnv env = n.wrap(properties); - assertThat(env.getInt(), is(100)); - assertThat(env.getInt(-45), is(-45)); - properties.setProperty(n.name, "123"); - assertThat(env.getInt(), is(100)); - env = n.wrap(properties); - assertThat(env.getInt(), is(123)); - assertThat(env.getInt(-45), is(123)); - - properties.setProperty(n.name, "10k"); - env = n.wrap(properties); - assertThat(env.getInt(), is(10 * 1024)); - - properties.setProperty(n.name, "-0.5k"); - env = n.wrap(properties); - assertThat(env.getInt(), is(-512)); - - properties.setProperty(n.name, "10m"); - env = n.wrap(properties); - assertThat(env.getInt(), is(10 * 1024 * 1024)); - assertThat(env.getLong(), is(10L * 1024 * 1024)); - assertThat(env.getDouble(), is(10D * 1024 * 1024)); - - properties.setProperty(n.name, "-2M"); - env = n.wrap(properties); - assertThat(env.getInt(), is(-2 * 1024 * 1024)); - - properties.setProperty(n.name, "10g"); - env = n.wrap(properties); - assertThat(env.getLong(), is(10L * 1024 * 1024 * 1024)); - - final ConnectionPropertyImpl b = new ConnectionPropertyImpl("B", - true, ConnectionProperty.Type.BOOLEAN); - - env = b.wrap(properties); - assertThat(env.getBoolean(), is(true)); - assertThat(env.getBoolean(true), is(true)); - assertThat(env.getBoolean(false), is(false)); - - properties.setProperty(b.name, "false"); - env = b.wrap(properties); - assertThat(env.getBoolean(), is(false)); - - final ConnectionPropertyImpl s = new ConnectionPropertyImpl("S", - "foo", ConnectionProperty.Type.STRING); - - env = s.wrap(properties); - assertThat(env.getString(), is("foo")); - assertThat(env.getString("baz"), is("baz")); - - properties.setProperty(s.name, " "); - env = s.wrap(properties); - assertThat(env.getString(), is(" ")); - - try { - final ConnectionPropertyImpl t = - new ConnectionPropertyImpl("T", null, ConnectionProperty.Type.ENUM); - fail("should throw if you specify an enum property without a class, got " - + t); - } catch (AssertionError e) { - assertThat(e.getMessage(), is("must specify value class for an ENUM")); - // ok - } - - // An enum with a default value - final ConnectionPropertyImpl t = new ConnectionPropertyImpl("T", Size.BIG, - ConnectionProperty.Type.ENUM, Size.class); - env = t.wrap(properties); - assertThat(env.getEnum(Size.class), is(Size.BIG)); - assertThat(env.getEnum(Size.class, Size.SMALL), is(Size.SMALL)); - assertThat(env.getEnum(Size.class, null), nullValue()); - try { - final Weight envEnum = env.getEnum(Weight.class, null); - fail("expected error, got " + envEnum); - } catch (AssertionError e) { - assertThat(e.getMessage(), - is("wrong value class; expected " + Size.class)); - } - - // An enum with a default value that is an anonymous enum, - // not specifying value type. - final ConnectionPropertyImpl v = new ConnectionPropertyImpl("V", - Size.SMALL, ConnectionProperty.Type.ENUM); - env = v.wrap(properties); - assertThat(env.getEnum(Size.class), is(Size.SMALL)); - assertThat(env.getEnum(Size.class, Size.BIG), is(Size.BIG)); - assertThat(env.getEnum(Size.class, null), nullValue()); - try { - final Weight envEnum = env.getEnum(Weight.class, null); - fail("expected error, got " + envEnum); - } catch (AssertionError e) { - assertThat(e.getMessage(), - is("wrong value class; expected " + Size.class)); - } - - // An enum with no default value - final ConnectionPropertyImpl u = new ConnectionPropertyImpl("U", null, - ConnectionProperty.Type.ENUM, Size.class); - env = u.wrap(properties); - assertThat(env.getEnum(Size.class), nullValue()); - assertThat(env.getEnum(Size.class, Size.SMALL), is(Size.SMALL)); - assertThat(env.getEnum(Size.class, null), nullValue()); - try { - final Weight envEnum = env.getEnum(Weight.class, null); - fail("expected error, got " + envEnum); - } catch (AssertionError e) { - assertThat(e.getMessage(), - is("wrong value class; expected " + Size.class)); - } - } - - @Test public void testLongToIntegerTranslation() { - long[] longValues = new long[] {Integer.MIN_VALUE, -5, 0, 1, Integer.MAX_VALUE, - ((long) Integer.MAX_VALUE) + 1L, Long.MAX_VALUE}; - int[] convertedValues = AvaticaUtils.toSaturatedInts(longValues); - int[] intValues = new int[] {Integer.MIN_VALUE, -5, 0, 1, Integer.MAX_VALUE, - Integer.MAX_VALUE, Integer.MAX_VALUE}; - assertArrayEquals(convertedValues, intValues); - } - - @Test public void testByteString() { - final byte[] bytes = {3, 14, 15, 92, 0, 65, 35, 0}; - final ByteString s = new ByteString(bytes); - final ByteString s2 = new ByteString(bytes.clone()); - final ByteString s3 = new ByteString(new byte[0]); - final ByteString s4 = new ByteString(new byte[] {0}); - final ByteString s5 = new ByteString(new byte[]{15, 92}); - - // length - assertThat(s.length(), is(8)); - assertThat(s3.length(), is(0)); - assertThat(s4.length(), is(1)); - - // equals and hashCode - assertThat(s.hashCode(), is(s2.hashCode())); - assertThat(s.equals(s2), is(true)); - assertThat(s2.equals(s), is(true)); - assertThat(s.equals(s3), is(false)); - assertThat(s3.equals(s), is(false)); - - // toString - assertThat(s.toString(), is("030e0f5c00412300")); - assertThat(s3.toString(), is("")); - assertThat(s4.toString(), is("00")); - - // indexOf - assertThat(s.indexOf(s3), is(0)); - assertThat(s.indexOf(s3, 5), is(5)); - assertThat(s.indexOf(s3, 15), is(-1)); - assertThat(s.indexOf(s4), is(4)); - assertThat(s.indexOf(s4, 4), is(4)); - assertThat(s.indexOf(s4, 5), is(7)); - assertThat(s.indexOf(s5), is(2)); - assertThat(s.indexOf(s5, 2), is(2)); - assertThat(s.indexOf(s5, 3), is(-1)); - assertThat(s.indexOf(s5, 7), is(-1)); - - // substring - assertThat(s.substring(8), is(s3)); - assertThat(s.substring(7), is(s4)); - assertThat(s.substring(0), is(s)); - - // getBytes - assertThat(s.getBytes().length, is(8)); - assertThat(Arrays.equals(s.getBytes(), bytes), is(true)); - assertThat(s.getBytes()[3], is((byte) 92)); - final byte[] copyBytes = s.getBytes(); - copyBytes[3] = 11; - assertThat(s.getBytes()[3], is((byte) 92)); - assertThat(s, is(s2)); - } - - /** Dummy implementation of {@link ConnectionProperty}. */ - private static class ConnectionPropertyImpl implements ConnectionProperty { - private final String name; - private final Object defaultValue; - private final Class<?> valueClass; - private Type type; - - ConnectionPropertyImpl(String name, Object defaultValue, Type type) { - this(name, defaultValue, type, null); - } - - ConnectionPropertyImpl(String name, Object defaultValue, Type type, - Class valueClass) { - this.name = name; - this.defaultValue = defaultValue; - this.type = type; - this.valueClass = type.deduceValueClass(defaultValue, valueClass); - if (!type.valid(defaultValue, this.valueClass)) { - throw new AssertionError(name); - } - } - - public String name() { - return name.toUpperCase(Locale.ROOT); - } - - public String camelName() { - return name.toLowerCase(Locale.ROOT); - } - - public Object defaultValue() { - return defaultValue; - } - - public Type type() { - return type; - } - - public Class valueClass() { - return valueClass; - } - - public ConnectionConfigImpl.PropEnv wrap(Properties properties) { - final HashMap<String, ConnectionProperty> map = new HashMap<>(); - map.put(name, this); - return new ConnectionConfigImpl.PropEnv( - ConnectionConfigImpl.parse(properties, map), this); - } - - public boolean required() { - return false; - } - } - - /** How large? */ - private enum Size { - BIG, - SMALL { - } - } - - /** How heavy? */ - private enum Weight { - HEAVY, LIGHT - } -} - -// End AvaticaUtilsTest.java http://git-wip-us.apache.org/repos/asf/calcite-avatica/blob/fc7b26c8/avatica/core/src/test/java/org/apache/calcite/avatica/test/ConnectStringParserTest.java ---------------------------------------------------------------------- diff --git a/avatica/core/src/test/java/org/apache/calcite/avatica/test/ConnectStringParserTest.java b/avatica/core/src/test/java/org/apache/calcite/avatica/test/ConnectStringParserTest.java deleted file mode 100644 index cdc8d8a..0000000 --- a/avatica/core/src/test/java/org/apache/calcite/avatica/test/ConnectStringParserTest.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.calcite.avatica.test; - -import org.apache.calcite.avatica.ConnectStringParser; - -import org.junit.Test; - -import java.sql.SQLException; -import java.util.Properties; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -/** - * Unit test for JDBC connect string parser, {@link ConnectStringParser}. The - * ConnectStringParser is adapted from code in Mondrian, but most of the tests - * below were unfortunately "reinvented" prior to having the Mondrian unit tests - * in hand. - */ -public class ConnectStringParserTest { - /** - * Tests simple connect string. Adapted from Mondrian tests. - */ - @Test public void testSimpleStrings() throws Throwable { - Properties props = ConnectStringParser.parse("foo=x;bar=y;foo=z"); - assertEquals( - "bar", - "y", - props.get("bar")); - assertNull( - "BAR", - props.get("BAR")); // case-sensitive, unlike Mondrian - assertEquals( - "last foo", - "z", - props.get("foo")); - assertNull( - "key=\" bar\"", - props.get(" bar")); - assertNull( - "bogus key", - props.get("kipper")); - assertEquals( - "param count", - 2, - props.size()); - - String synth = ConnectStringParser.getParamString(props); - Properties synthProps = ConnectStringParser.parse(synth); - assertEquals("reversible", props, synthProps); - } - - /** - * Tests complex connect strings. Adapted directly from Mondrian tests. - */ - @Test public void testComplexStrings() throws Throwable { - Properties props = - ConnectStringParser.parse("normalProp=value;" - + "emptyValue=;" - + " spaceBeforeProp=abc;" - + " spaceBeforeAndAfterProp =def;" - + " space in prop = foo bar ;" - + "equalsInValue=foo=bar;" - + "semiInProp;Name=value;" - + " singleQuotedValue = 'single quoted value ending in space ' ;" - + " doubleQuotedValue = " - + "\"=double quoted value preceded by equals\" ;" - + " singleQuotedValueWithSemi = 'one; two';" - + " singleQuotedValueWithSpecials = 'one; two \"three''four=five'"); - - assertEquals( - "param count", - 11, - props.size()); - - String value; - value = (String) props.get("normalProp"); - assertEquals("value", value); - value = (String) props.get("emptyValue"); - assertEquals("", value); // empty string, not null! - value = (String) props.get("spaceBeforeProp"); - assertEquals("abc", value); - value = (String) props.get("spaceBeforeAndAfterProp"); - assertEquals("def", value); - value = (String) props.get("space in prop"); - assertEquals(value, "foo bar"); - value = (String) props.get("equalsInValue"); - assertEquals("foo=bar", value); - value = (String) props.get("semiInProp;Name"); - assertEquals("value", value); - value = (String) props.get("singleQuotedValue"); - assertEquals("single quoted value ending in space ", value); - value = (String) props.get("doubleQuotedValue"); - assertEquals("=double quoted value preceded by equals", value); - value = (String) props.get("singleQuotedValueWithSemi"); - assertEquals(value, "one; two"); - value = (String) props.get("singleQuotedValueWithSpecials"); - assertEquals(value, "one; two \"three'four=five"); - } - - /** - * Tests for specific errors thrown by the parser. - */ - @Test public void testConnectStringErrors() throws Throwable { - // force some parsing errors - try { - ConnectStringParser.parse("key='can't parse'"); - fail("quoted value ended too soon"); - } catch (SQLException e) { - assertExceptionMatches(e, ".*quoted value ended.*position 9.*"); - } - - try { - ConnectStringParser.parse("key='\"can''t parse\""); - fail("unterminated quoted value"); - } catch (SQLException e) { - assertExceptionMatches(e, ".*unterminated quoted value.*"); - } - } - - /** - * Tests most of the examples from the <a - * href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/oledb/htm/oledbconnectionstringsyntax.asp"> - * OLE DB spec</a>. Omitted are cases for Window handles, returning multiple - * values, and special handling of "Provider" keyword. - */ - @Test public void testOleDbExamples() throws Throwable { - // test the parser with examples from OLE DB documentation - Quad[] quads = { - // {reason for test, key, val, string to parse}, - new Quad( - "printable chars", - "Jet OLE DB:System Database", "c:\\system.mda", - "Jet OLE DB:System Database=c:\\system.mda"), - new Quad( - "key embedded semi", - "Authentication;Info", "Column 5", - "Authentication;Info=Column 5"), - new Quad( - "key embedded equal", - "Verification=Security", "True", - "Verification==Security=True"), - new Quad( - "key many equals", - "Many==One", "Valid", - "Many====One=Valid"), - new Quad( - "key too many equal", - "TooMany=", "False", - "TooMany===False"), - new Quad( - "value embedded quote and semi", - "ExtProps", "Data Source='localhost';Key Two='value 2'", - "ExtProps=\"Data Source='localhost';Key Two='value 2'\""), - new Quad( - "value embedded double quote and semi", - "ExtProps", "Integrated Security=\"SSPI\";Key Two=\"value 2\"", - "ExtProps='Integrated Security=\"SSPI\";Key Two=\"value 2\"'"), - new Quad( - "value double quoted", - "DataSchema", "\"MyCustTable\"", - "DataSchema='\"MyCustTable\"'"), - new Quad( - "value single quoted", - "DataSchema", "'MyCustTable'", - "DataSchema=\"'MyCustTable'\""), - new Quad( - "value double quoted double trouble", - "Caption", "\"Company's \"new\" customer\"", - "Caption=\"\"\"Company's \"\"new\"\" customer\"\"\""), - new Quad( - "value single quoted double trouble", - "Caption", "\"Company's \"new\" customer\"", - "Caption='\"Company''s \"new\" customer\"'"), - new Quad( - "embedded blanks and trim", - "My Keyword", "My Value", - " My Keyword = My Value ;MyNextValue=Value"), - new Quad( - "value single quotes preserve blanks", - "My Keyword", " My Value ", - " My Keyword =' My Value ';MyNextValue=Value"), - new Quad( - "value double quotes preserve blanks", - "My Keyword", " My Value ", - " My Keyword =\" My Value \";MyNextValue=Value"), - new Quad( - "last redundant key wins", - "SomeKey", "NextValue", - "SomeKey=FirstValue;SomeKey=NextValue"), - }; - for (Quad quad : quads) { - Properties props = ConnectStringParser.parse(quad.str); - - assertEquals(quad.why, quad.val, props.get(quad.key)); - String synth = ConnectStringParser.getParamString(props); - - try { - assertEquals("reversible " + quad.why, quad.str, synth); - } catch (Throwable e) { - // it's OK that the strings don't match as long as the - // two strings parse out the same way and are thus - // "semantically reversible" - Properties synthProps = ConnectStringParser.parse(synth); - assertEquals("equivalent " + quad.why, props, synthProps); - } - } - } - - static void assertExceptionMatches( - Throwable e, - String expectedPattern) { - if (e == null) { - fail("Expected an error which matches pattern '" + expectedPattern + "'"); - } - String msg = e.toString(); - if (!msg.matches(expectedPattern)) { - fail("Got a different error '" + msg + "' than expected '" - + expectedPattern + "'"); - } - } - - /** Collection of values comprising a test. */ - static class Quad { - private final String why; - private final String key; - private final String val; - private final String str; - - Quad(String why, String key, String val, String str) { - this.why = why; - this.key = key; - this.val = val; - this.str = str; - } - } -} - -// End ConnectStringParserTest.java
