From 5a247cff3b0c00a9b5291279e758338a5828ad0f Mon Sep 17 00:00:00 2001 From: Andres Taylor Date: Tue, 11 Dec 2018 10:13:31 +0100 Subject: [PATCH 1/2] Minor cleanups of the JDBC code Signed-off-by: Andres Taylor --- java/jdbc/pom.xml | 9 - .../java/io/vitess/jdbc/VitessConnection.java | 28 +- .../java/io/vitess/jdbc/VitessDriver.java | 5 +- .../vitess/jdbc/VitessPreparedStatement.java | 7 +- .../java/io/vitess/jdbc/VitessResultSet.java | 6 +- .../java/io/vitess/jdbc/VitessStatement.java | 22 +- .../vitess/jdbc/ConnectionPropertiesTest.java | 168 ++-- .../io/vitess/jdbc/VitessConnectionTest.java | 236 ++--- .../java/io/vitess/jdbc/VitessDriverTest.java | 94 +- .../jdbc/VitessPreparedStatementTest.java | 485 ++++----- .../io/vitess/jdbc/VitessResultSetTest.java | 330 +++--- .../io/vitess/jdbc/VitessStatementTest.java | 947 +++++++++--------- 12 files changed, 1153 insertions(+), 1184 deletions(-) diff --git a/java/jdbc/pom.xml b/java/jdbc/pom.xml index 9019aaa72fe..cd9bc8282a4 100644 --- a/java/jdbc/pom.xml +++ b/java/jdbc/pom.xml @@ -81,15 +81,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - 3.5 - - 7 - 7 - - org.apache.maven.plugins maven-surefire-plugin diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java index 40a110bbf79..601b35f2801 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java @@ -41,13 +41,11 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.Executor; -import java.util.logging.Logger; import io.vitess.client.Context; import io.vitess.client.VTGateConnection; import io.vitess.client.VTSession; import io.vitess.proto.Query; -import io.vitess.proto.Vtgate; import io.vitess.util.CommonUtils; import io.vitess.util.Constants; import io.vitess.util.MysqlDefs; @@ -58,7 +56,6 @@ public class VitessConnection extends ConnectionProperties implements Connection { /* Get actual class name to be printed on */ - private static Logger logger = Logger.getLogger(VitessConnection.class.getName()); private static DatabaseMetaData databaseMetaData = null; /** @@ -223,9 +220,8 @@ public void close() throws SQLException { * Return Connection state * * @return DatabaseMetadata Object - * @throws SQLException */ - public boolean isClosed() throws SQLException { + public boolean isClosed() { return this.closed; } @@ -486,9 +482,8 @@ public void setClientInfo(String name, String value) throws SQLClientInfoExcepti * * @param name - Property Name * @return Property Value - * @throws SQLException */ - public String getClientInfo(String name) throws SQLException { + public String getClientInfo(String name) { return null; } @@ -496,9 +491,8 @@ public String getClientInfo(String name) throws SQLException { * TODO: For Implementation Possibility * * @return - Property Object - * @throws SQLException */ - public Properties getClientInfo() throws SQLException { + public Properties getClientInfo() { return null; } @@ -818,11 +812,11 @@ private String initializeDBProperties() throws SQLException { if (metadataNullOrClosed()) { String versionValue; - ResultSet resultSet = null; - VitessStatement vitessStatement = new VitessStatement(this); - try { - resultSet = vitessStatement.executeQuery( - "SHOW VARIABLES WHERE VARIABLE_NAME IN (\'tx_isolation\',\'INNODB_VERSION\', \'lower_case_table_names\')"); + + try(VitessStatement vitessStatement = new VitessStatement(this); + ResultSet resultSet = vitessStatement.executeQuery( + "SHOW VARIABLES WHERE VARIABLE_NAME IN (\'tx_isolation\',\'INNODB_VERSION\', \'lower_case_table_names\')") + ) { while (resultSet.next()) { dbVariables.put(resultSet.getString(1), resultSet.getString(2)); } @@ -855,13 +849,7 @@ private String initializeDBProperties() throws SQLException { } this.dbProperties = new DBProperties(productVersion, majorVersion, minorVersion, isolationLevel, lowerCaseTables); - } finally { - if (null != resultSet) { - resultSet.close(); - } - vitessStatement.close(); } - } return dbEngine; } diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java index b78579b1abf..1518f52371b 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java @@ -38,9 +38,6 @@ */ public class VitessDriver implements Driver { - /* Get actual class name to be printed on */ - private static Logger logger = Logger.getLogger(VitessDriver.class.getName()); - static { try { DriverManager.registerDriver(new VitessDriver()); @@ -73,7 +70,7 @@ public Connection connect(String url, Properties info) throws SQLException { * TODO: Write a better regex */ @Override - public boolean acceptsURL(String url) throws SQLException { + public boolean acceptsURL(String url) { return null != url && url.startsWith(Constants.URL_PREFIX); } diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java index b554a224fae..304456af86f 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java @@ -48,7 +48,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.logging.Logger; import io.vitess.client.Context; import io.vitess.client.VTGateConnection; @@ -70,7 +69,6 @@ public class VitessPreparedStatement extends VitessStatement implements PreparedStatement { /* Get actual class name to be printed on */ - private static Logger logger = Logger.getLogger(VitessPreparedStatement.class.getName()); private final String sql; private final Map bindVariables; /** @@ -394,7 +392,7 @@ public void addBatch() throws SQLException { vtGateConn = this.vitessConnection.getVtGateConn(); this.retrieveGeneratedKeys = true; // mimicking mysql-connector-j - /** + /* * Current api does not support single query and multiple bindVariables list. * So, List of the query is created to match the bindVariables list. */ @@ -466,9 +464,6 @@ private int calculateParameterCount() throws SQLException { continue; // inline quote escape } - inQuotes = !inQuotes; - currentQuoteChar = 0; - } else if (((c == '\'') || (c == '"')) && c == currentQuoteChar) { inQuotes = !inQuotes; currentQuoteChar = 0; } diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java index aa6cdcd36b3..f7fd6715519 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java @@ -46,7 +46,6 @@ import java.util.Calendar; import java.util.List; import java.util.Map; -import java.util.logging.Logger; import javax.sql.rowset.serial.SerialClob; import io.vitess.client.cursor.Cursor; @@ -61,9 +60,6 @@ */ public class VitessResultSet implements ResultSet { - /* Get actual class name to be printed on */ - private static Logger logger = Logger.getLogger(VitessResultSet.class.getName()); - private Cursor cursor; private List fields; private VitessStatement vitessStatement; @@ -765,7 +761,7 @@ public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLExcept return getTimestamp(columnIndex, cal); } - public boolean isClosed() throws SQLException { + public boolean isClosed() { return this.closed; } diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java index f4a0904824f..3e2373e4ca4 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java @@ -24,7 +24,6 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; -import java.util.logging.Logger; import io.vitess.client.Context; import io.vitess.client.Proto; @@ -48,8 +47,6 @@ */ public class VitessStatement implements Statement { protected static final String[] ON_DUPLICATE_KEY_UPDATE_CLAUSE = new String[] { "ON", "DUPLICATE", "KEY", "UPDATE" }; - /* Get actual class name to be printed on */ - private static Logger logger = Logger.getLogger(VitessStatement.class.getName()); protected VitessResultSet vitessResultSet; protected VitessConnection vitessConnection; protected boolean closed; @@ -268,9 +265,8 @@ public SQLWarning getWarnings() throws SQLException { /** * Clear the warnings - Not saving Warnings * - * @throws SQLException */ - public void clearWarnings() throws SQLException { + public void clearWarnings() { //no-op } @@ -316,7 +312,7 @@ public VitessConnection getConnection() throws SQLException { return vitessConnection; } - public boolean isClosed() throws SQLException { + public boolean isClosed() { return this.closed; } @@ -376,15 +372,15 @@ public ResultSet getGeneratedKeys() throws SQLException { } } else if (this.batchGeneratedKeys != null) { long totalAffected = 0; - for (int i = 0; i < this.batchGeneratedKeys.length; i++) { - long rowsAffected = this.batchGeneratedKeys[i][1]; + for (long[] batchGeneratedKey : this.batchGeneratedKeys) { + long rowsAffected = batchGeneratedKey[1]; totalAffected += rowsAffected; } data = new String[(int) totalAffected][1]; int idx = 0; - for (int i = 0; i < this.batchGeneratedKeys.length; i++) { - long insertId = this.batchGeneratedKeys[i][0]; - long rowsAffected = this.batchGeneratedKeys[i][1]; + for (long[] batchGeneratedKey : this.batchGeneratedKeys) { + long insertId = batchGeneratedKey[0]; + long rowsAffected = batchGeneratedKey[1]; for (int j = 0; j < rowsAffected; j++) { data[idx++][0] = String.valueOf(insertId + j); } @@ -591,7 +587,7 @@ protected void checkSQLNullOrEmpty(String sql) throws SQLException { protected int[] generateBatchUpdateResult(List cursorWithErrorList, List batchedArgs) throws BatchUpdateException { int[] updateCounts = new int[cursorWithErrorList.size()]; - ArrayList generatedKeys = new ArrayList(); + ArrayList generatedKeys = new ArrayList<>(); Vtrpc.RPCError rpcError = null; String batchCommand = null; @@ -663,7 +659,7 @@ protected void checkAndBeginTransaction() throws SQLException { if (!(this.vitessConnection.getAutoCommit() || this.vitessConnection.isInTransaction())) { Context context = this.vitessConnection.createContext(this.queryTimeoutInMillis); VTGateConnection vtGateConn = this.vitessConnection.getVtGateConn(); - Cursor cursor = vtGateConn.execute(context,"begin",null,this.vitessConnection.getVtSession()).checkedGet(); + vtGateConn.execute(context,"begin",null,this.vitessConnection.getVtSession()).checkedGet(); } } diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java index 6d1e8cc5c4b..79a4e12d0c5 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java @@ -21,6 +21,7 @@ import java.util.Arrays; import java.util.Properties; +import io.vitess.util.Constants.ZeroDateTimeBehavior; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; @@ -29,6 +30,14 @@ import io.vitess.proto.Topodata; import io.vitess.util.Constants; +import static io.vitess.util.Constants.DEFAULT_EXECUTE_TYPE; +import static io.vitess.util.Constants.DEFAULT_INCLUDED_FIELDS; +import static io.vitess.util.Constants.DEFAULT_TABLET_TYPE; +import static org.junit.Assert.*; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + public class ConnectionPropertiesTest { private static final int NUM_PROPS = 39; @@ -42,8 +51,8 @@ public void testReflection() throws Exception { // Just testing that we are properly picking up all the fields defined in the properties // For each field we call initializeFrom, which should call getProperty and remove - Mockito.verify(info, Mockito.times(NUM_PROPS)).getProperty(Mockito.anyString()); - Mockito.verify(info, Mockito.times(NUM_PROPS)).remove(Mockito.anyString()); + verify(info, times(NUM_PROPS)).getProperty(anyString()); + verify(info, times(NUM_PROPS)).remove(anyString()); } @Test @@ -52,24 +61,24 @@ public void testDefaults() throws SQLException { ConnectionProperties props = new ConnectionProperties(); props.initializeProperties(new Properties()); - Assert.assertEquals("blobsAreStrings", false, props.getBlobsAreStrings()); - Assert.assertEquals("functionsNeverReturnBlobs", false, props.getFunctionsNeverReturnBlobs()); - Assert.assertEquals("tinyInt1isBit", true, props.getTinyInt1isBit()); - Assert.assertEquals("yearIsDateType", true, props.getYearIsDateType()); - Assert.assertEquals("useBlobToStoreUTF8OutsideBMP", false, props.getUseBlobToStoreUTF8OutsideBMP()); - Assert.assertEquals("utf8OutsideBmpIncludedColumnNamePattern", null, props.getUtf8OutsideBmpIncludedColumnNamePattern()); - Assert.assertEquals("utf8OutsideBmpExcludedColumnNamePattern", null, props.getUtf8OutsideBmpExcludedColumnNamePattern()); - Assert.assertEquals("zeroDateTimeBehavior", Constants.ZeroDateTimeBehavior.GARBLE, props.getZeroDateTimeBehavior()); - Assert.assertEquals("characterEncoding", null, props.getEncoding()); - Assert.assertEquals("executeType", Constants.DEFAULT_EXECUTE_TYPE, props.getExecuteType()); - Assert.assertEquals("twopcEnabled", false, props.getTwopcEnabled()); - Assert.assertEquals("includedFields", Constants.DEFAULT_INCLUDED_FIELDS, props.getIncludedFields()); - Assert.assertEquals("includedFieldsCache", true, props.isIncludeAllFields()); - Assert.assertEquals("tabletType", Constants.DEFAULT_TABLET_TYPE, props.getTabletType()); - Assert.assertEquals("useSSL", false, props.getUseSSL()); - Assert.assertEquals("useAffectedRows", true, props.getUseAffectedRows()); - Assert.assertEquals("refreshConnection", false, props.getRefreshConnection()); - Assert.assertEquals("refreshSeconds", 60, props.getRefreshSeconds()); + assertEquals("blobsAreStrings", false, props.getBlobsAreStrings()); + assertEquals("functionsNeverReturnBlobs", false, props.getFunctionsNeverReturnBlobs()); + assertEquals("tinyInt1isBit", true, props.getTinyInt1isBit()); + assertEquals("yearIsDateType", true, props.getYearIsDateType()); + assertEquals("useBlobToStoreUTF8OutsideBMP", false, props.getUseBlobToStoreUTF8OutsideBMP()); + assertEquals("utf8OutsideBmpIncludedColumnNamePattern", null, props.getUtf8OutsideBmpIncludedColumnNamePattern()); + assertEquals("utf8OutsideBmpExcludedColumnNamePattern", null, props.getUtf8OutsideBmpExcludedColumnNamePattern()); + assertEquals("zeroDateTimeBehavior", ZeroDateTimeBehavior.GARBLE, props.getZeroDateTimeBehavior()); + assertEquals("characterEncoding", null, props.getEncoding()); + assertEquals("executeType", DEFAULT_EXECUTE_TYPE, props.getExecuteType()); + assertEquals("twopcEnabled", false, props.getTwopcEnabled()); + assertEquals("includedFields", DEFAULT_INCLUDED_FIELDS, props.getIncludedFields()); + assertEquals("includedFieldsCache", true, props.isIncludeAllFields()); + assertEquals("tabletType", DEFAULT_TABLET_TYPE, props.getTabletType()); + assertEquals("useSSL", false, props.getUseSSL()); + assertEquals("useAffectedRows", true, props.getUseAffectedRows()); + assertEquals("refreshConnection", false, props.getRefreshConnection()); + assertEquals("refreshSeconds", 60, props.getRefreshSeconds()); } @Test @@ -93,24 +102,24 @@ public void testInitializeFromProperties() throws SQLException { props.initializeProperties(info); - Assert.assertEquals("blobsAreStrings", true, props.getBlobsAreStrings()); - Assert.assertEquals("functionsNeverReturnBlobs", true, props.getFunctionsNeverReturnBlobs()); - Assert.assertEquals("tinyInt1isBit", true, props.getTinyInt1isBit()); - Assert.assertEquals("yearIsDateType", true, props.getYearIsDateType()); - Assert.assertEquals("useBlobToStoreUTF8OutsideBMP", true, props.getUseBlobToStoreUTF8OutsideBMP()); - Assert.assertEquals("utf8OutsideBmpIncludedColumnNamePattern", "(foo|bar)?baz", props.getUtf8OutsideBmpIncludedColumnNamePattern()); - Assert.assertEquals("utf8OutsideBmpExcludedColumnNamePattern", "(foo|bar)?baz", props.getUtf8OutsideBmpExcludedColumnNamePattern()); - Assert.assertEquals("zeroDateTimeBehavior", Constants.ZeroDateTimeBehavior.CONVERTTONULL, props.getZeroDateTimeBehavior()); - Assert.assertEquals("characterEncoding", "utf-8", props.getEncoding()); - Assert.assertEquals("executeType", Constants.QueryExecuteType.STREAM, props.getExecuteType()); - Assert.assertEquals("twopcEnabled", true, props.getTwopcEnabled()); - Assert.assertEquals("includedFields", Query.ExecuteOptions.IncludedFields.TYPE_ONLY, props.getIncludedFields()); - Assert.assertEquals("includedFieldsCache", false, props.isIncludeAllFields()); - Assert.assertEquals("tabletType", Topodata.TabletType.BACKUP, props.getTabletType()); + assertEquals("blobsAreStrings", true, props.getBlobsAreStrings()); + assertEquals("functionsNeverReturnBlobs", true, props.getFunctionsNeverReturnBlobs()); + assertEquals("tinyInt1isBit", true, props.getTinyInt1isBit()); + assertEquals("yearIsDateType", true, props.getYearIsDateType()); + assertEquals("useBlobToStoreUTF8OutsideBMP", true, props.getUseBlobToStoreUTF8OutsideBMP()); + assertEquals("utf8OutsideBmpIncludedColumnNamePattern", "(foo|bar)?baz", props.getUtf8OutsideBmpIncludedColumnNamePattern()); + assertEquals("utf8OutsideBmpExcludedColumnNamePattern", "(foo|bar)?baz", props.getUtf8OutsideBmpExcludedColumnNamePattern()); + assertEquals("zeroDateTimeBehavior", ZeroDateTimeBehavior.CONVERTTONULL, props.getZeroDateTimeBehavior()); + assertEquals("characterEncoding", "utf-8", props.getEncoding()); + assertEquals("executeType", Constants.QueryExecuteType.STREAM, props.getExecuteType()); + assertEquals("twopcEnabled", true, props.getTwopcEnabled()); + assertEquals("includedFields", Query.ExecuteOptions.IncludedFields.TYPE_ONLY, props.getIncludedFields()); + assertEquals("includedFieldsCache", false, props.isIncludeAllFields()); + assertEquals("tabletType", Topodata.TabletType.BACKUP, props.getTabletType()); } - @Test(expected = SQLException.class) - public void testEncodingValidation() throws SQLException { + @Test + public void testEncodingValidation() { ConnectionProperties props = new ConnectionProperties(); Properties info = new Properties(); @@ -118,10 +127,9 @@ public void testEncodingValidation() throws SQLException { info.setProperty("characterEncoding", fakeEncoding); try { props.initializeProperties(info); - Assert.fail("should have failed to parse encoding " + fakeEncoding); + fail("should have failed to parse encoding " + fakeEncoding); } catch (SQLException e) { - Assert.assertEquals("Unsupported character encoding: " + fakeEncoding, e.getMessage()); - throw e; + assertEquals("Unsupported character encoding: " + fakeEncoding, e.getMessage()); } } @@ -129,14 +137,14 @@ public void testEncodingValidation() throws SQLException { public void testDriverPropertiesOutput() throws SQLException { Properties info = new Properties(); DriverPropertyInfo[] infos = ConnectionProperties.exposeAsDriverPropertyInfo(info, 0); - Assert.assertEquals(NUM_PROPS, infos.length); + assertEquals(NUM_PROPS, infos.length); // Test the expected fields for just 1 int indexForFullTest = 3; - Assert.assertEquals("executeType", infos[indexForFullTest].name); - Assert.assertEquals("Query execution type: simple or stream", + assertEquals("executeType", infos[indexForFullTest].name); + assertEquals("Query execution type: simple or stream", infos[indexForFullTest].description); - Assert.assertEquals(false, infos[indexForFullTest].required); + assertEquals(false, infos[indexForFullTest].required); Constants.QueryExecuteType[] enumConstants = Constants.QueryExecuteType.values(); String[] allowed = new String[enumConstants.length]; for (int i = 0; i < enumConstants.length; i++) { @@ -145,17 +153,17 @@ public void testDriverPropertiesOutput() throws SQLException { Assert.assertArrayEquals(allowed, infos[indexForFullTest].choices); // Test that name exists for the others, as a sanity check - Assert.assertEquals("dbName", infos[1].name); - Assert.assertEquals("characterEncoding", infos[2].name); - Assert.assertEquals("executeType", infos[3].name); - Assert.assertEquals("functionsNeverReturnBlobs", infos[4].name); - Assert.assertEquals("grpcRetriesEnabled", infos[5].name); - Assert.assertEquals("grpcRetriesBackoffMultiplier", infos[6].name); - Assert.assertEquals("grpcRetriesInitialBackoffMillis", infos[7].name); - Assert.assertEquals("grpcRetriesMaxBackoffMillis", infos[8].name); - Assert.assertEquals(Constants.Property.INCLUDED_FIELDS, infos[9].name); - Assert.assertEquals(Constants.Property.TABLET_TYPE, infos[21].name); - Assert.assertEquals(Constants.Property.TWOPC_ENABLED, infos[29].name); + assertEquals("dbName", infos[1].name); + assertEquals("characterEncoding", infos[2].name); + assertEquals("executeType", infos[3].name); + assertEquals("functionsNeverReturnBlobs", infos[4].name); + assertEquals("grpcRetriesEnabled", infos[5].name); + assertEquals("grpcRetriesBackoffMultiplier", infos[6].name); + assertEquals("grpcRetriesInitialBackoffMillis", infos[7].name); + assertEquals("grpcRetriesMaxBackoffMillis", infos[8].name); + assertEquals(Constants.Property.INCLUDED_FIELDS, infos[9].name); + assertEquals(Constants.Property.TABLET_TYPE, infos[21].name); + assertEquals(Constants.Property.TWOPC_ENABLED, infos[29].name); } @Test @@ -172,14 +180,12 @@ public void testValidBooleanValues() throws SQLException { info.setProperty(Constants.Property.TWOPC_ENABLED, "false-ish"); try { props.initializeProperties(info); - Assert.fail("should have thrown an exception on bad value false-ish"); + fail("should have thrown an exception on bad value false-ish"); } catch (IllegalArgumentException e) { - Assert.assertEquals( - "Property '" + Constants.Property.TWOPC_ENABLED + "' Value 'false-ish' not in the list of allowable values: " - + Arrays.toString(new String[] { Boolean.toString(true), Boolean.toString(false), "yes", "no"}) - , e.getMessage()); + String expected = String.format("Property '%s' Value 'false-ish' not in the list of allowable values: [true, false, yes, no]", + Constants.Property.TWOPC_ENABLED); + assertEquals(expected , e.getMessage()); } - } @Test @@ -190,9 +196,9 @@ public void testValidEnumValues() throws SQLException { info.setProperty("executeType", "foo"); try { props.initializeProperties(info); - Assert.fail("should have thrown an exception on bad value foo"); + fail("should have thrown an exception on bad value foo"); } catch (IllegalArgumentException e) { - Assert.assertEquals( + assertEquals( "Property 'executeType' Value 'foo' not in the list of allowable values: " + Arrays.toString(Constants.QueryExecuteType.values()) , e.getMessage()); @@ -205,16 +211,16 @@ public void testSettersUpdateCaches() throws SQLException { props.initializeProperties(new Properties()); // included fields and all boolean cache - Assert.assertEquals(Constants.DEFAULT_INCLUDED_FIELDS, props.getIncludedFields()); - Assert.assertEquals(true, props.isIncludeAllFields()); + assertEquals(DEFAULT_INCLUDED_FIELDS, props.getIncludedFields()); + assertTrue(props.isIncludeAllFields()); // execute type and simple boolean cache - Assert.assertEquals(Constants.DEFAULT_EXECUTE_TYPE, props.getExecuteType()); - Assert.assertEquals(Constants.DEFAULT_EXECUTE_TYPE == Constants.QueryExecuteType.SIMPLE, props.isSimpleExecute()); + assertEquals(DEFAULT_EXECUTE_TYPE, props.getExecuteType()); + assertEquals(DEFAULT_EXECUTE_TYPE == Constants.QueryExecuteType.SIMPLE, props.isSimpleExecute()); // tablet type and twopc - Assert.assertEquals(Constants.DEFAULT_TABLET_TYPE, props.getTabletType()); - Assert.assertEquals(false, props.getTwopcEnabled()); + assertEquals(DEFAULT_TABLET_TYPE, props.getTabletType()); + assertFalse(props.getTwopcEnabled()); props.setIncludedFields(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME); props.setExecuteType(Constants.QueryExecuteType.STREAM); @@ -222,16 +228,16 @@ public void testSettersUpdateCaches() throws SQLException { props.setTwopcEnabled(true); // included fields and all boolean cache - Assert.assertEquals(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME, props.getIncludedFields()); - Assert.assertEquals(false, props.isIncludeAllFields()); + assertEquals(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME, props.getIncludedFields()); + assertFalse(props.isIncludeAllFields()); // execute type and simple boolean cache - Assert.assertEquals(Constants.QueryExecuteType.STREAM, props.getExecuteType()); - Assert.assertEquals(Constants.DEFAULT_EXECUTE_TYPE != Constants.QueryExecuteType.SIMPLE, props.isSimpleExecute()); + assertEquals(Constants.QueryExecuteType.STREAM, props.getExecuteType()); + assertEquals(DEFAULT_EXECUTE_TYPE != Constants.QueryExecuteType.SIMPLE, props.isSimpleExecute()); // tablet type and twopc - Assert.assertEquals(Topodata.TabletType.BACKUP, props.getTabletType()); - Assert.assertEquals(true, props.getTwopcEnabled()); + assertEquals(Topodata.TabletType.BACKUP, props.getTabletType()); + assertTrue(props.getTwopcEnabled()); } @Test @@ -242,33 +248,33 @@ public void testTarget() throws SQLException { Properties info = new Properties(); info.setProperty(Constants.Property.KEYSPACE, "test_keyspace"); props.initializeProperties(info); - Assert.assertEquals("target", "test_keyspace@master", props.getTarget()); + assertEquals("target", "test_keyspace@master", props.getTarget()); // Setting keyspace and shard info = new Properties(); info.setProperty(Constants.Property.KEYSPACE, "test_keyspace"); info.setProperty(Constants.Property.SHARD, "80-c0"); props.initializeProperties(info); - Assert.assertEquals("target", "test_keyspace:80-c0@master", props.getTarget()); + assertEquals("target", "test_keyspace:80-c0@master", props.getTarget()); // Setting tablet type info = new Properties(); info.setProperty(Constants.Property.TABLET_TYPE, "replica"); props.initializeProperties(info); - Assert.assertEquals("target", "@replica", props.getTarget()); + assertEquals("target", "@replica", props.getTarget()); // Setting shard which will have no impact without keyspace info = new Properties(); info.setProperty(Constants.Property.SHARD, "80-c0"); props.initializeProperties(info); - Assert.assertEquals("target", "@master", props.getTarget()); + assertEquals("target", "@master", props.getTarget()); // Setting shard and tablet type. Shard will have no impact. info = new Properties(); info.setProperty(Constants.Property.SHARD, "80-c0"); info.setProperty(Constants.Property.TABLET_TYPE, "replica"); props.initializeProperties(info); - Assert.assertEquals("target", "@replica", props.getTarget()); + assertEquals("target", "@replica", props.getTarget()); // Setting keyspace, shard and tablet type. info = new Properties(); @@ -276,7 +282,7 @@ public void testTarget() throws SQLException { info.setProperty(Constants.Property.SHARD, "80-c0"); info.setProperty(Constants.Property.TABLET_TYPE, "rdonly"); props.initializeProperties(info); - Assert.assertEquals("target", "test_keyspace:80-c0@rdonly", props.getTarget()); + assertEquals("target", "test_keyspace:80-c0@rdonly", props.getTarget()); // Setting keyspace, shard, tablet type and target. Target supersede others. info = new Properties(); @@ -285,6 +291,6 @@ public void testTarget() throws SQLException { info.setProperty(Constants.Property.TABLET_TYPE, "rdonly"); info.setProperty(Constants.Property.TARGET, "dummy"); props.initializeProperties(info); - Assert.assertEquals("target", "dummy", props.getTarget()); + assertEquals("target", "dummy", props.getTarget()); } } diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java index 3121857c70f..8a25caf7e77 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java @@ -1,12 +1,12 @@ /* * Copyright 2017 Google Inc. - * + * * Licensed 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. @@ -23,7 +23,7 @@ import java.sql.Statement; import java.util.Properties; -import org.junit.Assert; +import io.vitess.proto.Query.ExecuteOptions.TransactionIsolation; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -35,221 +35,229 @@ import io.vitess.proto.Topodata; import io.vitess.util.Constants; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + /** * Created by harshit.gangal on 19/01/16. */ @RunWith(PowerMockRunner.class) public class VitessConnectionTest extends BaseTest { - @Test public void testVitessConnection() throws SQLException { + @Test + public void testVitessConnection() throws SQLException { VitessConnection vitessConnection = new VitessConnection(dbURL, new Properties()); - Assert.assertEquals(false, vitessConnection.isClosed()); - Assert.assertNull(vitessConnection.getDbProperties()); + assertFalse(vitessConnection.isClosed()); + assertNull(vitessConnection.getDbProperties()); } - @Test public void testCreateStatement() throws SQLException { + @Test + public void testCreateStatement() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); Statement statement = vitessConnection.createStatement(); - Assert.assertEquals(vitessConnection, statement.getConnection()); + assertEquals(vitessConnection, statement.getConnection()); } - - @Test(expected = SQLException.class) public void testCreateStatementForClose() - throws SQLException { + @Test + public void testCreateStatementForClose() + throws SQLException { VitessConnection vitessConnection = getVitessConnection(); - vitessConnection.close(); - try { - Statement statement = vitessConnection.createStatement(); - } catch (SQLException e) { - throw new SQLException(Constants.SQLExceptionMessages.CONN_CLOSED); - } + assertFailsOnClosedConnection(vitessConnection, vitessConnection::createStatement); } - @Test public void testnativeSQL() throws SQLException { + @Test + public void testnativeSQL() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); - Assert.assertEquals("query", vitessConnection.nativeSQL("query")); + assertEquals("query", vitessConnection.nativeSQL("query")); } - @Test public void testCreatePreperedStatement() throws SQLException { + @Test + public void testCreatePreperedStatement() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); PreparedStatement preparedStatementstatement = vitessConnection.prepareStatement("query"); - Assert.assertEquals(vitessConnection, preparedStatementstatement.getConnection()); + assertEquals(vitessConnection, preparedStatementstatement.getConnection()); } - - @Test(expected = SQLException.class) public void testCreatePreperedStatementForClose() - throws SQLException { + @Test + public void testCreatePreparedStatementForClose() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); - vitessConnection.close(); - try { - PreparedStatement preparedStatementstatement = - vitessConnection.prepareStatement("query"); - } catch (SQLException e) { - throw new SQLException(Constants.SQLExceptionMessages.CONN_CLOSED); - } + assertFailsOnClosedConnection(vitessConnection, () -> vitessConnection.prepareStatement("query")); } - @Test public void testDefaultGetAutoCommit() throws SQLException { + @Test + public void testDefaultGetAutoCommit() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); - Assert.assertEquals(true, vitessConnection.getAutoCommit()); + assertTrue(vitessConnection.getAutoCommit()); } - @Test(expected = SQLException.class) public void testDefaultGetAutoCommitForClose() - throws SQLException { + @Test + public void testDefaultGetAutoCommitForClose() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); - vitessConnection.close(); - try { - boolean autoCommit = vitessConnection.getAutoCommit(); - } catch (SQLException e) { - throw new SQLException(Constants.SQLExceptionMessages.CONN_CLOSED); - } + assertFailsOnClosedConnection(vitessConnection, vitessConnection::getAutoCommit); } - @Test public void testDefaultSetAutoCommit() throws SQLException { + @Test + public void testDefaultSetAutoCommit() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); vitessConnection.setAutoCommit(false); - Assert.assertEquals(false, vitessConnection.getAutoCommit()); + assertFalse(vitessConnection.getAutoCommit()); } - @Test(expected = SQLException.class) public void testDefaultSetAutoCommitForClose() - throws SQLException { + @Test + public void testDefaultSetAutoCommitForClose() + throws SQLException { VitessConnection vitessConnection = getVitessConnection(); - vitessConnection.close(); - try { - boolean autoCommit = vitessConnection.getAutoCommit(); - } catch (SQLException e) { - throw new SQLException(Constants.SQLExceptionMessages.CONN_CLOSED); - } + assertFailsOnClosedConnection(vitessConnection, () -> vitessConnection.setAutoCommit(false)); } - @Test public void testCommit() throws SQLException { + @Test + public void testCommit() throws Exception { VTSession mockSession = PowerMockito.mock(VTSession.class); VitessConnection vitessConnection = getVitessConnection(); - try { - Field privateVTSessionField = VitessConnection.class.getDeclaredField("vtSession"); - privateVTSessionField.setAccessible(true); - privateVTSessionField.set(vitessConnection, mockSession); - PowerMockito.when(mockSession.isInTransaction()).thenReturn(false); - PowerMockito.when(mockSession.isAutoCommit()).thenReturn(false); - } catch (NoSuchFieldException | IllegalAccessException e) { - Assert.fail(e.getMessage()); - } + Field privateVTSessionField = VitessConnection.class.getDeclaredField("vtSession"); + privateVTSessionField.setAccessible(true); + privateVTSessionField.set(vitessConnection, mockSession); + PowerMockito.when(mockSession.isInTransaction()).thenReturn(false); + PowerMockito.when(mockSession.isAutoCommit()).thenReturn(false); vitessConnection.commit(); } - @Test(expected = SQLException.class) public void testCommitForException() throws SQLException { + @Test(expected = SQLException.class) + public void testCommitForException() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); vitessConnection.setAutoCommit(true); vitessConnection.commit(); } - @Test public void testRollback() throws SQLException { + @Test + public void testRollback() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); vitessConnection.setAutoCommit(false); vitessConnection.rollback(); } - @Test(expected = SQLException.class) public void testRollbackForException() - throws SQLException { + @Test(expected = SQLException.class) + public void testRollbackForException() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); vitessConnection.setAutoCommit(true); vitessConnection.rollback(); } - @Test public void testClosed() throws SQLException { + @Test + public void testClosed() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); vitessConnection.setAutoCommit(false); vitessConnection.close(); - Assert.assertEquals(true, vitessConnection.isClosed()); + assertTrue(vitessConnection.isClosed()); } - @Test(expected = SQLException.class) public void testClosedForException() throws SQLException { + @Test(expected = SQLException.class) + public void testClosedForException() throws Exception { VTSession mockSession = PowerMockito.mock(VTSession.class); VitessConnection vitessConnection = getVitessConnection(); - try { - Field privateVTSessionField = VitessConnection.class.getDeclaredField("vtSession"); - privateVTSessionField.setAccessible(true); - privateVTSessionField.set(vitessConnection, mockSession); - //vtSession.setSession(mockSession.getSession()); - PowerMockito.when(mockSession.isInTransaction()).thenReturn(true); - PowerMockito.when(mockSession.isAutoCommit()).thenReturn(true); - } catch (NoSuchFieldException | IllegalAccessException e) { - Assert.fail(e.getMessage()); - } + Field privateVTSessionField = VitessConnection.class.getDeclaredField("vtSession"); + privateVTSessionField.setAccessible(true); + privateVTSessionField.set(vitessConnection, mockSession); + PowerMockito.when(mockSession.isInTransaction()).thenReturn(true); + PowerMockito.when(mockSession.isAutoCommit()).thenReturn(true); vitessConnection.close(); } - @Test public void testGetCatalog() throws SQLException { + @Test + public void testGetCatalog() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); - Assert.assertEquals("keyspace", vitessConnection.getCatalog()); + assertEquals("keyspace", vitessConnection.getCatalog()); } - @Test public void testSetCatalog() throws SQLException { + @Test + public void testSetCatalog() throws SQLException { VitessConnection vitessConnection = getVitessConnection(); vitessConnection.setCatalog("myDB"); - Assert.assertEquals("myDB", vitessConnection.getCatalog()); + assertEquals("myDB", vitessConnection.getCatalog()); } - @Test public void testPropertiesFromJdbcUrl() throws SQLException { + @Test + public void testPropertiesFromJdbcUrl() throws SQLException { String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica&includedFields=type_and_name&blobsAreStrings=yes"; VitessConnection conn = new VitessConnection(url, new Properties()); // Properties from the url should be passed into the connection properties, and override whatever defaults we've defined - Assert.assertEquals(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME, conn.getIncludedFields()); - Assert.assertEquals(false, conn.isIncludeAllFields()); - Assert.assertEquals(Topodata.TabletType.REPLICA, conn.getTabletType()); - Assert.assertEquals(true, conn.getBlobsAreStrings()); + assertEquals(Query.ExecuteOptions.IncludedFields.TYPE_AND_NAME, conn.getIncludedFields()); + assertFalse(conn.isIncludeAllFields()); + assertEquals(Topodata.TabletType.REPLICA, conn.getTabletType()); + assertTrue(conn.getBlobsAreStrings()); } - @Test public void testClientFoundRows() throws SQLException { + @Test + public void testClientFoundRows() throws SQLException { String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica&useAffectedRows=true"; VitessConnection conn = new VitessConnection(url, new Properties()); - Assert.assertEquals(true, conn.getUseAffectedRows()); - Assert.assertEquals(false, conn.getVtSession().getSession().getOptions().getClientFoundRows()); + assertTrue(conn.getUseAffectedRows()); + assertFalse(conn.getVtSession().getSession().getOptions().getClientFoundRows()); + } - url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica&useAffectedRows=false"; - conn = new VitessConnection(url, new Properties()); + @Test + public void testClientFoundRows2() throws SQLException { + String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica&useAffectedRows=false"; + VitessConnection conn = new VitessConnection(url, new Properties()); - Assert.assertEquals(false, conn.getUseAffectedRows()); - Assert.assertEquals(true, conn.getVtSession().getSession().getOptions().getClientFoundRows()); + assertFalse(conn.getUseAffectedRows()); + assertTrue(conn.getVtSession().getSession().getOptions().getClientFoundRows()); } - @Test public void testWorkload() throws SQLException { + @Test + public void testWorkload() throws SQLException { for (Query.ExecuteOptions.Workload workload : Query.ExecuteOptions.Workload.values()) { if (workload == Query.ExecuteOptions.Workload.UNRECOGNIZED) { continue; } String url = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?TABLET_TYPE=replica&workload=" + workload.toString().toLowerCase(); VitessConnection conn = new VitessConnection(url, new Properties()); - - Assert.assertEquals(workload, conn.getWorkload()); - Assert.assertEquals(workload, conn.getVtSession().getSession().getOptions().getWorkload()); + + assertEquals(workload, conn.getWorkload()); + assertEquals(workload, conn.getVtSession().getSession().getOptions().getWorkload()); } } - @Test public void testTransactionIsolation() throws SQLException { + @Test + public void testTransactionIsolation() throws SQLException { VitessConnection conn = Mockito.spy(getVitessConnection()); - Mockito.doReturn(new DBProperties("random", "random", "random", Connection.TRANSACTION_REPEATABLE_READ, "random")) - .when(conn) - .getDbProperties(); - Mockito.doReturn(new VitessMySQLDatabaseMetadata(conn)).when(conn).getMetaData(); + doReturn(new DBProperties("random", "random", "random", Connection.TRANSACTION_REPEATABLE_READ, "random")) + .when(conn) + .getDbProperties(); + doReturn(new VitessMySQLDatabaseMetadata(conn)).when(conn).getMetaData(); - Assert.assertEquals(Query.ExecuteOptions.TransactionIsolation.DEFAULT, conn.getVtSession().getSession().getOptions().getTransactionIsolation()); - Assert.assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn.getTransactionIsolation()); + assertEquals(TransactionIsolation.DEFAULT, conn.getVtSession().getSession().getOptions().getTransactionIsolation()); + assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn.getTransactionIsolation()); conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - Assert.assertEquals(Query.ExecuteOptions.TransactionIsolation.READ_COMMITTED, conn.getVtSession().getSession().getOptions().getTransactionIsolation()); - Assert.assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation()); + assertEquals(TransactionIsolation.READ_COMMITTED, conn.getVtSession().getSession().getOptions().getTransactionIsolation()); + assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn.getTransactionIsolation()); - VitessStatement statement = Mockito.mock(VitessStatement.class); - Mockito.when(conn.createStatement()).thenReturn(statement); - Mockito.when(conn.isInTransaction()).thenReturn(true); + VitessStatement statement = mock(VitessStatement.class); + when(conn.createStatement()).thenReturn(statement); + when(conn.isInTransaction()).thenReturn(true); conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); - Mockito.verify(statement).executeUpdate("rollback"); - Assert.assertEquals(Query.ExecuteOptions.TransactionIsolation.READ_UNCOMMITTED, conn.getVtSession().getSession().getOptions().getTransactionIsolation()); - Assert.assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn.getTransactionIsolation()); + verify(statement).executeUpdate("rollback"); + assertEquals(TransactionIsolation.READ_UNCOMMITTED, conn.getVtSession().getSession().getOptions().getTransactionIsolation()); + assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn.getTransactionIsolation()); } + + interface Runthis { + void run() throws SQLException; + } + + private void assertFailsOnClosedConnection(VitessConnection connection, Runthis failingRunnable) throws SQLException { + connection.close(); + try { + failingRunnable.run(); + fail("expected this to fail on a closed connection"); + } catch (SQLException e) { + assertEquals(e.getMessage(), Constants.SQLExceptionMessages.CONN_CLOSED); + } + } + } diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java index ba6f756545e..b3fdd1388a1 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java @@ -1,12 +1,12 @@ /* * Copyright 2017 Google Inc. - * + * * Licensed 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. @@ -20,12 +20,16 @@ import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.Properties; + import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import io.vitess.util.Constants; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + /** * Created by harshit.gangal on 19/01/16. */ @@ -34,84 +38,80 @@ public class VitessDriverTest { private static VitessDriver driver = new VitessDriver(); String dbURL = - "jdbc:vitess://localhost:9000/shipment/vt_shipment?tabletType=master&executeType=stream&userName" - + "=user"; + "jdbc:vitess://localhost:9000/shipment/vt_shipment?tabletType=master&executeType=stream&userName" + + "=user"; - @BeforeClass public static void setUp() { + @BeforeClass + public static void setUp() { // load Vitess driver try { Class.forName("io.vitess.jdbc.VitessDriver"); } catch (ClassNotFoundException e) { - Assert.fail("Driver is not in the CLASSPATH -> " + e); + fail("Driver is not in the CLASSPATH -> " + e); } } - @Test public void testConnect() { - try { - VitessConnection connection = + @Test + public void testConnect() throws SQLException { + VitessConnection connection = (VitessConnection) DriverManager.getConnection(dbURL, new Properties()); - Assert.assertEquals(connection.getUrl().getUrl(), dbURL); - } catch (SQLException e) { - Assert.fail("SQLException Not Expected"); - } + assertEquals(connection.getUrl().getUrl(), dbURL); } - @Test public void testAcceptsURL() { - try { - Assert.assertEquals(true, driver.acceptsURL(dbURL)); - } catch (SQLException e) { - Assert.fail("SQLException Not Expected"); - } + @Test + public void testAcceptsURL() { + assertEquals(true, driver.acceptsURL(dbURL)); } - @Test public void testAcceptsMalformedURL() { - try { - String url = + @Test + public void testAcceptsMalformedURL() { + String url = "jdbc:MalfromdedUrl://localhost:9000/shipment/vt_shipment?tabletType=master"; - Assert.assertEquals(false, driver.acceptsURL(url)); - } catch (SQLException e) { - Assert.fail("SQLException Not Expected"); - } + assertEquals(false, driver.acceptsURL(url)); } - @Test public void testGetPropertyInfo() throws SQLException { + @Test + public void testGetPropertyInfo() throws SQLException { // Used to ensure that we're properly adding the below URL-based properties at the beginning // of the full ConnectionProperties configuration DriverPropertyInfo[] underlying = ConnectionProperties.exposeAsDriverPropertyInfo(new Properties(), 0); int additionalProp = 2; DriverPropertyInfo[] driverPropertyInfos = driver.getPropertyInfo(dbURL, null); - Assert.assertEquals(underlying.length + additionalProp, driverPropertyInfos.length); + assertEquals(underlying.length + additionalProp, driverPropertyInfos.length); - Assert.assertEquals(driverPropertyInfos[0].description, Constants.VITESS_HOST); - Assert.assertEquals(driverPropertyInfos[0].required, true); - Assert.assertEquals(driverPropertyInfos[0].name, Constants.Property.HOST); - Assert.assertEquals(driverPropertyInfos[0].value, "localhost"); + assertEquals(driverPropertyInfos[0].description, Constants.VITESS_HOST); + assertEquals(driverPropertyInfos[0].required, true); + assertEquals(driverPropertyInfos[0].name, Constants.Property.HOST); + assertEquals(driverPropertyInfos[0].value, "localhost"); - Assert.assertEquals(driverPropertyInfos[1].description, Constants.VITESS_PORT); - Assert.assertEquals(driverPropertyInfos[1].required, false); - Assert.assertEquals(driverPropertyInfos[1].name, Constants.Property.PORT); - Assert.assertEquals(driverPropertyInfos[1].value, "9000"); + assertEquals(driverPropertyInfos[1].description, Constants.VITESS_PORT); + assertEquals(driverPropertyInfos[1].required, false); + assertEquals(driverPropertyInfos[1].name, Constants.Property.PORT); + assertEquals(driverPropertyInfos[1].value, "9000"); // Validate the remainder of the driver properties match up with the underlying for (int i = additionalProp; i < driverPropertyInfos.length; i++) { - Assert.assertEquals(underlying[i - additionalProp].description, driverPropertyInfos[i].description); - Assert.assertEquals(underlying[i - additionalProp].required, driverPropertyInfos[i].required); - Assert.assertEquals(underlying[i - additionalProp].name, driverPropertyInfos[i].name); - Assert.assertEquals(underlying[i - additionalProp].value, driverPropertyInfos[i].value); + assertEquals(underlying[i - additionalProp].description, driverPropertyInfos[i].description); + assertEquals(underlying[i - additionalProp].required, driverPropertyInfos[i].required); + assertEquals(underlying[i - additionalProp].name, driverPropertyInfos[i].name); + assertEquals(underlying[i - additionalProp].value, driverPropertyInfos[i].value); } } - @Test public void testGetMajorVersion() { - Assert.assertEquals(driver.getMajorVersion(), Constants.DRIVER_MAJOR_VERSION); + @Test + public void testGetMajorVersion() { + assertEquals(driver.getMajorVersion(), Constants.DRIVER_MAJOR_VERSION); } - @Test public void testGetMinorVersion() { - Assert.assertEquals(driver.getMinorVersion(), Constants.DRIVER_MINOR_VERSION); + @Test + public void testGetMinorVersion() { + assertEquals(driver.getMinorVersion(), Constants.DRIVER_MINOR_VERSION); } - @Test public void testJdbcCompliant() { - Assert.assertEquals(false, driver.jdbcCompliant()); + @Test + public void testJdbcCompliant() { + assertEquals(false, driver.jdbcCompliant()); } } diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java index 31b7356f1f0..9fabc9be6d4 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java @@ -57,6 +57,14 @@ import io.vitess.proto.Vtrpc; import io.vitess.util.Constants; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyString; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; + /** * Created by harshit.gangal on 09/02/16. @@ -69,51 +77,50 @@ private String sqlUpdate = "update test_table set msg = null"; private String sqlInsert = "insert into test_table(msg) values (?)"; - @Test public void testStatementExecute() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test public void testStatementExecute() { + VitessConnection mockConn = mock(VitessConnection.class); VitessPreparedStatement preparedStatement; try { preparedStatement = new VitessPreparedStatement(mockConn, sqlShow); preparedStatement.executeQuery(sqlSelect); - Assert.fail("Should have thrown exception for calling this method"); + fail("Should have thrown exception for calling this method"); } catch (SQLException ex) { - Assert.assertEquals("This method cannot be called using this class object", + assertEquals("This method cannot be called using this class object", ex.getMessage()); } try { preparedStatement = new VitessPreparedStatement(mockConn, sqlShow); preparedStatement.executeUpdate(sqlUpdate); - Assert.fail("Should have thrown exception for calling this method"); + fail("Should have thrown exception for calling this method"); } catch (SQLException ex) { - Assert.assertEquals("This method cannot be called using this class object", + assertEquals("This method cannot be called using this class object", ex.getMessage()); } try { preparedStatement = new VitessPreparedStatement(mockConn, sqlShow); preparedStatement.execute(sqlShow); - Assert.fail("Should have thrown exception for calling this method"); + fail("Should have thrown exception for calling this method"); } catch (SQLException ex) { - Assert.assertEquals("This method cannot be called using this class object", + assertEquals("This method cannot be called using this class object", ex.getMessage()); } } @Test public void testExecuteQuery() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockConn.getExecuteType()) + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn.execute(any(Context.class), anyString(), anyMap(),any(VTSession.class))). + thenReturn(mockSqlFutureCursor); + when(mockConn.getExecuteType()) .thenReturn(Constants.QueryExecuteType.SIMPLE); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(true); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockConn.isSimpleExecute()).thenReturn(true); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); VitessPreparedStatement preparedStatement; try { @@ -121,64 +128,64 @@ //Empty Sql Statement try { new VitessPreparedStatement(mockConn, ""); - Assert.fail("Should have thrown exception for empty sql"); + fail("Should have thrown exception for empty sql"); } catch (SQLException ex) { - Assert.assertEquals("SQL statement is not valid", ex.getMessage()); + assertEquals("SQL statement is not valid", ex.getMessage()); } //show query preparedStatement = new VitessPreparedStatement(mockConn, sqlShow); ResultSet rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); //select on replica with bind variables preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); //select on replica without bind variables preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); //select on master rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); try { //when returned cursor is null - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(null); + when(mockSqlFutureCursor.checkedGet()).thenReturn(null); preparedStatement.executeQuery(); - Assert.fail("Should have thrown exception for cursor null"); + fail("Should have thrown exception for cursor null"); } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); + assertEquals("Failed to execute this method", ex.getMessage()); } } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + fail("Test failed " + e.getMessage()); } } @Test public void testExecuteQueryWithStream() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockCursor); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockConn.getExecuteType()) + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockCursor); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockConn.getExecuteType()) .thenReturn(Constants.QueryExecuteType.STREAM); VitessPreparedStatement preparedStatement; @@ -187,65 +194,65 @@ //Empty Sql Statement try { new VitessPreparedStatement(mockConn, ""); - Assert.fail("Should have thrown exception for empty sql"); + fail("Should have thrown exception for empty sql"); } catch (SQLException ex) { - Assert.assertEquals("SQL statement is not valid", ex.getMessage()); + assertEquals("SQL statement is not valid", ex.getMessage()); } //show query preparedStatement = new VitessPreparedStatement(mockConn, sqlShow); ResultSet rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); //select on replica with bind variables preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); //select on replica without bind variables preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); //select on master rs = preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); try { //when returned cursor is null - PowerMockito.when(mockVtGateConn - .streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(null); + when(mockVtGateConn + .streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(null); preparedStatement.executeQuery(); - Assert.fail("Should have thrown exception for cursor null"); + fail("Should have thrown exception for cursor null"); } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); + assertEquals("Failed to execute this method", ex.getMessage()); } } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + fail("Test failed " + e.getMessage()); } } @Test public void testExecuteUpdate() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - List fieldList = PowerMockito.mock(ArrayList.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + List fieldList = mock(ArrayList.class); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); VitessPreparedStatement preparedStatement; try { @@ -255,76 +262,76 @@ new VitessPreparedStatement(mockConn, sqlUpdate, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); int updateCount = preparedStatement.executeUpdate(); - Assert.assertEquals(0, updateCount); + assertEquals(0, updateCount); //tx is null & autoCommit is true - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); + when(mockConn.getAutoCommit()).thenReturn(true); preparedStatement = new VitessPreparedStatement(mockConn, sqlUpdate); updateCount = preparedStatement.executeUpdate(); - Assert.assertEquals(0, updateCount); + assertEquals(0, updateCount); //cursor fields is not null - PowerMockito.when(mockCursor.getFields()).thenReturn(fieldList); - PowerMockito.when(fieldList.isEmpty()).thenReturn(false); + when(mockCursor.getFields()).thenReturn(fieldList); + when(fieldList.isEmpty()).thenReturn(false); try { preparedStatement.executeUpdate(); - Assert.fail("Should have thrown exception for field not null"); + fail("Should have thrown exception for field not null"); } catch (SQLException ex) { - Assert.assertEquals("ResultSet generation is not allowed through this method", + assertEquals("ResultSet generation is not allowed through this method", ex.getMessage()); } //cursor is null - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(null); + when(mockSqlFutureCursor.checkedGet()).thenReturn(null); try { preparedStatement.executeUpdate(); - Assert.fail("Should have thrown exception for cursor null"); + fail("Should have thrown exception for cursor null"); } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); + assertEquals("Failed to execute this method", ex.getMessage()); } //read only - PowerMockito.when(mockConn.isReadOnly()).thenReturn(true); + when(mockConn.isReadOnly()).thenReturn(true); try { preparedStatement.executeUpdate(); - Assert.fail("Should have thrown exception for read only"); + fail("Should have thrown exception for read only"); } catch (SQLException ex) { - Assert.assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); + assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); } //read only - PowerMockito.when(mockConn.isReadOnly()).thenReturn(true); + when(mockConn.isReadOnly()).thenReturn(true); try { preparedStatement.executeBatch(); - Assert.fail("Should have thrown exception for read only"); + fail("Should have thrown exception for read only"); } catch (SQLException ex) { - Assert.assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); + assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); } } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + fail("Test failed " + e.getMessage()); } } @Test public void testExecute() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - List mockFieldList = PowerMockito.spy(new ArrayList()); + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + List mockFieldList = PowerMockito.spy(new ArrayList<>()); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockConn.getExecuteType()) + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockConn.getExecuteType()) .thenReturn(Constants.QueryExecuteType.SIMPLE); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(true); + when(mockConn.isSimpleExecute()).thenReturn(true); - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); + when(mockConn.getAutoCommit()).thenReturn(true); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(mockFieldList); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(mockFieldList); VitessPreparedStatement preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect, ResultSet.TYPE_FORWARD_ONLY, @@ -332,7 +339,7 @@ try { int fieldSize = 5; - PowerMockito.when(mockCursor.getFields()).thenReturn(mockFieldList); + when(mockCursor.getFields()).thenReturn(mockFieldList); PowerMockito.doReturn(fieldSize).when(mockFieldList).size(); PowerMockito.doReturn(false).when(mockFieldList).isEmpty(); boolean hasResultSet = preparedStatement.execute(); @@ -345,26 +352,26 @@ Assert.assertNotNull(preparedStatement.getResultSet()); int mockUpdateCount = 10; - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); - PowerMockito.when(mockCursor.getRowsAffected()).thenReturn((long) mockUpdateCount); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + when(mockCursor.getRowsAffected()).thenReturn((long) mockUpdateCount); preparedStatement = new VitessPreparedStatement(mockConn, sqlUpdate); hasResultSet = preparedStatement.execute(); Assert.assertFalse(hasResultSet); Assert.assertNull(preparedStatement.getResultSet()); - Assert.assertEquals(mockUpdateCount, preparedStatement.getUpdateCount()); + assertEquals(mockUpdateCount, preparedStatement.getUpdateCount()); //cursor is null - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(null); + when(mockSqlFutureCursor.checkedGet()).thenReturn(null); try { preparedStatement = new VitessPreparedStatement(mockConn, sqlShow); preparedStatement.execute(); - Assert.fail("Should have thrown exception for cursor null"); + fail("Should have thrown exception for cursor null"); } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); + assertEquals("Failed to execute this method", ex.getMessage()); } } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + fail("Test failed " + e.getMessage()); } } @@ -376,82 +383,82 @@ } private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRunExecute, boolean shouldRunStreamExecute) throws SQLException { - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(simpleExecute); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + VitessConnection mockConn = mock(VitessConnection.class); + when(mockConn.isSimpleExecute()).thenReturn(simpleExecute); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockVtGateConn - .streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockCursor); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockVtGateConn + .streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockCursor); VitessPreparedStatement statement = new VitessPreparedStatement(mockConn, sqlSelect); statement.setFetchSize(fetchSize); statement.executeQuery(); if (shouldRunExecute) { - Mockito.verify(mockVtGateConn, Mockito.times(2)).execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class)); + Mockito.verify(mockVtGateConn, Mockito.times(2)).execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class)); } if (shouldRunStreamExecute) { - Mockito.verify(mockVtGateConn).streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class)); + Mockito.verify(mockVtGateConn).streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class)); } } @Test public void testGetUpdateCount() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFuture = PowerMockito.mock(SQLFuture.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFuture); - PowerMockito.when(mockSqlFuture.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFuture = mock(SQLFuture.class); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFuture); + when(mockSqlFuture.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); VitessPreparedStatement preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect); try { - PowerMockito.when(mockCursor.getRowsAffected()).thenReturn(10L); + when(mockCursor.getRowsAffected()).thenReturn(10L); int updateCount = preparedStatement.executeUpdate(); - Assert.assertEquals(10L, updateCount); - Assert.assertEquals(10L, preparedStatement.getUpdateCount()); + assertEquals(10L, updateCount); + assertEquals(10L, preparedStatement.getUpdateCount()); // Truncated Update Count - PowerMockito.when(mockCursor.getRowsAffected()) + when(mockCursor.getRowsAffected()) .thenReturn((long) Integer.MAX_VALUE + 10); updateCount = preparedStatement.executeUpdate(); - Assert.assertEquals(Integer.MAX_VALUE, updateCount); - Assert.assertEquals(Integer.MAX_VALUE, preparedStatement.getUpdateCount()); + assertEquals(Integer.MAX_VALUE, updateCount); + assertEquals(Integer.MAX_VALUE, preparedStatement.getUpdateCount()); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(true); + when(mockConn.isSimpleExecute()).thenReturn(true); preparedStatement.executeQuery(); - Assert.assertEquals(-1, preparedStatement.getUpdateCount()); + assertEquals(-1, preparedStatement.getUpdateCount()); } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + fail("Test failed " + e.getMessage()); } } @Test public void testSetParameters() throws Exception { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + VitessConnection mockConn = mock(VitessConnection.class); Mockito.when(mockConn.getTreatUtilDateAsTimestamp()).thenReturn(true); VitessPreparedStatement preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect); - Boolean boolValue = Boolean.TRUE; + Boolean boolValue = true; Byte byteValue = Byte.MAX_VALUE; Short shortValue = Short.MAX_VALUE; Integer intValue = Integer.MAX_VALUE; @@ -519,57 +526,57 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun bindVariablesMap.setAccessible(true); Map bindVariables = (Map) bindVariablesMap.get(preparedStatement); - Assert.assertEquals(null, bindVariables.get("v1")); - Assert.assertEquals(boolValue, bindVariables.get("v2")); - Assert.assertEquals(byteValue, bindVariables.get("v3")); - Assert.assertEquals(shortValue, bindVariables.get("v4")); - Assert.assertEquals(intValue, bindVariables.get("v5")); - Assert.assertEquals(longValue, bindVariables.get("v6")); - Assert.assertEquals(floatValue, bindVariables.get("v7")); - Assert.assertEquals(doubleValue, bindVariables.get("v8")); - Assert.assertEquals(bigDecimalValue, bindVariables.get("v9")); - Assert.assertEquals(bigIntegerValue, bindVariables.get("v10")); - Assert.assertEquals(stringValue, bindVariables.get("v11")); - Assert.assertEquals(bytesValue, bindVariables.get("v12")); - Assert.assertEquals(dateValue.toString(), bindVariables.get("v13")); - Assert.assertEquals(timeValue.toString(), bindVariables.get("v14")); - Assert.assertEquals(timestampValue.toString(), bindVariables.get("v15")); - Assert.assertEquals(dateValue.toString(), bindVariables.get("v16")); - Assert.assertEquals(timeValue.toString(), bindVariables.get("v17")); - Assert.assertEquals(timestampValue.toString(), bindVariables.get("v18")); - Assert.assertEquals(boolValue, bindVariables.get("v19")); - Assert.assertEquals(byteValue, bindVariables.get("v20")); - Assert.assertEquals(shortValue, bindVariables.get("v21")); - Assert.assertEquals(intValue, bindVariables.get("v22")); - Assert.assertEquals(longValue, bindVariables.get("v23")); - Assert.assertEquals(floatValue, bindVariables.get("v24")); - Assert.assertEquals(doubleValue, bindVariables.get("v25")); - Assert.assertEquals(bigDecimalValue, bindVariables.get("v26")); - Assert.assertEquals(bigIntegerValue, bindVariables.get("v27")); - Assert.assertEquals(stringValue, bindVariables.get("v28")); - Assert.assertEquals(dateValue.toString(), bindVariables.get("v29")); - Assert.assertEquals(timeValue.toString(), bindVariables.get("v30")); - Assert.assertEquals(timestampValue.toString(), bindVariables.get("v31")); - Assert.assertEquals("a", bindVariables.get("v32")); - Assert.assertEquals(null, bindVariables.get("v33")); - Assert.assertEquals(boolValue, bindVariables.get("v34")); - Assert.assertEquals(shortValue.intValue(), bindVariables.get("v35")); - Assert.assertEquals(longValue, bindVariables.get("v36")); - Assert.assertEquals((double) floatValue, (double) bindVariables.get("v37"), 0.1); - Assert.assertEquals(doubleValue, (double) bindVariables.get("v38"), 0.1); - Assert.assertEquals(expectedDecimalValue, bindVariables.get("v39")); - Assert.assertEquals(stringValue, bindVariables.get("v40")); - Assert.assertEquals(dateValue.toString(), bindVariables.get("v41")); - Assert.assertEquals(timeValue.toString(), bindVariables.get("v42")); - Assert.assertEquals(timestampValue.toString(), bindVariables.get("v43")); - Assert.assertEquals("clob", bindVariables.get("v44")); + assertEquals(null, bindVariables.get("v1")); + assertEquals(boolValue, bindVariables.get("v2")); + assertEquals(byteValue, bindVariables.get("v3")); + assertEquals(shortValue, bindVariables.get("v4")); + assertEquals(intValue, bindVariables.get("v5")); + assertEquals(longValue, bindVariables.get("v6")); + assertEquals(floatValue, bindVariables.get("v7")); + assertEquals(doubleValue, bindVariables.get("v8")); + assertEquals(bigDecimalValue, bindVariables.get("v9")); + assertEquals(bigIntegerValue, bindVariables.get("v10")); + assertEquals(stringValue, bindVariables.get("v11")); + assertEquals(bytesValue, bindVariables.get("v12")); + assertEquals(dateValue.toString(), bindVariables.get("v13")); + assertEquals(timeValue.toString(), bindVariables.get("v14")); + assertEquals(timestampValue.toString(), bindVariables.get("v15")); + assertEquals(dateValue.toString(), bindVariables.get("v16")); + assertEquals(timeValue.toString(), bindVariables.get("v17")); + assertEquals(timestampValue.toString(), bindVariables.get("v18")); + assertEquals(boolValue, bindVariables.get("v19")); + assertEquals(byteValue, bindVariables.get("v20")); + assertEquals(shortValue, bindVariables.get("v21")); + assertEquals(intValue, bindVariables.get("v22")); + assertEquals(longValue, bindVariables.get("v23")); + assertEquals(floatValue, bindVariables.get("v24")); + assertEquals(doubleValue, bindVariables.get("v25")); + assertEquals(bigDecimalValue, bindVariables.get("v26")); + assertEquals(bigIntegerValue, bindVariables.get("v27")); + assertEquals(stringValue, bindVariables.get("v28")); + assertEquals(dateValue.toString(), bindVariables.get("v29")); + assertEquals(timeValue.toString(), bindVariables.get("v30")); + assertEquals(timestampValue.toString(), bindVariables.get("v31")); + assertEquals("a", bindVariables.get("v32")); + assertEquals(null, bindVariables.get("v33")); + assertEquals(true, bindVariables.get("v34")); + assertEquals(shortValue.intValue(), bindVariables.get("v35")); + assertEquals(longValue, bindVariables.get("v36")); + assertEquals((double) floatValue, (double) bindVariables.get("v37"), 0.1); + assertEquals(doubleValue, (double) bindVariables.get("v38"), 0.1); + assertEquals(expectedDecimalValue, bindVariables.get("v39")); + assertEquals(stringValue, bindVariables.get("v40")); + assertEquals(dateValue.toString(), bindVariables.get("v41")); + assertEquals(timeValue.toString(), bindVariables.get("v42")); + assertEquals(timestampValue.toString(), bindVariables.get("v43")); + assertEquals("clob", bindVariables.get("v44")); Assert.assertArrayEquals(bytesValue, (byte[])bindVariables.get("v45")); preparedStatement.clearParameters(); } @Test public void testTreatUtilDateAsTimestamp() throws Exception { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + VitessConnection mockConn = mock(VitessConnection.class); VitessPreparedStatement preparedStatement = new VitessPreparedStatement(mockConn, sqlSelect); @@ -577,7 +584,7 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun Timestamp timestamp = new Timestamp(utilDateValue.getTime()); try { preparedStatement.setObject(1, utilDateValue); - Assert.fail("setObject on java.util.Date should have failed with SQLException"); + fail("setObject on java.util.Date should have failed with SQLException"); } catch (SQLException e) { Assert.assertTrue(e.getMessage().startsWith(Constants.SQLExceptionMessages.SQL_TYPE_INFER)); } @@ -593,57 +600,57 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun Map bindVariables = (Map) bindVariablesMap.get(preparedStatement); - Assert.assertEquals(DateTime.formatTimestamp(timestamp), bindVariables.get("v1")); + assertEquals(DateTime.formatTimestamp(timestamp), bindVariables.get("v1")); } @Test public void testAutoGeneratedKeys() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); try { long expectedFirstGeneratedId = 121; long[] expectedGeneratedIds = {121, 122}; int expectedAffectedRows = 2; - PowerMockito.when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); - PowerMockito.when(mockCursor.getRowsAffected()) + when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); + when(mockCursor.getRowsAffected()) .thenReturn(Long.valueOf(expectedAffectedRows)); //Executing Insert Statement VitessPreparedStatement preparedStatement = new VitessPreparedStatement(mockConn, sqlInsert, Statement.RETURN_GENERATED_KEYS); int updateCount = preparedStatement.executeUpdate(); - Assert.assertEquals(expectedAffectedRows, updateCount); + assertEquals(expectedAffectedRows, updateCount); ResultSet rs = preparedStatement.getGeneratedKeys(); int i = 0; while (rs.next()) { long generatedId = rs.getLong(1); - Assert.assertEquals(expectedGeneratedIds[i++], generatedId); + assertEquals(expectedGeneratedIds[i++], generatedId); } } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + fail("Test failed " + e.getMessage()); } } @Test public void testAddBatch() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + VitessConnection mockConn = mock(VitessConnection.class); VitessPreparedStatement statement = new VitessPreparedStatement(mockConn, sqlInsert); try { statement.addBatch(this.sqlInsert); - Assert.fail("Should have thrown Exception"); + fail("Should have thrown Exception"); } catch (SQLException ex) { - Assert.assertEquals(Constants.SQLExceptionMessages.METHOD_NOT_ALLOWED, ex.getMessage()); + assertEquals(Constants.SQLExceptionMessages.METHOD_NOT_ALLOWED, ex.getMessage()); } statement.setString(1, "string1"); statement.addBatch(); @@ -651,17 +658,17 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun Field privateStringField = VitessPreparedStatement.class.getDeclaredField("batchedArgs"); privateStringField.setAccessible(true); - Assert.assertEquals("string1", + assertEquals("string1", (((List>) privateStringField.get(statement)).get(0)).get("v1")); } catch (NoSuchFieldException e) { - Assert.fail("Private Field should exists: batchedArgs"); + fail("Private Field should exists: batchedArgs"); } catch (IllegalAccessException e) { - Assert.fail("Private Field should be accessible: batchedArgs"); + fail("Private Field should be accessible: batchedArgs"); } } @Test public void testClearBatch() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + VitessConnection mockConn = mock(VitessConnection.class); VitessPreparedStatement statement = new VitessPreparedStatement(mockConn, sqlInsert); statement.setString(1, "string1"); statement.addBatch(); @@ -673,44 +680,44 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun Assert.assertTrue( ((List>) privateStringField.get(statement)).isEmpty()); } catch (NoSuchFieldException e) { - Assert.fail("Private Field should exists: batchedArgs"); + fail("Private Field should exists: batchedArgs"); } catch (IllegalAccessException e) { - Assert.fail("Private Field should be accessible: batchedArgs"); + fail("Private Field should be accessible: batchedArgs"); } } @Test public void testExecuteBatch() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + VitessConnection mockConn = mock(VitessConnection.class); VitessPreparedStatement statement = new VitessPreparedStatement(mockConn, sqlInsert); int[] updateCounts = statement.executeBatch(); - Assert.assertEquals(0, updateCounts.length); + assertEquals(0, updateCounts.length); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockConn.getAutoCommit()).thenReturn(true); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - PowerMockito.when(mockVtGateConn - .executeBatch(Matchers.any(Context.class), Matchers.anyList(), Matchers.anyList(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + when(mockVtGateConn + .executeBatch(any(Context.class), Matchers.anyList(), Matchers.anyList(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); List mockCursorWithErrorList = new ArrayList<>(); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); - CursorWithError mockCursorWithError1 = PowerMockito.mock(CursorWithError.class); - PowerMockito.when(mockCursorWithError1.getError()).thenReturn(null); - PowerMockito.when(mockCursorWithError1.getCursor()) - .thenReturn(PowerMockito.mock(Cursor.class)); + CursorWithError mockCursorWithError1 = mock(CursorWithError.class); + when(mockCursorWithError1.getError()).thenReturn(null); + when(mockCursorWithError1.getCursor()) + .thenReturn(mock(Cursor.class)); mockCursorWithErrorList.add(mockCursorWithError1); statement.setString(1, "string1"); statement.addBatch(); updateCounts = statement.executeBatch(); - Assert.assertEquals(1, updateCounts.length); + assertEquals(1, updateCounts.length); - CursorWithError mockCursorWithError2 = PowerMockito.mock(CursorWithError.class); + CursorWithError mockCursorWithError2 = mock(CursorWithError.class); Vtrpc.RPCError rpcError = Vtrpc.RPCError.newBuilder().setMessage("preparedStatement execute batch error").build(); - PowerMockito.when(mockCursorWithError2.getError()) + when(mockCursorWithError2.getError()) .thenReturn(rpcError); mockCursorWithErrorList.add(mockCursorWithError2); statement.setString(1, "string1"); @@ -719,16 +726,16 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun statement.addBatch(); try { statement.executeBatch(); - Assert.fail("Should have thrown Exception"); + fail("Should have thrown Exception"); } catch (BatchUpdateException ex) { - Assert.assertEquals(rpcError.toString(), ex.getMessage()); - Assert.assertEquals(2, ex.getUpdateCounts().length); - Assert.assertEquals(Statement.EXECUTE_FAILED, ex.getUpdateCounts()[1]); + assertEquals(rpcError.toString(), ex.getMessage()); + assertEquals(2, ex.getUpdateCounts().length); + assertEquals(Statement.EXECUTE_FAILED, ex.getUpdateCounts()[1]); } } @Test public void testStatementCount() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + VitessConnection mockConn = mock(VitessConnection.class); Map testCases = ImmutableMap.builder() .put("select * from foo where a = ?", 1) .put("select * from foo where a = ? and b = ?", 2) @@ -750,7 +757,7 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun for (Map.Entry testCase : testCases.entrySet()) { VitessPreparedStatement statement = new VitessPreparedStatement(mockConn, testCase.getKey()); - Assert.assertEquals(testCase.getKey(), testCase.getValue().longValue(), statement.getParameterMetaData().getParameterCount()); + assertEquals(testCase.getKey(), testCase.getValue().longValue(), statement.getParameterMetaData().getParameterCount()); } } } diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java index 12502faa082..80edc9033b5 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java @@ -45,6 +45,8 @@ import io.vitess.util.StringUtils; import io.vitess.util.charset.CharsetMapping; +import static org.junit.Assert.assertEquals; + /** * Created by harshit.gangal on 19/01/16. */ @@ -85,34 +87,34 @@ public Cursor getCursorWithRows() { UNRECOGNIZED(-1, -1); */ return new SimpleCursor(Query.QueryResult.newBuilder() - .addFields(Query.Field.newBuilder().setName("col1").setType(Query.Type.INT8).build()) - .addFields(Query.Field.newBuilder().setName("col2").setType(Query.Type.UINT8).build()) - .addFields(Query.Field.newBuilder().setName("col3").setType(Query.Type.INT16).build()) - .addFields(Query.Field.newBuilder().setName("col4").setType(Query.Type.UINT16).build()) - .addFields(Query.Field.newBuilder().setName("col5").setType(Query.Type.INT24).build()) - .addFields(Query.Field.newBuilder().setName("col6").setType(Query.Type.UINT24).build()) - .addFields(Query.Field.newBuilder().setName("col7").setType(Query.Type.INT32).build()) - .addFields(Query.Field.newBuilder().setName("col8").setType(Query.Type.UINT32).build()) - .addFields(Query.Field.newBuilder().setName("col9").setType(Query.Type.INT64).build()) - .addFields(Query.Field.newBuilder().setName("col10").setType(Query.Type.UINT64).build()) - .addFields(Query.Field.newBuilder().setName("col11").setType(Query.Type.FLOAT32).build()) - .addFields(Query.Field.newBuilder().setName("col12").setType(Query.Type.FLOAT64).build()) - .addFields(Query.Field.newBuilder().setName("col13").setType(Query.Type.TIMESTAMP).build()) - .addFields(Query.Field.newBuilder().setName("col14").setType(Query.Type.DATE).build()) - .addFields(Query.Field.newBuilder().setName("col15").setType(Query.Type.TIME).build()) - .addFields(Query.Field.newBuilder().setName("col16").setType(Query.Type.DATETIME).build()) - .addFields(Query.Field.newBuilder().setName("col17").setType(Query.Type.YEAR).build()) - .addFields(Query.Field.newBuilder().setName("col18").setType(Query.Type.DECIMAL).build()) - .addFields(Query.Field.newBuilder().setName("col19").setType(Query.Type.TEXT).build()) - .addFields(Query.Field.newBuilder().setName("col20").setType(Query.Type.BLOB).build()) - .addFields(Query.Field.newBuilder().setName("col21").setType(Query.Type.VARCHAR).build()) - .addFields(Query.Field.newBuilder().setName("col22").setType(Query.Type.VARBINARY).build()) - .addFields(Query.Field.newBuilder().setName("col23").setType(Query.Type.CHAR).build()) - .addFields(Query.Field.newBuilder().setName("col24").setType(Query.Type.BINARY).build()) - .addFields(Query.Field.newBuilder().setName("col25").setType(Query.Type.BIT).build()) - .addFields(Query.Field.newBuilder().setName("col26").setType(Query.Type.ENUM).build()) - .addFields(Query.Field.newBuilder().setName("col27").setType(Query.Type.SET).build()) - .addFields(Query.Field.newBuilder().setName("col28").setType(Query.Type.TIMESTAMP).build()) + .addFields(getField("col1", Query.Type.INT8)) + .addFields(getField("col2", Query.Type.UINT8)) + .addFields(getField("col3", Query.Type.INT16)) + .addFields(getField("col4", Query.Type.UINT16)) + .addFields(getField("col5", Query.Type.INT24)) + .addFields(getField("col6", Query.Type.UINT24)) + .addFields(getField("col7", Query.Type.INT32)) + .addFields(getField("col8", Query.Type.UINT32)) + .addFields(getField("col9", Query.Type.INT64)) + .addFields(getField("col10", Query.Type.UINT64)) + .addFields(getField("col11", Query.Type.FLOAT32)) + .addFields(getField("col12", Query.Type.FLOAT64)) + .addFields(getField("col13", Query.Type.TIMESTAMP)) + .addFields(getField("col14", Query.Type.DATE)) + .addFields(getField("col15", Query.Type.TIME)) + .addFields(getField("col16", Query.Type.DATETIME)) + .addFields(getField("col17", Query.Type.YEAR)) + .addFields(getField("col18", Query.Type.DECIMAL)) + .addFields(getField("col19", Query.Type.TEXT)) + .addFields(getField("col20", Query.Type.BLOB)) + .addFields(getField("col21", Query.Type.VARCHAR)) + .addFields(getField("col22", Query.Type.VARBINARY)) + .addFields(getField("col23", Query.Type.CHAR)) + .addFields(getField("col24", Query.Type.BINARY)) + .addFields(getField("col25", Query.Type.BIT)) + .addFields(getField("col26", Query.Type.ENUM)) + .addFields(getField("col27", Query.Type.SET)) + .addFields(getField("col28", Query.Type.TIMESTAMP)) .addRows(Query.Row.newBuilder().addLengths("-50".length()).addLengths("50".length()) .addLengths("-23000".length()).addLengths("23000".length()) .addLengths("-100".length()).addLengths("100".length()).addLengths("-100".length()) @@ -133,6 +135,14 @@ public Cursor getCursorWithRows() { " TDS TEAMHELLO TDS TEAMNHELLO TDS TEAM1val123val1230000-00-00 00:00:00"))).build()); } + private Query.Field getField(String fieldName, Query.Type typ) { + return Query.Field.newBuilder().setName(fieldName).setType(typ).build(); + } + + private Query.Field getField(String fieldName) { + return Query.Field.newBuilder().setName(fieldName).build(); + } + public Cursor getCursorWithRowsAsNull() { /* INT8(1, 257), -50 @@ -166,33 +176,33 @@ public Cursor getCursorWithRowsAsNull() { UNRECOGNIZED(-1, -1); */ return new SimpleCursor(Query.QueryResult.newBuilder() - .addFields(Query.Field.newBuilder().setName("col1").setType(Query.Type.INT8).build()) - .addFields(Query.Field.newBuilder().setName("col2").setType(Query.Type.UINT8).build()) - .addFields(Query.Field.newBuilder().setName("col3").setType(Query.Type.INT16).build()) - .addFields(Query.Field.newBuilder().setName("col4").setType(Query.Type.UINT16).build()) - .addFields(Query.Field.newBuilder().setName("col5").setType(Query.Type.INT24).build()) - .addFields(Query.Field.newBuilder().setName("col6").setType(Query.Type.UINT24).build()) - .addFields(Query.Field.newBuilder().setName("col7").setType(Query.Type.INT32).build()) - .addFields(Query.Field.newBuilder().setName("col8").setType(Query.Type.UINT32).build()) - .addFields(Query.Field.newBuilder().setName("col9").setType(Query.Type.INT64).build()) - .addFields(Query.Field.newBuilder().setName("col10").setType(Query.Type.UINT64).build()) - .addFields(Query.Field.newBuilder().setName("col11").setType(Query.Type.FLOAT32).build()) - .addFields(Query.Field.newBuilder().setName("col12").setType(Query.Type.FLOAT64).build()) - .addFields(Query.Field.newBuilder().setName("col13").setType(Query.Type.TIMESTAMP).build()) - .addFields(Query.Field.newBuilder().setName("col14").setType(Query.Type.DATE).build()) - .addFields(Query.Field.newBuilder().setName("col15").setType(Query.Type.TIME).build()) - .addFields(Query.Field.newBuilder().setName("col16").setType(Query.Type.DATETIME).build()) - .addFields(Query.Field.newBuilder().setName("col17").setType(Query.Type.YEAR).build()) - .addFields(Query.Field.newBuilder().setName("col18").setType(Query.Type.DECIMAL).build()) - .addFields(Query.Field.newBuilder().setName("col19").setType(Query.Type.TEXT).build()) - .addFields(Query.Field.newBuilder().setName("col20").setType(Query.Type.BLOB).build()) - .addFields(Query.Field.newBuilder().setName("col21").setType(Query.Type.VARCHAR).build()) - .addFields(Query.Field.newBuilder().setName("col22").setType(Query.Type.VARBINARY).build()) - .addFields(Query.Field.newBuilder().setName("col23").setType(Query.Type.CHAR).build()) - .addFields(Query.Field.newBuilder().setName("col24").setType(Query.Type.BINARY).build()) - .addFields(Query.Field.newBuilder().setName("col25").setType(Query.Type.BIT).build()) - .addFields(Query.Field.newBuilder().setName("col26").setType(Query.Type.ENUM).build()) - .addFields(Query.Field.newBuilder().setName("col27").setType(Query.Type.SET).build()) + .addFields(getField("col1", Query.Type.INT8)) + .addFields(getField("col2", Query.Type.UINT8)) + .addFields(getField("col3", Query.Type.INT16)) + .addFields(getField("col4", Query.Type.UINT16)) + .addFields(getField("col5", Query.Type.INT24)) + .addFields(getField("col6", Query.Type.UINT24)) + .addFields(getField("col7", Query.Type.INT32)) + .addFields(getField("col8", Query.Type.UINT32)) + .addFields(getField("col9", Query.Type.INT64)) + .addFields(getField("col10", Query.Type.UINT64)) + .addFields(getField("col11", Query.Type.FLOAT32)) + .addFields(getField("col12", Query.Type.FLOAT64)) + .addFields(getField("col13", Query.Type.TIMESTAMP)) + .addFields(getField("col14", Query.Type.DATE)) + .addFields(getField("col15", Query.Type.TIME)) + .addFields(getField("col16", Query.Type.DATETIME)) + .addFields(getField("col17", Query.Type.YEAR)) + .addFields(getField("col18", Query.Type.DECIMAL)) + .addFields(getField("col19", Query.Type.TEXT)) + .addFields(getField("col20", Query.Type.BLOB)) + .addFields(getField("col21", Query.Type.VARCHAR)) + .addFields(getField("col22", Query.Type.VARBINARY)) + .addFields(getField("col23", Query.Type.CHAR)) + .addFields(getField("col24", Query.Type.BINARY)) + .addFields(getField("col25", Query.Type.BIT)) + .addFields(getField("col26", Query.Type.ENUM)) + .addFields(getField("col27", Query.Type.SET)) .addRows(Query.Row.newBuilder().addLengths("-50".length()).addLengths("50".length()) .addLengths("-23000".length()).addLengths("23000".length()) .addLengths("-100".length()).addLengths("100".length()).addLengths("-100".length()) @@ -212,52 +222,52 @@ public Cursor getCursorWithRowsAsNull() { @Test public void testNextWithZeroRows() throws Exception { Cursor cursor = new SimpleCursor(Query.QueryResult.newBuilder() - .addFields(Query.Field.newBuilder().setName("col0").build()) - .addFields(Query.Field.newBuilder().setName("col1").build()) - .addFields(Query.Field.newBuilder().setName("col2").build()).build()); + .addFields(getField("col0")) + .addFields(getField("col1")) + .addFields(getField("col2")).build()); VitessResultSet vitessResultSet = new VitessResultSet(cursor); - Assert.assertEquals(false, vitessResultSet.next()); + assertEquals(false, vitessResultSet.next()); } @Test public void testNextWithNonZeroRows() throws Exception { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor); - Assert.assertEquals(true, vitessResultSet.next()); - Assert.assertEquals(false, vitessResultSet.next()); + assertEquals(true, vitessResultSet.next()); + assertEquals(false, vitessResultSet.next()); } @Test public void testgetString() throws SQLException { Cursor cursor = getCursorWithRowsAsNull(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals("-50", vitessResultSet.getString(1)); - Assert.assertEquals("50", vitessResultSet.getString(2)); - Assert.assertEquals("-23000", vitessResultSet.getString(3)); - Assert.assertEquals("23000", vitessResultSet.getString(4)); - Assert.assertEquals("-100", vitessResultSet.getString(5)); - Assert.assertEquals("100", vitessResultSet.getString(6)); - Assert.assertEquals("-100", vitessResultSet.getString(7)); - Assert.assertEquals("100", vitessResultSet.getString(8)); - Assert.assertEquals("-1000", vitessResultSet.getString(9)); - Assert.assertEquals("1000", vitessResultSet.getString(10)); - Assert.assertEquals("24.52", vitessResultSet.getString(11)); - Assert.assertEquals("100.43", vitessResultSet.getString(12)); - Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(13)); - Assert.assertEquals("2016-02-06", vitessResultSet.getString(14)); - Assert.assertEquals("12:34:56", vitessResultSet.getString(15)); - Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(16)); - Assert.assertEquals("2016", vitessResultSet.getString(17)); - Assert.assertEquals("1234.56789", vitessResultSet.getString(18)); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(19)); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(20)); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(21)); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(22)); - Assert.assertEquals("N", vitessResultSet.getString(23)); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString(24)); - Assert.assertEquals("0", vitessResultSet.getString(25)); - Assert.assertEquals("val123", vitessResultSet.getString(26)); - Assert.assertEquals(null, vitessResultSet.getString(27)); + assertEquals("-50", vitessResultSet.getString(1)); + assertEquals("50", vitessResultSet.getString(2)); + assertEquals("-23000", vitessResultSet.getString(3)); + assertEquals("23000", vitessResultSet.getString(4)); + assertEquals("-100", vitessResultSet.getString(5)); + assertEquals("100", vitessResultSet.getString(6)); + assertEquals("-100", vitessResultSet.getString(7)); + assertEquals("100", vitessResultSet.getString(8)); + assertEquals("-1000", vitessResultSet.getString(9)); + assertEquals("1000", vitessResultSet.getString(10)); + assertEquals("24.52", vitessResultSet.getString(11)); + assertEquals("100.43", vitessResultSet.getString(12)); + assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(13)); + assertEquals("2016-02-06", vitessResultSet.getString(14)); + assertEquals("12:34:56", vitessResultSet.getString(15)); + assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString(16)); + assertEquals("2016", vitessResultSet.getString(17)); + assertEquals("1234.56789", vitessResultSet.getString(18)); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString(19)); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString(20)); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString(21)); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString(22)); + assertEquals("N", vitessResultSet.getString(23)); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString(24)); + assertEquals("0", vitessResultSet.getString(25)); + assertEquals("val123", vitessResultSet.getString(26)); + assertEquals(null, vitessResultSet.getString(27)); } @Test public void getObjectUint64AsBigInteger() throws SQLException { @@ -265,7 +275,7 @@ public Cursor getCursorWithRowsAsNull() { VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new BigInteger("1000"), vitessResultSet.getObject(10)); + assertEquals(new BigInteger("1000"), vitessResultSet.getObject(10)); } @Test public void getBigInteger() throws SQLException { @@ -273,7 +283,7 @@ public Cursor getCursorWithRowsAsNull() { VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new BigInteger("1000"), vitessResultSet.getBigInteger(10)); + assertEquals(new BigInteger("1000"), vitessResultSet.getBigInteger(10)); } @Test public void testgetBoolean() throws SQLException { @@ -281,62 +291,62 @@ public Cursor getCursorWithRowsAsNull() { Cursor cursorWithRowsAsNull = getCursorWithRowsAsNull(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(true, vitessResultSet.getBoolean(25)); - Assert.assertEquals(false, vitessResultSet.getBoolean(1)); + assertEquals(true, vitessResultSet.getBoolean(25)); + assertEquals(false, vitessResultSet.getBoolean(1)); vitessResultSet = new VitessResultSet(cursorWithRowsAsNull, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(false, vitessResultSet.getBoolean(25)); - Assert.assertEquals(false, vitessResultSet.getBoolean(1)); + assertEquals(false, vitessResultSet.getBoolean(25)); + assertEquals(false, vitessResultSet.getBoolean(1)); } @Test public void testgetByte() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-50, vitessResultSet.getByte(1)); - Assert.assertEquals(1, vitessResultSet.getByte(25)); + assertEquals(-50, vitessResultSet.getByte(1)); + assertEquals(1, vitessResultSet.getByte(25)); } @Test public void testgetShort() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-23000, vitessResultSet.getShort(3)); + assertEquals(-23000, vitessResultSet.getShort(3)); } @Test public void testgetInt() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-100, vitessResultSet.getInt(7)); + assertEquals(-100, vitessResultSet.getInt(7)); } @Test public void testgetLong() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-1000, vitessResultSet.getInt(9)); + assertEquals(-1000, vitessResultSet.getInt(9)); } @Test public void testgetFloat() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(24.52f, vitessResultSet.getFloat(11), 0.001); + assertEquals(24.52f, vitessResultSet.getFloat(11), 0.001); } @Test public void testgetDouble() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(100.43, vitessResultSet.getFloat(12), 0.001); + assertEquals(100.43, vitessResultSet.getFloat(12), 0.001); } @Test public void testBigDecimal() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5), + assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5), vitessResultSet.getBigDecimal(18)); } @@ -351,21 +361,21 @@ public Cursor getCursorWithRowsAsNull() { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate(14)); + assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate(14)); } @Test public void testgetTime() throws SQLException, UnsupportedEncodingException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new Time(12, 34, 56), vitessResultSet.getTime(15)); + assertEquals(new Time(12, 34, 56), vitessResultSet.getTime(15)); } @Test public void testgetTimestamp() throws SQLException, UnsupportedEncodingException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0), + assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0), vitessResultSet.getTimestamp(13)); } @@ -375,7 +385,7 @@ public Cursor getCursorWithRowsAsNull() { new VitessStatement(new VitessConnection( "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?zeroDateTimeBehavior=garble", new Properties()))); vitessResultSet.next(); - Assert.assertEquals("0002-11-30 00:00:00.0", + assertEquals("0002-11-30 00:00:00.0", vitessResultSet.getTimestamp(28).toString()); } @@ -406,7 +416,7 @@ public Cursor getCursorWithRowsAsNull() { new VitessStatement(new VitessConnection( "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?zeroDateTimeBehavior=round", new Properties()))); vitessResultSet.next(); - Assert.assertEquals("0001-01-01 00:00:00.0", vitessResultSet.getTimestamp(28).toString()); + assertEquals("0001-01-01 00:00:00.0", vitessResultSet.getTimestamp(28).toString()); } @Test public void testgetZeroDateRound() throws SQLException, UnsupportedEncodingException { @@ -415,84 +425,84 @@ public Cursor getCursorWithRowsAsNull() { new VitessStatement(new VitessConnection( "jdbc:vitess://locahost:9000/vt_keyspace/keyspace?zeroDateTimeBehavior=round", new Properties()))); vitessResultSet.next(); - Assert.assertEquals("0001-01-01", vitessResultSet.getDate(28).toString()); + assertEquals("0001-01-01", vitessResultSet.getDate(28).toString()); } @Test public void testgetStringbyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals("-50", vitessResultSet.getString("col1")); - Assert.assertEquals("50", vitessResultSet.getString("col2")); - Assert.assertEquals("-23000", vitessResultSet.getString("col3")); - Assert.assertEquals("23000", vitessResultSet.getString("col4")); - Assert.assertEquals("-100", vitessResultSet.getString("col5")); - Assert.assertEquals("100", vitessResultSet.getString("col6")); - Assert.assertEquals("-100", vitessResultSet.getString("col7")); - Assert.assertEquals("100", vitessResultSet.getString("col8")); - Assert.assertEquals("-1000", vitessResultSet.getString("col9")); - Assert.assertEquals("1000", vitessResultSet.getString("col10")); - Assert.assertEquals("24.52", vitessResultSet.getString("col11")); - Assert.assertEquals("100.43", vitessResultSet.getString("col12")); - Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col13")); - Assert.assertEquals("2016-02-06", vitessResultSet.getString("col14")); - Assert.assertEquals("12:34:56", vitessResultSet.getString("col15")); - Assert.assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col16")); - Assert.assertEquals("2016", vitessResultSet.getString("col17")); - Assert.assertEquals("1234.56789", vitessResultSet.getString("col18")); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col19")); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col20")); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col21")); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col22")); - Assert.assertEquals("N", vitessResultSet.getString("col23")); - Assert.assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col24")); - Assert.assertEquals("1", vitessResultSet.getString("col25")); - Assert.assertEquals("val123", vitessResultSet.getString("col26")); - Assert.assertEquals("val123", vitessResultSet.getString("col27")); + assertEquals("-50", vitessResultSet.getString("col1")); + assertEquals("50", vitessResultSet.getString("col2")); + assertEquals("-23000", vitessResultSet.getString("col3")); + assertEquals("23000", vitessResultSet.getString("col4")); + assertEquals("-100", vitessResultSet.getString("col5")); + assertEquals("100", vitessResultSet.getString("col6")); + assertEquals("-100", vitessResultSet.getString("col7")); + assertEquals("100", vitessResultSet.getString("col8")); + assertEquals("-1000", vitessResultSet.getString("col9")); + assertEquals("1000", vitessResultSet.getString("col10")); + assertEquals("24.52", vitessResultSet.getString("col11")); + assertEquals("100.43", vitessResultSet.getString("col12")); + assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col13")); + assertEquals("2016-02-06", vitessResultSet.getString("col14")); + assertEquals("12:34:56", vitessResultSet.getString("col15")); + assertEquals("2016-02-06 14:15:16.0", vitessResultSet.getString("col16")); + assertEquals("2016", vitessResultSet.getString("col17")); + assertEquals("1234.56789", vitessResultSet.getString("col18")); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col19")); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col20")); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col21")); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col22")); + assertEquals("N", vitessResultSet.getString("col23")); + assertEquals("HELLO TDS TEAM", vitessResultSet.getString("col24")); + assertEquals("1", vitessResultSet.getString("col25")); + assertEquals("val123", vitessResultSet.getString("col26")); + assertEquals("val123", vitessResultSet.getString("col27")); } @Test public void testgetBooleanbyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(true, vitessResultSet.getBoolean("col25")); - Assert.assertEquals(false, vitessResultSet.getBoolean("col1")); + assertEquals(true, vitessResultSet.getBoolean("col25")); + assertEquals(false, vitessResultSet.getBoolean("col1")); } @Test public void testgetBytebyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-50, vitessResultSet.getByte("col1")); - Assert.assertEquals(1, vitessResultSet.getByte("col25")); + assertEquals(-50, vitessResultSet.getByte("col1")); + assertEquals(1, vitessResultSet.getByte("col25")); } @Test public void testgetShortbyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-23000, vitessResultSet.getShort("col3")); + assertEquals(-23000, vitessResultSet.getShort("col3")); } @Test public void testgetIntbyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-100, vitessResultSet.getInt("col7")); + assertEquals(-100, vitessResultSet.getInt("col7")); } @Test public void testgetLongbyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(-1000, vitessResultSet.getInt("col9")); + assertEquals(-1000, vitessResultSet.getInt("col9")); } @Test public void testBigIntegerbyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new BigInteger("1000"), + assertEquals(new BigInteger("1000"), vitessResultSet.getBigInteger("col10")); } @@ -500,21 +510,21 @@ public Cursor getCursorWithRowsAsNull() { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(24.52f, vitessResultSet.getFloat("col11"), 0.001); + assertEquals(24.52f, vitessResultSet.getFloat("col11"), 0.001); } @Test public void testgetDoublebyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(100.43, vitessResultSet.getFloat("col12"), 0.001); + assertEquals(100.43, vitessResultSet.getFloat("col12"), 0.001); } @Test public void testBigDecimalbyColumnLabel() throws SQLException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5), + assertEquals(new BigDecimal(BigInteger.valueOf(123456789), 5), vitessResultSet.getBigDecimal("col18")); } @@ -531,14 +541,14 @@ public Cursor getCursorWithRowsAsNull() { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate("col14")); + assertEquals(new java.sql.Date(116, 1, 6), vitessResultSet.getDate("col14")); } @Test public void testgetTimebyColumnLabel() throws SQLException, UnsupportedEncodingException { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new Time(12, 34, 56), vitessResultSet.getTime("col15")); + assertEquals(new Time(12, 34, 56), vitessResultSet.getTime("col15")); } @Test public void testgetTimestampbyColumnLabel() @@ -546,7 +556,7 @@ public Cursor getCursorWithRowsAsNull() { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); vitessResultSet.next(); - Assert.assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0), + assertEquals(new Timestamp(116, 1, 6, 14, 15, 16, 0), vitessResultSet.getTimestamp("col13")); } @@ -573,13 +583,13 @@ public Cursor getCursorWithRowsAsNull() { vitessResultSet.getBinaryStream(22).read(ba3, 0, 128); Assert.assertArrayEquals(ba1, ba3); - Assert.assertEquals(null, vitessResultSet.getBinaryStream(27)); + assertEquals(null, vitessResultSet.getBinaryStream(27)); } @Test public void testEnhancedFieldsFromCursor() throws Exception { Cursor cursor = getCursorWithRows(); VitessResultSet vitessResultSet = new VitessResultSet(cursor, getVitessStatement()); - Assert.assertEquals(cursor.getFields().size(), vitessResultSet.getFields().size()); + assertEquals(cursor.getFields().size(), vitessResultSet.getFields().size()); } @Test public void testGetStringUsesEncoding() throws Exception { @@ -626,8 +636,8 @@ public Cursor getCursorWithRowsAsNull() { VitessResultSet vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn))); vitessResultSet.next(); - Assert.assertEquals(true, vitessResultSet.getObject(1)); - Assert.assertEquals(false, vitessResultSet.getObject(2)); + assertEquals(true, vitessResultSet.getObject(1)); + assertEquals(false, vitessResultSet.getObject(2)); Assert.assertArrayEquals(new byte[] {1,2,3,4}, (byte[]) vitessResultSet.getObject(3)); PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(3)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class)); @@ -785,12 +795,12 @@ public Cursor getCursorWithRowsAsNull() { VitessResultSet vitessResultSet = PowerMockito.spy(new VitessResultSet(new SimpleCursor(result), new VitessStatement(conn))); vitessResultSet.next(); - Assert.assertEquals(trimmedCharStr, vitessResultSet.getObject(1)); - Assert.assertEquals(varcharStr, vitessResultSet.getObject(2)); + assertEquals(trimmedCharStr, vitessResultSet.getObject(1)); + assertEquals(varcharStr, vitessResultSet.getObject(2)); Assert.assertArrayEquals(opaqueBinary, (byte[]) vitessResultSet.getObject(3)); - Assert.assertEquals(masqueradingBlobStr, vitessResultSet.getObject(4)); - Assert.assertEquals(textStr, vitessResultSet.getObject(5)); - Assert.assertEquals(jsonStr, vitessResultSet.getObject(6)); + assertEquals(masqueradingBlobStr, vitessResultSet.getObject(4)); + assertEquals(textStr, vitessResultSet.getObject(5)); + assertEquals(jsonStr, vitessResultSet.getObject(6)); PowerMockito.verifyPrivate(vitessResultSet, VerificationModeFactory.times(6)).invoke("convertBytesIfPossible", Matchers.any(byte[].class), Matchers.any(FieldWithMetadata.class)); @@ -816,9 +826,9 @@ public Cursor getCursorWithRowsAsNull() { Assert.assertTrue(vitessResultSet.next()); Clob clob = vitessResultSet.getClob(1); - Assert.assertEquals("clobValue", clob.getSubString(1, (int) clob.length())); + assertEquals("clobValue", clob.getSubString(1, (int) clob.length())); clob = vitessResultSet.getClob("clob"); - Assert.assertEquals("clobValue", clob.getSubString(1, (int) clob.length())); + assertEquals("clobValue", clob.getSubString(1, (int) clob.length())); } } diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java index 39482e9f14c..febb968e5fa 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java @@ -1,12 +1,12 @@ /* * Copyright 2017 Google Inc. - * + * * Licensed 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. @@ -23,6 +23,7 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; + import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -42,12 +43,21 @@ import io.vitess.proto.Vtrpc; import io.vitess.util.Constants; +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.when; + /** * Created by harshit.gangal on 19/01/16. */ -@RunWith(PowerMockRunner.class) @PrepareForTest({VTGateConnection.class, - Vtrpc.RPCError.class}) public class VitessStatementTest { +@RunWith(PowerMockRunner.class) +@PrepareForTest({VTGateConnection.class, + Vtrpc.RPCError.class}) +public class VitessStatementTest { private String sqlSelect = "select 1 from test_table"; private String sqlShow = "show tables"; @@ -56,132 +66,117 @@ private String sqlUpsert = "insert into test_table(msg) values ('abc') on duplicate key update msg = 'def'"; - @Test public void testGetConnection() { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetConnection() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - try { - Assert.assertEquals(mockConn, statement.getConnection()); - } catch (SQLException e) { - Assert.fail("Connection Object is different than expect"); - } + assertEquals(mockConn, statement.getConnection()); } - @Test public void testGetResultSet() { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetResultSet() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - try { - Assert.assertEquals(null, statement.getResultSet()); - } catch (SQLException e) { - Assert.fail("ResultSet Object is different than expect"); - } + assertEquals(null, statement.getResultSet()); } - @Test public void testExecuteQuery() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), Matchers.any( - VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(true); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + @Test + public void testExecuteQuery() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), any( + VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockConn.isSimpleExecute()).thenReturn(true); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); VitessStatement statement = new VitessStatement(mockConn); + //Empty Sql Statement try { + statement.executeQuery(""); + fail("Should have thrown exception for empty sql"); + } catch (SQLException ex) { + assertEquals("SQL statement is not valid", ex.getMessage()); + } - //Empty Sql Statement - try { - statement.executeQuery(""); - Assert.fail("Should have thrown exception for empty sql"); - } catch (SQLException ex) { - Assert.assertEquals("SQL statement is not valid", ex.getMessage()); - } - - ResultSet rs = statement.executeQuery(sqlSelect); - Assert.assertEquals(-1, statement.getUpdateCount()); - - //autocommit is false and not in transaction - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(false); - PowerMockito.when(mockConn.isInTransaction()).thenReturn(false); - rs = statement.executeQuery(sqlSelect); - Assert.assertEquals(-1, statement.getUpdateCount()); - - //when returned cursor is null - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(null); - try { - statement.executeQuery(sqlSelect); - Assert.fail("Should have thrown exception for cursor null"); - } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); - } - - } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + ResultSet rs = statement.executeQuery(sqlSelect); + assertEquals(-1, statement.getUpdateCount()); + + //autocommit is false and not in transaction + when(mockConn.getAutoCommit()).thenReturn(false); + when(mockConn.isInTransaction()).thenReturn(false); + rs = statement.executeQuery(sqlSelect); + assertEquals(-1, statement.getUpdateCount()); + + //when returned cursor is null + when(mockSqlFutureCursor.checkedGet()).thenReturn(null); + try { + statement.executeQuery(sqlSelect); + fail("Should have thrown exception for cursor null"); + } catch (SQLException ex) { + assertEquals("Failed to execute this method", ex.getMessage()); } } - @Test public void testExecuteQueryWithStreamExecuteType() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockCursor); - PowerMockito.when(mockConn.getExecuteType()) - .thenReturn(Constants.QueryExecuteType.STREAM); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + @Test + public void testExecuteQueryWithStreamExecuteType() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockCursor); + when(mockConn.getExecuteType()) + .thenReturn(Constants.QueryExecuteType.STREAM); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); VitessStatement statement = new VitessStatement(mockConn); + //Empty Sql Statement try { + statement.executeQuery(""); + fail("Should have thrown exception for empty sql"); + } catch (SQLException ex) { + assertEquals("SQL statement is not valid", ex.getMessage()); + } + + //select on replica + ResultSet rs = statement.executeQuery(sqlSelect); + assertEquals(-1, statement.getUpdateCount()); + + //show query + rs = statement.executeQuery(sqlShow); + assertEquals(-1, statement.getUpdateCount()); - //Empty Sql Statement - try { - statement.executeQuery(""); - Assert.fail("Should have thrown exception for empty sql"); - } catch (SQLException ex) { - Assert.assertEquals("SQL statement is not valid", ex.getMessage()); - } - - //select on replica - ResultSet rs = statement.executeQuery(sqlSelect); - Assert.assertEquals(-1, statement.getUpdateCount()); - - //show query - rs = statement.executeQuery(sqlShow); - Assert.assertEquals(-1, statement.getUpdateCount()); - - //select on master when tx is null and autocommit is false - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(false); - PowerMockito.when(mockConn.isInTransaction()).thenReturn(false); - rs = statement.executeQuery(sqlSelect); - Assert.assertEquals(-1, statement.getUpdateCount()); - - //when returned cursor is null - PowerMockito.when(mockVtGateConn - .streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(null); - try { - statement.executeQuery(sqlSelect); - Assert.fail("Should have thrown exception for cursor null"); - } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); - } - - } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + //select on master when tx is null and autocommit is false + when(mockConn.getAutoCommit()).thenReturn(false); + when(mockConn.isInTransaction()).thenReturn(false); + rs = statement.executeQuery(sqlSelect); + assertEquals(-1, statement.getUpdateCount()); + + //when returned cursor is null + when(mockVtGateConn + .streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(null); + try { + statement.executeQuery(sqlSelect); + fail("Should have thrown exception for cursor null"); + } catch (SQLException ex) { + assertEquals("Failed to execute this method", ex.getMessage()); } } - @Test public void testExecuteFetchSizeAsStreaming() throws SQLException { + @Test + public void testExecuteFetchSizeAsStreaming() throws SQLException { testExecute(5, true, false, true); testExecute(5, false, false, true); testExecute(0, true, true, false); @@ -189,504 +184,483 @@ } private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRunExecute, boolean shouldRunStreamExecute) throws SQLException { - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(simpleExecute); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockVtGateConn - .streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockCursor); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + + VitessConnection mockConn = mock(VitessConnection.class); + when(mockConn.isSimpleExecute()).thenReturn(simpleExecute); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockVtGateConn + .streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockCursor); VitessStatement statement = new VitessStatement(mockConn); statement.setFetchSize(fetchSize); statement.executeQuery(sqlSelect); if (shouldRunExecute) { - Mockito.verify(mockVtGateConn, Mockito.times(2)).execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class)); + verify(mockVtGateConn, Mockito.times(2)).execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class)); } if (shouldRunStreamExecute) { - Mockito.verify(mockVtGateConn).streamExecute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class)); + verify(mockVtGateConn).streamExecute(any(Context.class), anyString(), anyMap(), + any(VTSession.class)); } } - @Test public void testExecuteUpdate() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - List fieldList = PowerMockito.mock(ArrayList.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + @Test + public void testExecuteUpdate() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + List fieldList = mock(ArrayList.class); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); VitessStatement statement = new VitessStatement(mockConn); + //executing dml on master + int updateCount = statement.executeUpdate(sqlUpdate); + assertEquals(0, updateCount); + + //tx is null & autoCommit is true + when(mockConn.getAutoCommit()).thenReturn(true); + updateCount = statement.executeUpdate(sqlUpdate); + assertEquals(0, updateCount); + + //cursor fields is not null + when(mockCursor.getFields()).thenReturn(fieldList); + when(fieldList.isEmpty()).thenReturn(false); try { - - //executing dml on master - int updateCount = statement.executeUpdate(sqlUpdate); - Assert.assertEquals(0, updateCount); - - //tx is null & autoCommit is true - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); - updateCount = statement.executeUpdate(sqlUpdate); - Assert.assertEquals(0, updateCount); - - //cursor fields is not null - PowerMockito.when(mockCursor.getFields()).thenReturn(fieldList); - PowerMockito.when(fieldList.isEmpty()).thenReturn(false); - try { - statement.executeUpdate(sqlSelect); - Assert.fail("Should have thrown exception for field not null"); - } catch (SQLException ex) { - Assert.assertEquals("ResultSet generation is not allowed through this method", + statement.executeUpdate(sqlSelect); + fail("Should have thrown exception for field not null"); + } catch (SQLException ex) { + assertEquals("ResultSet generation is not allowed through this method", ex.getMessage()); - } - - //cursor is null - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(null); - try { - statement.executeUpdate(sqlUpdate); - Assert.fail("Should have thrown exception for cursor null"); - } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); - } - - //read only - PowerMockito.when(mockConn.isReadOnly()).thenReturn(true); - try { - statement.execute("UPDATE SET foo = 1 ON mytable WHERE id = 1"); - Assert.fail("Should have thrown exception for read only"); - } catch (SQLException ex) { - Assert.assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); - } - - //read only - PowerMockito.when(mockConn.isReadOnly()).thenReturn(true); - try { - statement.executeBatch(); - Assert.fail("Should have thrown exception for read only"); - } catch (SQLException ex) { - Assert.assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); - } - - } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); } - } - @Test public void testExecute() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - List mockFieldList = PowerMockito.spy(new ArrayList()); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); - PowerMockito.when(mockConn.getExecuteType()) - .thenReturn(Constants.QueryExecuteType.SIMPLE); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(true); - - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(mockFieldList); + //cursor is null + when(mockSqlFutureCursor.checkedGet()).thenReturn(null); + try { + statement.executeUpdate(sqlUpdate); + fail("Should have thrown exception for cursor null"); + } catch (SQLException ex) { + assertEquals("Failed to execute this method", ex.getMessage()); + } - VitessStatement statement = new VitessStatement(mockConn); + //read only + when(mockConn.isReadOnly()).thenReturn(true); try { + statement.execute("UPDATE SET foo = 1 ON mytable WHERE id = 1"); + fail("Should have thrown exception for read only"); + } catch (SQLException ex) { + assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); + } - int fieldSize = 5; - PowerMockito.when(mockCursor.getFields()).thenReturn(mockFieldList); - PowerMockito.doReturn(fieldSize).when(mockFieldList).size(); - PowerMockito.doReturn(false).when(mockFieldList).isEmpty(); - - boolean hasResultSet = statement.execute(sqlSelect); - Assert.assertTrue(hasResultSet); - Assert.assertNotNull(statement.getResultSet()); - - hasResultSet = statement.execute(sqlShow); - Assert.assertTrue(hasResultSet); - Assert.assertNotNull(statement.getResultSet()); - - int mockUpdateCount = 10; - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); - PowerMockito.when(mockCursor.getRowsAffected()).thenReturn((long) mockUpdateCount); - hasResultSet = statement.execute(sqlUpdate); - Assert.assertFalse(hasResultSet); - Assert.assertNull(statement.getResultSet()); - Assert.assertEquals(mockUpdateCount, statement.getUpdateCount()); - - //cursor is null - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(null); - try { - statement.execute(sqlUpdate); - Assert.fail("Should have thrown exception for cursor null"); - } catch (SQLException ex) { - Assert.assertEquals("Failed to execute this method", ex.getMessage()); - } - - } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + //read only + when(mockConn.isReadOnly()).thenReturn(true); + try { + statement.executeBatch(); + fail("Should have thrown exception for read only"); + } catch (SQLException ex) { + assertEquals(Constants.SQLExceptionMessages.READ_ONLY, ex.getMessage()); } } - @Test public void testGetUpdateCount() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFuture = PowerMockito.mock(SQLFuture.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFuture); - PowerMockito.when(mockSqlFuture.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + @Test + public void testExecute() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + List mockFieldList = PowerMockito.spy(new ArrayList<>()); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockConn.getAutoCommit()).thenReturn(true); + when(mockConn.getExecuteType()) + .thenReturn(Constants.QueryExecuteType.SIMPLE); + when(mockConn.isSimpleExecute()).thenReturn(true); + + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(mockFieldList); VitessStatement statement = new VitessStatement(mockConn); + int fieldSize = 5; + when(mockCursor.getFields()).thenReturn(mockFieldList); + doReturn(fieldSize).when(mockFieldList).size(); + doReturn(false).when(mockFieldList).isEmpty(); + + boolean hasResultSet = statement.execute(sqlSelect); + assertTrue(hasResultSet); + assertNotNull(statement.getResultSet()); + + hasResultSet = statement.execute(sqlShow); + assertTrue(hasResultSet); + assertNotNull(statement.getResultSet()); + + int mockUpdateCount = 10; + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + when(mockCursor.getRowsAffected()).thenReturn((long) mockUpdateCount); + hasResultSet = statement.execute(sqlUpdate); + assertFalse(hasResultSet); + assertNull(statement.getResultSet()); + assertEquals(mockUpdateCount, statement.getUpdateCount()); + + //cursor is null + when(mockSqlFutureCursor.checkedGet()).thenReturn(null); try { + statement.execute(sqlUpdate); + fail("Should have thrown exception for cursor null"); + } catch (SQLException ex) { + assertEquals("Failed to execute this method", ex.getMessage()); + } + } - PowerMockito.when(mockCursor.getRowsAffected()).thenReturn(10L); - int updateCount = statement.executeUpdate(sqlUpdate); - Assert.assertEquals(10L, updateCount); - Assert.assertEquals(10L, statement.getUpdateCount()); + @Test + public void testGetUpdateCount() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFuture = mock(SQLFuture.class); - // Truncated Update Count - PowerMockito.when(mockCursor.getRowsAffected()) - .thenReturn((long) Integer.MAX_VALUE + 10); - updateCount = statement.executeUpdate(sqlUpdate); - Assert.assertEquals(Integer.MAX_VALUE, updateCount); - Assert.assertEquals(Integer.MAX_VALUE, statement.getUpdateCount()); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFuture); + when(mockSqlFuture.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(true); - statement.executeQuery(sqlSelect); - Assert.assertEquals(-1, statement.getUpdateCount()); + VitessStatement statement = new VitessStatement(mockConn); + when(mockCursor.getRowsAffected()).thenReturn(10L); + int updateCount = statement.executeUpdate(sqlUpdate); + assertEquals(10L, updateCount); + assertEquals(10L, statement.getUpdateCount()); - } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); - } + // Truncated Update Count + when(mockCursor.getRowsAffected()) + .thenReturn((long) Integer.MAX_VALUE + 10); + updateCount = statement.executeUpdate(sqlUpdate); + assertEquals(Integer.MAX_VALUE, updateCount); + assertEquals(Integer.MAX_VALUE, statement.getUpdateCount()); + + when(mockConn.isSimpleExecute()).thenReturn(true); + statement.executeQuery(sqlSelect); + assertEquals(-1, statement.getUpdateCount()); } - @Test public void testClose() throws Exception { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockConn.getExecuteType()) - .thenReturn(Constants.QueryExecuteType.SIMPLE); - PowerMockito.when(mockConn.isSimpleExecute()).thenReturn(true); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + @Test + public void testClose() throws Exception { + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockConn.getExecuteType()) + .thenReturn(Constants.QueryExecuteType.SIMPLE); + when(mockConn.isSimpleExecute()).thenReturn(true); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); VitessStatement statement = new VitessStatement(mockConn); + ResultSet rs = statement.executeQuery(sqlSelect); + statement.close(); try { - ResultSet rs = statement.executeQuery(sqlSelect); - statement.close(); - try { - statement.executeQuery(sqlSelect); - Assert.fail("Should have thrown exception for statement closed"); - } catch (SQLException ex) { - Assert.assertEquals("Statement is closed", ex.getMessage()); - } - } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + statement.executeQuery(sqlSelect); + fail("Should have thrown exception for statement closed"); + } catch (SQLException ex) { + assertEquals("Statement is closed", ex.getMessage()); } } - @Test public void testGetMaxFieldSize() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetMaxFieldSize() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertEquals(65535, statement.getMaxFieldSize()); + assertEquals(65535, statement.getMaxFieldSize()); } - @Test public void testGetMaxRows() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetMaxRows() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); statement.setMaxRows(10); - Assert.assertEquals(10, statement.getMaxRows()); + assertEquals(10, statement.getMaxRows()); try { statement.setMaxRows(-1); - Assert.fail("Should have thrown exception for wrong value"); + fail("Should have thrown exception for wrong value"); } catch (SQLException ex) { - Assert.assertEquals("Illegal value for max row", ex.getMessage()); + assertEquals("Illegal value for max row", ex.getMessage()); } } - @Test public void testGetQueryTimeout() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - Mockito.when(mockConn.getTimeout()).thenReturn((long)Constants.DEFAULT_TIMEOUT); + @Test + public void testGetQueryTimeout() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + Mockito.when(mockConn.getTimeout()).thenReturn((long) Constants.DEFAULT_TIMEOUT); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertEquals(30, statement.getQueryTimeout()); + assertEquals(30, statement.getQueryTimeout()); } - @Test public void testGetQueryTimeoutZeroDefault() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetQueryTimeoutZeroDefault() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); Mockito.when(mockConn.getTimeout()).thenReturn(0L); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertEquals(0, statement.getQueryTimeout()); + assertEquals(0, statement.getQueryTimeout()); } - @Test public void testSetQueryTimeout() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - Mockito.when(mockConn.getTimeout()).thenReturn((long)Constants.DEFAULT_TIMEOUT); + @Test + public void testSetQueryTimeout() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + Mockito.when(mockConn.getTimeout()).thenReturn((long) Constants.DEFAULT_TIMEOUT); VitessStatement statement = new VitessStatement(mockConn); int queryTimeout = 10; statement.setQueryTimeout(queryTimeout); - Assert.assertEquals(queryTimeout, statement.getQueryTimeout()); + assertEquals(queryTimeout, statement.getQueryTimeout()); try { queryTimeout = -1; statement.setQueryTimeout(queryTimeout); - Assert.fail("Should have thrown exception for wrong value"); + fail("Should have thrown exception for wrong value"); } catch (SQLException ex) { - Assert.assertEquals("Illegal value for query timeout", ex.getMessage()); + assertEquals("Illegal value for query timeout", ex.getMessage()); } statement.setQueryTimeout(0); - Assert.assertEquals(30, statement.getQueryTimeout()); + assertEquals(30, statement.getQueryTimeout()); } - @Test public void testGetWarnings() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetWarnings() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertNull(statement.getWarnings()); + assertNull(statement.getWarnings()); } - @Test public void testGetFetchDirection() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetFetchDirection() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertEquals(ResultSet.FETCH_FORWARD, statement.getFetchDirection()); + assertEquals(ResultSet.FETCH_FORWARD, statement.getFetchDirection()); } - @Test public void testGetFetchSize() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetFetchSize() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertEquals(0, statement.getFetchSize()); + assertEquals(0, statement.getFetchSize()); } - @Test public void testGetResultSetConcurrency() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetResultSetConcurrency() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertEquals(ResultSet.CONCUR_READ_ONLY, statement.getResultSetConcurrency()); + assertEquals(ResultSet.CONCUR_READ_ONLY, statement.getResultSetConcurrency()); } - @Test public void testGetResultSetType() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testGetResultSetType() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertEquals(ResultSet.TYPE_FORWARD_ONLY, statement.getResultSetType()); + assertEquals(ResultSet.TYPE_FORWARD_ONLY, statement.getResultSetType()); } - @Test public void testIsClosed() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testIsClosed() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Assert.assertFalse(statement.isClosed()); + assertFalse(statement.isClosed()); statement.close(); - Assert.assertTrue(statement.isClosed()); + assertTrue(statement.isClosed()); } - @Test public void testAutoGeneratedKeys() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); + @Test + public void testAutoGeneratedKeys() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockVtGateConn - .execute(Matchers.any(Context.class), Matchers.anyString(), Matchers.anyMap(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockVtGateConn + .execute(any(Context.class), anyString(), anyMap(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); VitessStatement statement = new VitessStatement(mockConn); - try { - - long expectedFirstGeneratedId = 121; - long[] expectedGeneratedIds = {121, 122, 123, 124, 125}; - int expectedAffectedRows = 5; - PowerMockito.when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); - PowerMockito.when(mockCursor.getRowsAffected()) + long expectedFirstGeneratedId = 121; + long[] expectedGeneratedIds = {121, 122, 123, 124, 125}; + int expectedAffectedRows = 5; + when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); + when(mockCursor.getRowsAffected()) .thenReturn(Long.valueOf(expectedAffectedRows)); - //Executing Insert Statement - int updateCount = statement.executeUpdate(sqlInsert, Statement.RETURN_GENERATED_KEYS); - Assert.assertEquals(expectedAffectedRows, updateCount); - - ResultSet rs = statement.getGeneratedKeys(); - int i = 0; - while (rs.next()) { - long generatedId = rs.getLong(1); - Assert.assertEquals(expectedGeneratedIds[i++], generatedId); - } - - //Fetching Generated Keys without notifying the driver - statement.executeUpdate(sqlInsert); - try { - statement.getGeneratedKeys(); - Assert.fail("Should have thrown exception for not setting autoGeneratedKey flag"); - } catch (SQLException ex) { - Assert.assertEquals("Generated keys not requested. You need to specify Statement" - + ".RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement()", - ex.getMessage()); - } + //Executing Insert Statement + int updateCount = statement.executeUpdate(sqlInsert, Statement.RETURN_GENERATED_KEYS); + assertEquals(expectedAffectedRows, updateCount); - //Fetching Generated Keys on update query - expectedFirstGeneratedId = 0; - PowerMockito.when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); - updateCount = statement.executeUpdate(sqlUpdate, Statement.RETURN_GENERATED_KEYS); - Assert.assertEquals(expectedAffectedRows, updateCount); - - rs = statement.getGeneratedKeys(); - Assert.assertFalse(rs.next()); + ResultSet rs = statement.getGeneratedKeys(); + int i = 0; + while (rs.next()) { + long generatedId = rs.getLong(1); + assertEquals(expectedGeneratedIds[i++], generatedId); + } - } catch (SQLException e) { - Assert.fail("Test failed " + e.getMessage()); + //Fetching Generated Keys without notifying the driver + statement.executeUpdate(sqlInsert); + try { + statement.getGeneratedKeys(); + fail("Should have thrown exception for not setting autoGeneratedKey flag"); + } catch (SQLException ex) { + assertEquals("Generated keys not requested. You need to specify Statement" + + ".RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement()", + ex.getMessage()); } + + //Fetching Generated Keys on update query + expectedFirstGeneratedId = 0; + when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); + updateCount = statement.executeUpdate(sqlUpdate, Statement.RETURN_GENERATED_KEYS); + assertEquals(expectedAffectedRows, updateCount); + + rs = statement.getGeneratedKeys(); + assertFalse(rs.next()); } - @Test public void testAddBatch() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testAddBatch() throws Exception { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); statement.addBatch(sqlInsert); - try { - Field privateStringField = VitessStatement.class.getDeclaredField("batchedArgs"); - privateStringField.setAccessible(true); - Assert - .assertEquals(sqlInsert, ((List) privateStringField.get(statement)).get(0)); - } catch (NoSuchFieldException e) { - Assert.fail("Private Field should exists: batchedArgs"); - } catch (IllegalAccessException e) { - Assert.fail("Private Field should be accessible: batchedArgs"); - } + Field privateStringField = VitessStatement.class.getDeclaredField("batchedArgs"); + privateStringField.setAccessible(true); + assertEquals(sqlInsert, ((List) privateStringField.get(statement)).get(0)); } - @Test public void testClearBatch() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testClearBatch() throws Exception { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); statement.addBatch(sqlInsert); statement.clearBatch(); - try { - Field privateStringField = VitessStatement.class.getDeclaredField("batchedArgs"); - privateStringField.setAccessible(true); - Assert.assertTrue(((List) privateStringField.get(statement)).isEmpty()); - } catch (NoSuchFieldException e) { - Assert.fail("Private Field should exists: batchedArgs"); - } catch (IllegalAccessException e) { - Assert.fail("Private Field should be accessible: batchedArgs"); - } + Field privateStringField = VitessStatement.class.getDeclaredField("batchedArgs"); + privateStringField.setAccessible(true); + assertTrue(((List) privateStringField.get(statement)).isEmpty()); } - @Test public void testExecuteBatch() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testExecuteBatch() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); int[] updateCounts = statement.executeBatch(); - Assert.assertEquals(0, updateCounts.length); + assertEquals(0, updateCounts.length); - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockConn.getAutoCommit()).thenReturn(true); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - PowerMockito.when(mockVtGateConn - .executeBatch(Matchers.any(Context.class), Matchers.anyList(), Matchers.anyList(), - Matchers.any(VTSession.class))).thenReturn(mockSqlFutureCursor); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + when(mockVtGateConn + .executeBatch(any(Context.class), anyList(), anyList(), + any(VTSession.class))).thenReturn(mockSqlFutureCursor); List mockCursorWithErrorList = new ArrayList<>(); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); - CursorWithError mockCursorWithError1 = PowerMockito.mock(CursorWithError.class); - PowerMockito.when(mockCursorWithError1.getError()).thenReturn(null); - PowerMockito.when(mockCursorWithError1.getCursor()) - .thenReturn(PowerMockito.mock(Cursor.class)); + CursorWithError mockCursorWithError1 = mock(CursorWithError.class); + when(mockCursorWithError1.getError()).thenReturn(null); + when(mockCursorWithError1.getCursor()) + .thenReturn(mock(Cursor.class)); mockCursorWithErrorList.add(mockCursorWithError1); statement.addBatch(sqlUpdate); updateCounts = statement.executeBatch(); - Assert.assertEquals(1, updateCounts.length); + assertEquals(1, updateCounts.length); - CursorWithError mockCursorWithError2 = PowerMockito.mock(CursorWithError.class); + CursorWithError mockCursorWithError2 = mock(CursorWithError.class); Vtrpc.RPCError rpcError = Vtrpc.RPCError.newBuilder().setMessage("statement execute batch error").build(); - PowerMockito.when(mockCursorWithError2.getError()) - .thenReturn(rpcError); + when(mockCursorWithError2.getError()) + .thenReturn(rpcError); mockCursorWithErrorList.add(mockCursorWithError2); statement.addBatch(sqlUpdate); statement.addBatch(sqlUpdate); try { statement.executeBatch(); - Assert.fail("Should have thrown Exception"); + fail("Should have thrown Exception"); } catch (BatchUpdateException ex) { - Assert.assertEquals(rpcError.toString(), ex.getMessage()); - Assert.assertEquals(2, ex.getUpdateCounts().length); - Assert.assertEquals(Statement.EXECUTE_FAILED, ex.getUpdateCounts()[1]); + assertEquals(rpcError.toString(), ex.getMessage()); + assertEquals(2, ex.getUpdateCounts().length); + assertEquals(Statement.EXECUTE_FAILED, ex.getUpdateCounts()[1]); } } - @Test public void testBatchGeneratedKeys() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testBatchGeneratedKeys() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); - - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); - - PowerMockito.when(mockVtGateConn - .executeBatch(Matchers.any(Context.class), - Matchers.anyList(), - Matchers.anyList(), - Matchers.any(VTSession.class))) - .thenReturn(mockSqlFutureCursor); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockConn.getAutoCommit()).thenReturn(true); + + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + + when(mockVtGateConn + .executeBatch(any(Context.class), + anyList(), + anyList(), + any(VTSession.class))) + .thenReturn(mockSqlFutureCursor); List mockCursorWithErrorList = new ArrayList<>(); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); - CursorWithError mockCursorWithError = PowerMockito.mock(CursorWithError.class); - PowerMockito.when(mockCursorWithError.getError()).thenReturn(null); - PowerMockito.when(mockCursorWithError.getCursor()).thenReturn(mockCursor); + CursorWithError mockCursorWithError = mock(CursorWithError.class); + when(mockCursorWithError.getError()).thenReturn(null); + when(mockCursorWithError.getCursor()).thenReturn(mockCursor); mockCursorWithErrorList.add(mockCursorWithError); long expectedFirstGeneratedId = 121; long[] expectedGeneratedIds = {121, 122, 123, 124, 125}; - PowerMockito.when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); - PowerMockito.when(mockCursor.getRowsAffected()).thenReturn(Long.valueOf(expectedGeneratedIds.length)); + when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); + when(mockCursor.getRowsAffected()).thenReturn(Long.valueOf(expectedGeneratedIds.length)); statement.addBatch(sqlInsert); statement.executeBatch(); @@ -695,41 +669,42 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun int i = 0; while (rs.next()) { long generatedId = rs.getLong(1); - Assert.assertEquals(expectedGeneratedIds[i++], generatedId); + assertEquals(expectedGeneratedIds[i++], generatedId); } } - @Test public void testBatchUpsertGeneratedKeys() throws SQLException { - VitessConnection mockConn = PowerMockito.mock(VitessConnection.class); + @Test + public void testBatchUpsertGeneratedKeys() throws SQLException { + VitessConnection mockConn = mock(VitessConnection.class); VitessStatement statement = new VitessStatement(mockConn); - Cursor mockCursor = PowerMockito.mock(Cursor.class); - SQLFuture mockSqlFutureCursor = PowerMockito.mock(SQLFuture.class); - - VTGateConnection mockVtGateConn = PowerMockito.mock(VTGateConnection.class); - PowerMockito.when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); - PowerMockito.when(mockConn.getAutoCommit()).thenReturn(true); - - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); - PowerMockito.when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); - - PowerMockito.when(mockVtGateConn - .executeBatch(Matchers.any(Context.class), - Matchers.anyList(), - Matchers.anyList(), - Matchers.any(VTSession.class))) - .thenReturn(mockSqlFutureCursor); + Cursor mockCursor = mock(Cursor.class); + SQLFuture mockSqlFutureCursor = mock(SQLFuture.class); + + VTGateConnection mockVtGateConn = mock(VTGateConnection.class); + when(mockConn.getVtGateConn()).thenReturn(mockVtGateConn); + when(mockConn.getAutoCommit()).thenReturn(true); + + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursor); + when(mockCursor.getFields()).thenReturn(Query.QueryResult.getDefaultInstance().getFieldsList()); + + when(mockVtGateConn + .executeBatch(any(Context.class), + anyList(), + anyList(), + any(VTSession.class))) + .thenReturn(mockSqlFutureCursor); List mockCursorWithErrorList = new ArrayList<>(); - PowerMockito.when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); + when(mockSqlFutureCursor.checkedGet()).thenReturn(mockCursorWithErrorList); - CursorWithError mockCursorWithError = PowerMockito.mock(CursorWithError.class); - PowerMockito.when(mockCursorWithError.getError()).thenReturn(null); - PowerMockito.when(mockCursorWithError.getCursor()).thenReturn(mockCursor); + CursorWithError mockCursorWithError = mock(CursorWithError.class); + when(mockCursorWithError.getError()).thenReturn(null); + when(mockCursorWithError.getCursor()).thenReturn(mockCursor); mockCursorWithErrorList.add(mockCursorWithError); long expectedFirstGeneratedId = 121; long[] expectedGeneratedIds = {121, 122}; - PowerMockito.when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); - PowerMockito.when(mockCursor.getRowsAffected()).thenReturn(Long.valueOf(expectedGeneratedIds.length)); + when(mockCursor.getInsertId()).thenReturn(expectedFirstGeneratedId); + when(mockCursor.getRowsAffected()).thenReturn(Long.valueOf(expectedGeneratedIds.length)); statement.addBatch(sqlUpsert); statement.executeBatch(); @@ -738,19 +713,19 @@ private void testExecute(int fetchSize, boolean simpleExecute, boolean shouldRun int i = 0; while (rs.next()) { long generatedId = rs.getLong(1); - Assert.assertEquals(expectedGeneratedIds[i], generatedId); - Assert.assertEquals(i, 0); // we should only have one + assertEquals(expectedGeneratedIds[i], generatedId); + assertEquals(i, 0); // we should only have one i++; } VitessStatement noUpdate = new VitessStatement(mockConn); - PowerMockito.when(mockCursor.getInsertId()).thenReturn(0L); - PowerMockito.when(mockCursor.getRowsAffected()).thenReturn(1L); + when(mockCursor.getInsertId()).thenReturn(0L); + when(mockCursor.getRowsAffected()).thenReturn(1L); noUpdate.addBatch(sqlUpsert); noUpdate.executeBatch(); ResultSet empty = noUpdate.getGeneratedKeys(); - Assert.assertFalse(empty.next()); + assertFalse(empty.next()); } } From 40dafcfb7f2af4415fa6a05af0b76daaa668c81d Mon Sep 17 00:00:00 2001 From: Andres Taylor Date: Fri, 14 Dec 2018 09:05:27 +0100 Subject: [PATCH 2/2] Optimize jdbc imports Signed-off-by: Andres Taylor --- .../io/vitess/jdbc/ConnectionProperties.java | 10 ++--- .../io/vitess/jdbc/FieldWithMetadata.java | 7 ++-- .../java/io/vitess/jdbc/VitessConnection.java | 16 ++++---- .../vitess/jdbc/VitessDatabaseMetaData.java | 4 +- .../java/io/vitess/jdbc/VitessDriver.java | 4 +- .../java/io/vitess/jdbc/VitessJDBCUrl.java | 6 +-- .../jdbc/VitessMariaDBDatabaseMetadata.java | 6 +-- .../jdbc/VitessMySQLDatabaseMetadata.java | 11 ++--- .../vitess/jdbc/VitessPreparedStatement.java | 16 ++++---- .../java/io/vitess/jdbc/VitessResultSet.java | 17 ++++---- .../vitess/jdbc/VitessResultSetMetaData.java | 7 ++-- .../java/io/vitess/jdbc/VitessStatement.java | 18 ++++----- .../io/vitess/jdbc/VitessVTGateManager.java | 18 ++++----- .../test/java/io/vitess/jdbc/BaseTest.java | 5 ++- .../vitess/jdbc/ConnectionPropertiesTest.java | 17 ++++---- .../io/vitess/jdbc/FieldWithMetadataTest.java | 5 ++- .../io/vitess/jdbc/VitessConnectionTest.java | 27 ++++++++----- .../jdbc/VitessDatabaseMetadataTest.java | 23 ++++++----- .../java/io/vitess/jdbc/VitessDriverTest.java | 11 +++-- .../io/vitess/jdbc/VitessJDBCUrlTest.java | 5 ++- .../jdbc/VitessParameterMetaDataTest.java | 7 ++-- .../jdbc/VitessPreparedStatementTest.java | 40 +++++++++---------- .../jdbc/VitessResultSetMetadataTest.java | 11 ++--- .../io/vitess/jdbc/VitessResultSetTest.java | 25 ++++++------ .../io/vitess/jdbc/VitessStatementTest.java | 30 ++++++++------ .../vitess/jdbc/VitessVTGateManagerTest.java | 11 ++--- 26 files changed, 190 insertions(+), 167 deletions(-) diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/ConnectionProperties.java b/java/jdbc/src/main/java/io/vitess/jdbc/ConnectionProperties.java index 72850bb666a..f978311831e 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/ConnectionProperties.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/ConnectionProperties.java @@ -16,6 +16,11 @@ package io.vitess.jdbc; +import io.vitess.proto.Query; +import io.vitess.proto.Topodata; +import io.vitess.util.Constants; +import io.vitess.util.StringUtils; + import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.sql.DriverPropertyInfo; @@ -27,11 +32,6 @@ import java.util.Properties; import java.util.concurrent.TimeUnit; -import io.vitess.proto.Query; -import io.vitess.proto.Topodata; -import io.vitess.util.Constants; -import io.vitess.util.StringUtils; - public class ConnectionProperties { private static final ArrayList PROPERTY_LIST = new ArrayList<>(); diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/FieldWithMetadata.java b/java/jdbc/src/main/java/io/vitess/jdbc/FieldWithMetadata.java index e26253e017f..910c83825e3 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/FieldWithMetadata.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/FieldWithMetadata.java @@ -17,9 +17,6 @@ package io.vitess.jdbc; import com.google.common.annotations.VisibleForTesting; -import java.sql.SQLException; -import java.sql.Types; -import java.util.regex.PatternSyntaxException; import io.vitess.proto.Query; import io.vitess.util.Constants; @@ -27,6 +24,10 @@ import io.vitess.util.StringUtils; import io.vitess.util.charset.CharsetMapping; +import java.sql.SQLException; +import java.sql.Types; +import java.util.regex.PatternSyntaxException; + public class FieldWithMetadata { private final ConnectionProperties connectionProperties; diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java index 601b35f2801..9fcd3d947be 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessConnection.java @@ -16,6 +16,14 @@ package io.vitess.jdbc; +import io.vitess.client.Context; +import io.vitess.client.VTGateConnection; +import io.vitess.client.VTSession; +import io.vitess.proto.Query; +import io.vitess.util.CommonUtils; +import io.vitess.util.Constants; +import io.vitess.util.MysqlDefs; + import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; @@ -42,14 +50,6 @@ import java.util.Set; import java.util.concurrent.Executor; -import io.vitess.client.Context; -import io.vitess.client.VTGateConnection; -import io.vitess.client.VTSession; -import io.vitess.proto.Query; -import io.vitess.util.CommonUtils; -import io.vitess.util.Constants; -import io.vitess.util.MysqlDefs; - /** * Created by harshit.gangal on 23/01/16. */ diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessDatabaseMetaData.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessDatabaseMetaData.java index e0f3c0fbd9d..61942951a15 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessDatabaseMetaData.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessDatabaseMetaData.java @@ -16,14 +16,14 @@ package io.vitess.jdbc; +import io.vitess.util.Constants; + import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger; -import io.vitess.util.Constants; - /** * Created by harshit.gangal on 25/01/16. */ diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java index 1518f52371b..a06f7df9904 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessDriver.java @@ -16,6 +16,8 @@ package io.vitess.jdbc; +import io.vitess.util.Constants; + import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; @@ -25,8 +27,6 @@ import java.util.Properties; import java.util.logging.Logger; -import io.vitess.util.Constants; - /** * VitessDriver is the official JDBC driver for Vitess. * diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessJDBCUrl.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessJDBCUrl.java index ca7f39c22ee..416a76734a6 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessJDBCUrl.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessJDBCUrl.java @@ -16,6 +16,9 @@ package io.vitess.jdbc; +import io.vitess.util.Constants; +import io.vitess.util.StringUtils; + import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.SQLException; @@ -26,9 +29,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import io.vitess.util.Constants; -import io.vitess.util.StringUtils; - /** * VitessJDBCUrl is responsible for parsing a driver URL and Properties object, * returning a new Properties object with configuration from the URL and passed in Properties diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessMariaDBDatabaseMetadata.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessMariaDBDatabaseMetadata.java index 1dc87d55d7e..5b0f47f7e07 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessMariaDBDatabaseMetadata.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessMariaDBDatabaseMetadata.java @@ -16,6 +16,9 @@ package io.vitess.jdbc; +import io.vitess.proto.Query; +import io.vitess.util.Constants; + import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -24,9 +27,6 @@ import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger; -import io.vitess.proto.Query; -import io.vitess.util.Constants; - /** * Created by ashudeep.sharma on 15/02/16. */ diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessMySQLDatabaseMetadata.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessMySQLDatabaseMetadata.java index 8a72ef686bb..e94541dacde 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessMySQLDatabaseMetadata.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessMySQLDatabaseMetadata.java @@ -17,6 +17,12 @@ package io.vitess.jdbc; import com.google.common.annotations.VisibleForTesting; +import org.apache.commons.lang.StringUtils; + +import io.vitess.proto.Query; +import io.vitess.util.Constants; +import io.vitess.util.MysqlDefs; + import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -35,11 +41,6 @@ import java.util.StringTokenizer; import java.util.TreeMap; import java.util.logging.Logger; -import org.apache.commons.lang.StringUtils; - -import io.vitess.proto.Query; -import io.vitess.util.Constants; -import io.vitess.util.MysqlDefs; /** * Created by ashudeep.sharma on 15/02/16. diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java index 304456af86f..d53d7c86ceb 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessPreparedStatement.java @@ -16,6 +16,14 @@ package io.vitess.jdbc; +import io.vitess.client.Context; +import io.vitess.client.VTGateConnection; +import io.vitess.client.cursor.Cursor; +import io.vitess.client.cursor.CursorWithError; +import io.vitess.mysql.DateTime; +import io.vitess.util.Constants; +import io.vitess.util.StringUtils; + import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; @@ -49,14 +57,6 @@ import java.util.Locale; import java.util.Map; -import io.vitess.client.Context; -import io.vitess.client.VTGateConnection; -import io.vitess.client.cursor.Cursor; -import io.vitess.client.cursor.CursorWithError; -import io.vitess.mysql.DateTime; -import io.vitess.util.Constants; -import io.vitess.util.StringUtils; - /** * Created by harshit.gangal on 25/01/16. *

diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java index f7fd6715519..f13a31d24fb 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSet.java @@ -18,6 +18,15 @@ import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; + +import io.vitess.client.cursor.Cursor; +import io.vitess.client.cursor.Row; +import io.vitess.client.cursor.SimpleCursor; +import io.vitess.proto.Query; +import io.vitess.util.Constants; +import io.vitess.util.StringUtils; + +import javax.sql.rowset.serial.SerialClob; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.Reader; @@ -46,14 +55,6 @@ import java.util.Calendar; import java.util.List; import java.util.Map; -import javax.sql.rowset.serial.SerialClob; - -import io.vitess.client.cursor.Cursor; -import io.vitess.client.cursor.Row; -import io.vitess.client.cursor.SimpleCursor; -import io.vitess.proto.Query; -import io.vitess.util.Constants; -import io.vitess.util.StringUtils; /** * Created by harshit.gangal on 23/01/16. diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSetMetaData.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSetMetaData.java index a7f8c7cb4a3..8eddb40752f 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSetMetaData.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessResultSetMetaData.java @@ -17,15 +17,16 @@ package io.vitess.jdbc; import com.google.common.collect.ImmutableList; + +import io.vitess.proto.Query; +import io.vitess.util.Constants; + import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.List; import java.util.logging.Logger; -import io.vitess.proto.Query; -import io.vitess.util.Constants; - /** * Created by harshit.gangal on 25/01/16. diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java index 3e2373e4ca4..bde82e6f01e 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessStatement.java @@ -16,15 +16,6 @@ package io.vitess.jdbc; -import java.sql.BatchUpdateException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.sql.SQLWarning; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - import io.vitess.client.Context; import io.vitess.client.Proto; import io.vitess.client.VTGateConnection; @@ -35,6 +26,15 @@ import io.vitess.util.Constants; import io.vitess.util.StringUtils; +import java.sql.BatchUpdateException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.sql.SQLWarning; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + /** * Created by harshit.gangal on 19/01/16. *

diff --git a/java/jdbc/src/main/java/io/vitess/jdbc/VitessVTGateManager.java b/java/jdbc/src/main/java/io/vitess/jdbc/VitessVTGateManager.java index 895f8ef3f70..b9047d2a8c9 100644 --- a/java/jdbc/src/main/java/io/vitess/jdbc/VitessVTGateManager.java +++ b/java/jdbc/src/main/java/io/vitess/jdbc/VitessVTGateManager.java @@ -16,6 +16,14 @@ package io.vitess.jdbc; +import io.vitess.client.Context; +import io.vitess.client.RefreshableVTGateConnection; +import io.vitess.client.VTGateConnection; +import io.vitess.client.grpc.GrpcClientFactory; +import io.vitess.client.grpc.RetryingInterceptorConfig; +import io.vitess.client.grpc.tls.TlsOptions; +import io.vitess.util.Constants; + import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; @@ -26,16 +34,8 @@ import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; import java.util.logging.Level; - -import io.vitess.client.Context; -import io.vitess.client.VTGateConnection; -import io.vitess.client.RefreshableVTGateConnection; -import io.vitess.client.grpc.GrpcClientFactory; -import io.vitess.client.grpc.RetryingInterceptorConfig; -import io.vitess.client.grpc.tls.TlsOptions; -import io.vitess.util.Constants; +import java.util.logging.Logger; /** * Created by naveen.nahata on 24/02/16. diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/BaseTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/BaseTest.java index 0d807e2f7ec..5d4f7fbfaff 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/BaseTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/BaseTest.java @@ -16,11 +16,12 @@ package io.vitess.jdbc; -import java.sql.SQLException; -import java.util.Properties; import org.junit.Assert; import org.junit.BeforeClass; +import java.sql.SQLException; +import java.util.Properties; + public class BaseTest { String dbURL = "jdbc:vitess://locahost:9000/vt_keyspace/keyspace"; diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java index 79a4e12d0c5..195b867fa4d 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/ConnectionPropertiesTest.java @@ -16,12 +16,6 @@ package io.vitess.jdbc; -import java.sql.DriverPropertyInfo; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.Properties; - -import io.vitess.util.Constants.ZeroDateTimeBehavior; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; @@ -29,11 +23,20 @@ import io.vitess.proto.Query; import io.vitess.proto.Topodata; import io.vitess.util.Constants; +import io.vitess.util.Constants.ZeroDateTimeBehavior; + +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Properties; import static io.vitess.util.Constants.DEFAULT_EXECUTE_TYPE; import static io.vitess.util.Constants.DEFAULT_INCLUDED_FIELDS; import static io.vitess.util.Constants.DEFAULT_TABLET_TYPE; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/FieldWithMetadataTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/FieldWithMetadataTest.java index c81ce9d5d7f..863399930a3 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/FieldWithMetadataTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/FieldWithMetadataTest.java @@ -16,8 +16,6 @@ package io.vitess.jdbc; -import java.sql.SQLException; -import java.sql.Types; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,6 +29,9 @@ import io.vitess.util.MysqlDefs; import io.vitess.util.charset.CharsetMapping; +import java.sql.SQLException; +import java.sql.Types; + @PrepareForTest(FieldWithMetadata.class) @RunWith(PowerMockRunner.class) public class FieldWithMetadataTest extends BaseTest { diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java index 8a25caf7e77..64df7a23a58 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessConnectionTest.java @@ -16,14 +16,6 @@ package io.vitess.jdbc; -import java.lang.reflect.Field; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.Properties; - -import io.vitess.proto.Query.ExecuteOptions.TransactionIsolation; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -32,11 +24,26 @@ import io.vitess.client.VTSession; import io.vitess.proto.Query; +import io.vitess.proto.Query.ExecuteOptions.TransactionIsolation; import io.vitess.proto.Topodata; import io.vitess.util.Constants; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import java.lang.reflect.Field; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; /** * Created by harshit.gangal on 19/01/16. diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessDatabaseMetadataTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessDatabaseMetadataTest.java index 07d7fd1c2b8..d930e08d3a7 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessDatabaseMetadataTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessDatabaseMetadataTest.java @@ -19,6 +19,18 @@ import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import io.vitess.client.cursor.Cursor; +import io.vitess.client.cursor.SimpleCursor; +import io.vitess.proto.Query; +import io.vitess.util.Constants; + import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -31,17 +43,6 @@ import java.util.List; import java.util.Properties; import java.util.Scanner; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import io.vitess.client.cursor.Cursor; -import io.vitess.client.cursor.SimpleCursor; -import io.vitess.proto.Query; -import io.vitess.util.Constants; /** * Created by ashudeep.sharma on 08/03/16. diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java index b3fdd1388a1..326403f8298 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessDriverTest.java @@ -16,17 +16,16 @@ package io.vitess.jdbc; -import java.sql.DriverManager; -import java.sql.DriverPropertyInfo; -import java.sql.SQLException; -import java.util.Properties; - -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import io.vitess.util.Constants; +import java.sql.DriverManager; +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; +import java.util.Properties; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessJDBCUrlTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessJDBCUrlTest.java index d0d29078383..130d5bedf31 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessJDBCUrlTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessJDBCUrlTest.java @@ -16,14 +16,15 @@ package io.vitess.jdbc; -import java.sql.SQLException; -import java.util.Properties; import org.junit.Assert; import org.junit.Test; import io.vitess.proto.Topodata; import io.vitess.util.Constants; +import java.sql.SQLException; +import java.util.Properties; + /** * Created by naveen.nahata on 18/02/16. */ diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessParameterMetaDataTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessParameterMetaDataTest.java index 3c313d11814..57212aa40d5 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessParameterMetaDataTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessParameterMetaDataTest.java @@ -16,9 +16,6 @@ package io.vitess.jdbc; -import java.sql.ParameterMetaData; -import java.sql.SQLException; -import java.sql.Types; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,6 +24,10 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import java.sql.ParameterMetaData; +import java.sql.SQLException; +import java.sql.Types; + @RunWith(PowerMockRunner.class) @PrepareForTest(VitessParameterMetaData.class) public class VitessParameterMetaDataTest { diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java index 9fabc9be6d4..95512fd6f8d 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessPreparedStatementTest.java @@ -16,25 +16,7 @@ package io.vitess.jdbc; -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.BatchUpdateException; -import java.sql.Date; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Time; -import java.sql.Timestamp; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import javax.sql.rowset.serial.SerialClob; - +import com.google.common.collect.ImmutableMap; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -44,8 +26,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.google.common.collect.ImmutableMap; - import io.vitess.client.Context; import io.vitess.client.SQLFuture; import io.vitess.client.VTGateConnection; @@ -57,6 +37,24 @@ import io.vitess.proto.Vtrpc; import io.vitess.util.Constants; +import javax.sql.rowset.serial.SerialClob; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.BatchUpdateException; +import java.sql.Date; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Time; +import java.sql.Timestamp; +import java.sql.Types; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetMetadataTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetMetadataTest.java index 3f3140aadbe..3ac7be7b5eb 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetMetadataTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetMetadataTest.java @@ -16,11 +16,6 @@ package io.vitess.jdbc; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Types; -import java.util.ArrayList; -import java.util.List; import org.junit.Assert; import org.junit.Test; @@ -28,6 +23,12 @@ import io.vitess.util.Constants; import io.vitess.util.charset.CharsetMapping; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.List; + /** * Created by ashudeep.sharma on 08/02/16. */ diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java index 80edc9033b5..ce2c8b79aa2 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessResultSetTest.java @@ -16,17 +16,7 @@ package io.vitess.jdbc; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.Clob; -import java.sql.SQLException; -import java.sql.Time; -import java.sql.Timestamp; -import java.util.Properties; - +import com.google.protobuf.ByteString; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -36,8 +26,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.google.protobuf.ByteString; - import io.vitess.client.cursor.Cursor; import io.vitess.client.cursor.SimpleCursor; import io.vitess.proto.Query; @@ -45,6 +33,17 @@ import io.vitess.util.StringUtils; import io.vitess.util.charset.CharsetMapping; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Clob; +import java.sql.SQLException; +import java.sql.Time; +import java.sql.Timestamp; +import java.util.Properties; + import static org.junit.Assert.assertEquals; /** diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java index febb968e5fa..2880d5ab3fe 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessStatementTest.java @@ -16,18 +16,8 @@ package io.vitess.jdbc; -import java.lang.reflect.Field; -import java.sql.BatchUpdateException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Matchers; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -43,8 +33,24 @@ import io.vitess.proto.Vtrpc; import io.vitess.util.Constants; -import static org.junit.Assert.*; -import static org.mockito.Matchers.*; +import java.lang.reflect.Field; +import java.sql.BatchUpdateException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyList; +import static org.mockito.Matchers.anyMap; +import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.verify; import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.mock; diff --git a/java/jdbc/src/test/java/io/vitess/jdbc/VitessVTGateManagerTest.java b/java/jdbc/src/test/java/io/vitess/jdbc/VitessVTGateManagerTest.java index b8a6e9253e6..86eb64f43d7 100644 --- a/java/jdbc/src/test/java/io/vitess/jdbc/VitessVTGateManagerTest.java +++ b/java/jdbc/src/test/java/io/vitess/jdbc/VitessVTGateManagerTest.java @@ -16,11 +16,6 @@ package io.vitess.jdbc; -import java.io.IOException; -import java.lang.reflect.Field; -import java.sql.SQLException; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; import org.joda.time.Duration; import org.junit.Assert; import org.junit.Test; @@ -31,6 +26,12 @@ import io.vitess.client.grpc.GrpcClientFactory; import io.vitess.proto.Vtrpc; +import java.io.IOException; +import java.lang.reflect.Field; +import java.sql.SQLException; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; + /** * Created by naveen.nahata on 29/02/16. */