summaryrefslogtreecommitdiffstats
path: root/sql/src/test/java/tests/SQLite
diff options
context:
space:
mode:
Diffstat (limited to 'sql/src/test/java/tests/SQLite')
-rw-r--r--sql/src/test/java/tests/SQLite/AbstractSqlTest.java244
-rw-r--r--sql/src/test/java/tests/SQLite/AllTests.java38
-rw-r--r--sql/src/test/java/tests/SQLite/BlobTest.java223
-rw-r--r--sql/src/test/java/tests/SQLite/ConstantsTest.java110
-rw-r--r--sql/src/test/java/tests/SQLite/DatabaseTest.java2036
-rw-r--r--sql/src/test/java/tests/SQLite/ExceptionTest.java53
-rw-r--r--sql/src/test/java/tests/SQLite/FunctionContextTest.java156
-rw-r--r--sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java117
-rw-r--r--sql/src/test/java/tests/SQLite/JDBCDriverTest.java280
-rw-r--r--sql/src/test/java/tests/SQLite/SQLiteTest.java76
-rw-r--r--sql/src/test/java/tests/SQLite/ShellTest.java147
-rw-r--r--sql/src/test/java/tests/SQLite/StmtTest.java962
12 files changed, 4442 insertions, 0 deletions
diff --git a/sql/src/test/java/tests/SQLite/AbstractSqlTest.java b/sql/src/test/java/tests/SQLite/AbstractSqlTest.java
new file mode 100644
index 0000000..f580f70
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/AbstractSqlTest.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package tests.SQLite;
+
+import SQLite.Callback;
+import SQLite.Database;
+import SQLite.Exception;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+
+import junit.framework.TestCase;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+
+/**
+ * This class provides SQL unit test, which can be used by subclasses eg. to
+ * test JDBC drivers.
+ */
+@TestTargetClass(Database.class)
+abstract class AbstractSqlTest extends TestCase {
+
+ /**
+ * The first connection.
+ */
+ private Connection firstConnection;
+
+ /**
+ * The second connection.
+ */
+ private Connection secondConnection;
+
+ /**
+ * The statement from the first connection.
+ */
+ private Statement firstStmt;
+
+ /**
+ * The statement from the second connection.
+ */
+ private Statement secondStmt;
+
+ /**
+ * The values of the first column "one".
+ */
+ private final String[] ones = {"hello!", "goodbye"};
+
+ /**
+ * The values of the second column "two".
+ */
+ private final short[] twos = {10, 20};
+
+ /**
+ * The updated values of the first column "one".
+ */
+ private final String[] ones_updated;
+
+ /** Creates a new instance of this class */
+ public AbstractSqlTest(String testName) {
+ super(testName);
+ ones_updated = new String[ones.length];
+ for (int i = 0; i < ones.length; i++) {
+ ones_updated[i] = ones[i] + twos[i];
+ }
+ }
+
+ /**
+ * Sets up a unit test, by creating two statements from two connections and
+ * creating a test table.
+ *
+ * @exception SQLException if there is a problem accessing the database
+ * @throws Exception
+ * @exception Exception may be thrown by subclasses
+ */
+ @Override
+ protected void setUp() throws InstantiationException,
+ IllegalAccessException, ClassNotFoundException, SQLException, Exception {
+ Class.forName(getDriverClassName()).newInstance();
+ firstConnection = DriverManager.getConnection(getConnectionURL());
+ firstConnection.setTransactionIsolation(getTransactionIsolation());
+ secondConnection = DriverManager.getConnection(getConnectionURL());
+ secondConnection.setTransactionIsolation(getTransactionIsolation());
+ firstStmt = firstConnection.createStatement();
+ firstStmt.execute("create table tbl1(one varchar(10), two smallint)");
+ secondStmt = secondConnection.createStatement();
+ }
+
+ /**
+ * Tears down a unit test, by setting the auto commit property of the first
+ * connection back to true, dropping the test table and closing the two
+ * connections.
+ */
+ @Override
+ protected void tearDown() throws SQLException {
+ firstStmt.close();
+ secondStmt.close();
+ firstConnection.setAutoCommit(true);
+ firstStmt = firstConnection.createStatement();
+ firstStmt.execute("drop table tbl1");
+ firstStmt.close();
+ firstConnection.close();
+ secondConnection.close();
+ }
+
+ /**
+ * Adds some rows to the test table and asserts that the rows can be
+ * retrieved again.
+ *
+ * @throws SQLException if there is a problem accessing the database
+ */
+ private void autoCommitInsertSelect() throws SQLException {
+ firstStmt.getConnection().setAutoCommit(true);
+ for (int i = 0; i < ones.length; i++) {
+ firstStmt.execute("insert into tbl1 values('" + ones[i] + "',"
+ + twos[i] + ")");
+ }
+ assertAllFromTbl1(firstStmt, ones, twos);
+ }
+
+ /**
+ * Asserts that the expected values can be selected from the test table.
+ *
+ * @param stmt the statement to be used for the selection of the data
+ * @param ones the expected values of the column 'one'
+ * @param twos the expected values of the column 'two'
+ * @throws SQLException if there is a problem accessing the database
+ */
+ private void assertAllFromTbl1(Statement stmt, String[] ones, short[] twos)
+ throws SQLException {
+ ResultSet rs = stmt.executeQuery("select * from tbl1");
+ int i = 0;
+ for (; rs.next(); i++) {
+ assertTrue(i < ones.length);
+ assertEquals(ones[i], rs.getString("one"));
+ assertEquals(twos[i], rs.getShort("two"));
+ }
+ assertTrue(i == ones.length);
+ }
+
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ notes = "",
+ clazz = Database.class,
+ method = "exec",
+ args = {String.class, Callback.class}
+ )
+ public void testAutoCommitInsertSelect() throws SQLException{
+ autoCommitInsertSelect();
+ }
+
+ /**
+ * Tests the following sequence after successful insertion of some test
+ * data:
+ * - update data from connection one
+ * - select data from connection two (-> should have the old values)
+ * - commit data from connection one
+ * - select data from connection two (-> should have the new values)
+ *
+ * @throws SQLException if there is a problem accessing the database
+ */
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ notes = "",
+ clazz = Database.class,
+ method = "exec",
+ args = {String.class, Callback.class}
+ )
+ public void testUpdateSelectCommitSelect() throws SQLException {
+ autoCommitInsertSelect();
+ firstStmt.getConnection().setAutoCommit(false);
+ updateOnes(firstStmt, ones_updated, twos);
+ assertAllFromTbl1(secondStmt, ones, twos);
+ firstStmt.getConnection().commit();
+ assertAllFromTbl1(secondStmt, ones_updated, twos);
+ }
+
+ /**
+ * Tests the following sequence after successful insertion of some test
+ * data:
+ * - update data from connection one
+ * - select data from connection two (-> should have the old values)
+ * - rollback data from connection one
+ * - select data from connection two (-> should still have the old values)
+ *
+ * @throws SQLException if there is a problem accessing the database
+ */
+ @TestTargetNew(
+ level = TestLevel.PARTIAL_COMPLETE,
+ notes = "",
+ clazz = Database.class,
+ method = "exec",
+ args = {String.class, Callback.class}
+ )
+ public void testUpdateSelectRollbackSelect() throws SQLException {
+ autoCommitInsertSelect();
+ firstStmt.getConnection().setAutoCommit(false);
+ updateOnes(firstStmt, ones_updated, twos);
+ assertAllFromTbl1(secondStmt, ones, twos);
+ firstStmt.getConnection().rollback();
+ assertAllFromTbl1(secondStmt, ones, twos);
+ }
+
+ /**
+ * Updates the values in column 'one'
+ * @param stmt the statement to be used to update the data
+ * @param ones_updated the updated valus of column 'one'
+ * @param twos the reference values of column 'two'
+ * @throws SQLException if there is a problem accessing the database
+ */
+ private void updateOnes(Statement stmt, String[] ones_updated, short[] twos)
+ throws SQLException {
+ for (int i = 0; i < ones_updated.length; i++) {
+ stmt.execute("UPDATE tbl1 SET one = '" + ones_updated[i]
+ + "' WHERE two = " + twos[i]);
+ }
+ }
+
+ protected abstract String getConnectionURL();
+
+ protected abstract String getDriverClassName();
+
+ protected abstract int getTransactionIsolation();
+
+}
diff --git a/sql/src/test/java/tests/SQLite/AllTests.java b/sql/src/test/java/tests/SQLite/AllTests.java
new file mode 100644
index 0000000..bb41f58
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/AllTests.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+public class AllTests {
+
+ //All tests executed with sqlite3 only
+ public static Test suite() {
+ TestSuite suite = tests.TestSuiteFactory.createTestSuite("Tests for SQLite");
+ //$JUnit-BEGIN$
+ suite.addTestSuite(DatabaseTest.class);
+ suite.addTestSuite(JDBCDriverFunctionalTest.class);
+ suite.addTestSuite(JDBCDriverTest.class);
+ suite.addTestSuite(ConstantsTest.class);
+ suite.addTestSuite(BlobTest.class);
+ suite.addTestSuite(StmtTest.class);
+ //$JUnit-END$
+ return suite;
+ }
+
+}
diff --git a/sql/src/test/java/tests/SQLite/BlobTest.java b/sql/src/test/java/tests/SQLite/BlobTest.java
new file mode 100644
index 0000000..25c1274
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/BlobTest.java
@@ -0,0 +1,223 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.Blob;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+
+import junit.framework.TestCase;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+@TestTargetClass(Blob.class)
+public class BlobTest extends TestCase {
+
+ private static Blob testBlob = null;
+
+ private byte[] blobInput= null;
+
+ private static InputStream file = null;
+
+
+ public BlobTest(String name) {
+ super(name);
+ }
+
+ protected void setUp() throws java.lang.Exception {
+ super.setUp();
+ testBlob = new Blob();
+
+ // can not fill Blob with data at this point...
+ /*
+ File resources = Support_Resources.createTempFolder();
+ BufferedReader r = null;
+ try {
+ Class c = Class.forName(this.getClass().getName());
+ assertNotNull(c);
+ file = Class.forName(this.getClass().getName())
+ .getResourceAsStream("/blob.c");
+ r = new BufferedReader(new InputStreamReader(file));
+ } catch (NullPointerException e) {
+ fail("Should not throw NullPointerException reading file"
+ + e.getMessage());
+ }
+ OutputStream out = testBlob.getOutputStream();
+ String s = null;
+ while ((s = r.readLine()) != null) {
+ out.write(r.readLine().getBytes());
+ }
+ out.flush();
+ out.close();
+ testBlob.close();
+ */
+ }
+
+ protected void tearDown() throws java.lang.Exception {
+ super.tearDown();
+ testBlob.close();
+ }
+ /**
+ * @tests Blob#Blob()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "constructor test",
+ method = "Blob",
+ args = {}
+ )
+ public void _testBlob() {
+ Blob b = new Blob();
+ assertNotNull(b);
+ //assertEquals(0, b.size);
+ }
+
+ /**
+ * @tests Blob#finalize()
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "finalize",
+ args = {}
+ )
+ public void _testFinalize() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests Blob.getInputStream()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "getInputStream",
+ args = {}
+ )
+ public void testGetInputStream() {
+ InputStream in = testBlob.getInputStream();
+ assertNotNull(in);
+ try {
+ in.read();
+ fail("Read operation unsupported");
+ } catch (Throwable e) {
+ //ok
+ }
+
+ /*
+ byte[] defaultByteArray = null;
+ BufferedReader actual = new BufferedReader(new InputStreamReader(
+ testBlob.getInputStream()));
+ byte[] b1;
+ byte[] b2;
+ try {
+ BufferedReader shouldBe = new BufferedReader(new InputStreamReader(
+ this.file));
+ while (((b1 = actual.readLine().getBytes()) != null)
+ && ((b2 = shouldBe.readLine().getBytes()) != null)) {
+ assertEquals(b2, b1);
+ }
+ assertEquals("both finished", shouldBe.readLine(), actual
+ .readLine());
+ } catch (IOException e) {
+ fail("Error in test setup: " + e.toString());
+ e.printStackTrace();
+ }
+ */
+ }
+
+ /**
+ * @tests Blob#getOutputStream()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "getOutputStream",
+ args = {}
+ )
+ public void testGetOutputStream() {
+ OutputStream out = testBlob.getOutputStream();
+ assertNotNull(out);
+ try {
+ out.write(null);
+ fail("Write operation unsupported");
+ } catch (Throwable e) {
+ assertEquals("Write operation unsupported", e.getMessage());
+ }
+ }
+
+ /**
+ * @tests Blob#close()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "close",
+ args = {}
+ )
+ public void _testClose() {
+ try {
+ testBlob.close();
+ testBlob.close();
+ testBlob.getInputStream();
+ //assertEquals(0, testBlob.size);
+ } catch (Throwable e) {
+ fail("Tests failed");
+ }
+ }
+
+ // these tests show that read and write are unsupported -> blob is unsupported
+// /**
+// * @tests Blob#write(byte[], int, int, int)
+// */
+// @TestTargetNew(
+// level = TestLevel.COMPLETE,
+// notes = "method test",
+// method = "write",
+// args = {byte[].class, int.class, int.class, int.class}
+// )
+// public void testWrite() {
+// try {
+// testBlob.write(null, 0, 0, 0);
+// fail("Write operation unsupported");
+// } catch (Throwable e) {
+// //ok
+// }
+// }
+//
+// /**
+// * @tests Blob#read()
+// */
+// @TestTargetNew(
+// level = TestLevel.COMPLETE,
+// notes = "method test",
+// method = "read",
+// args = {}
+// )
+// public void testRead() {
+// Blob b = new Blob();
+// try {
+// testBlob.read(null, 0, 0, 0);
+// fail("Read operation unsupported");
+// } catch (Throwable e) {
+// //ok
+// }
+// }
+
+}
diff --git a/sql/src/test/java/tests/SQLite/ConstantsTest.java b/sql/src/test/java/tests/SQLite/ConstantsTest.java
new file mode 100644
index 0000000..2a4961f
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/ConstantsTest.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.Constants;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargetClass;
+
+import junit.framework.TestCase;
+
+@TestTargetClass(Constants.class)
+public class ConstantsTest extends TestCase {
+
+ /**
+ * @tests Constants#Constants()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "constructor test",
+ method = "Constants",
+ args = {}
+ )
+ public void testConstants() {
+ Constants c = new Constants();
+
+ assertNotNull(c);
+ assertEquals(c.SQLITE_OK, 0);
+ assertEquals(c.SQLITE_ERROR, 1);
+ assertEquals(c.SQLITE_INTERNAL, 2);
+ assertEquals(c.SQLITE_PERM, 3);
+ assertEquals(c.SQLITE_ABORT, 4);
+ assertEquals(c.SQLITE_BUSY, 5);
+ assertEquals(c.SQLITE_LOCKED, 6);
+ assertEquals(c.SQLITE_NOMEM, 7);
+ assertEquals(c.SQLITE_READONLY, 8);
+ assertEquals(c.SQLITE_INTERRUPT, 9);
+ assertEquals(c.SQLITE_IOERR, 10);
+ assertEquals(c.SQLITE_CORRUPT, 11);
+ assertEquals(c.SQLITE_NOTFOUND, 12);
+ assertEquals(c.SQLITE_FULL, 13);
+ assertEquals(c.SQLITE_CANTOPEN, 14);
+ assertEquals(c.SQLITE_PROTOCOL, 15);
+ assertEquals(c.SQLITE_EMPTY, 16);
+ assertEquals(c.SQLITE_SCHEMA, 17);
+ assertEquals(c.SQLITE_TOOBIG, 18);
+ assertEquals(c.SQLITE_CONSTRAINT, 19);
+ assertEquals(c.SQLITE_MISMATCH, 20);
+ assertEquals(c.SQLITE_MISUSE, 21);
+ assertEquals(c.SQLITE_NOLFS, 22);
+ assertEquals(c.SQLITE_AUTH, 23);
+ assertEquals(c.SQLITE_FORMAT, 24);
+ assertEquals(c.SQLITE_RANGE, 25);
+ assertEquals(c.SQLITE_NOTADB, 26);
+ assertEquals(c.SQLITE_ROW, 100);
+ assertEquals(c.SQLITE_DONE, 101);
+ assertEquals(c.SQLITE_INTEGER, 1);
+ assertEquals(c.SQLITE_FLOAT, 2);
+ assertEquals(c.SQLITE_BLOB, 4);
+ assertEquals(c.SQLITE_NULL, 5);
+ assertEquals(c.SQLITE3_TEXT, 3);
+ assertEquals(c.SQLITE_NUMERIC, -1);
+ assertEquals(c.SQLITE_TEXT, 3);
+ assertEquals(c.SQLITE2_TEXT, -2);
+ assertEquals(c.SQLITE_ARGS, -3);
+ assertEquals(c.SQLITE_COPY, 0);
+ assertEquals(c.SQLITE_CREATE_INDEX, 1);
+ assertEquals(c.SQLITE_CREATE_TABLE, 2);
+ assertEquals(c.SQLITE_CREATE_TEMP_INDEX, 3);
+ assertEquals(c.SQLITE_CREATE_TEMP_TABLE, 4);
+ assertEquals(c.SQLITE_CREATE_TEMP_TRIGGER, 5);
+ assertEquals(c.SQLITE_CREATE_TEMP_VIEW, 6);
+ assertEquals(c.SQLITE_CREATE_TRIGGER, 7);
+ assertEquals(c.SQLITE_CREATE_VIEW, 8);
+ assertEquals(c.SQLITE_DELETE, 9);
+ assertEquals(c.SQLITE_DROP_INDEX, 10);
+ assertEquals(c.SQLITE_DROP_TABLE, 11);
+ assertEquals(c.SQLITE_DROP_TEMP_INDEX, 12);
+ assertEquals(c.SQLITE_DROP_TEMP_TABLE, 13);
+ assertEquals(c.SQLITE_DROP_TEMP_TRIGGER, 14);
+ assertEquals(c.SQLITE_DROP_TEMP_VIEW, 15);
+ assertEquals(c.SQLITE_DROP_TRIGGER, 16);
+ assertEquals(c.SQLITE_DROP_VIEW, 17);
+ assertEquals(c.SQLITE_INSERT, 18);
+ assertEquals(c.SQLITE_PRAGMA, 19);
+ assertEquals(c.SQLITE_READ, 20);
+ assertEquals(c.SQLITE_SELECT, 21);
+ assertEquals(c.SQLITE_TRANSACTION, 22);
+ assertEquals(c.SQLITE_UPDATE, 23);
+ assertEquals(c.SQLITE_ATTACH, 24);
+ assertEquals(c.SQLITE_DETACH, 25);
+ assertEquals(c.SQLITE_DENY, 1);
+ assertEquals(c.SQLITE_IGNORE, 2);
+ }
+}
diff --git a/sql/src/test/java/tests/SQLite/DatabaseTest.java b/sql/src/test/java/tests/SQLite/DatabaseTest.java
new file mode 100644
index 0000000..6cb2b4e
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/DatabaseTest.java
@@ -0,0 +1,2036 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+import tests.support.DatabaseCreator;
+import tests.support.MockFunction;
+import tests.support.ThreadPool;
+import tests.support.resource.Support_Resources;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import SQLite.Authorizer;
+import SQLite.Blob;
+import SQLite.BusyHandler;
+import SQLite.Callback;
+import SQLite.Constants;
+import SQLite.Database;
+import SQLite.Exception;
+import SQLite.Function;
+import SQLite.FunctionContext;
+import SQLite.ProgressHandler;
+import SQLite.Stmt;
+import SQLite.TableResult;
+import SQLite.Trace;
+import SQLite.Vm;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@TestTargetClass(Database.class)
+public class DatabaseTest extends SQLiteTest {
+
+ /**
+ * The SQLite db file.
+ */
+// protected final File dbFile = new File("sqliteTest.db");
+//
+// private final String connectionURL = "jdbc:sqlite:/" + dbFile.getName();
+//
+// private final String classname = "SQLite.JDBCDriver";
+//
+// private static Connection conn = null;
+
+ private static ErrorTracker tracker = null;
+
+ private Statement statement;
+
+ private Database db = null;
+
+ private static final int numThreads = 10;
+
+ private static final int numOfRecords = 30;
+
+ protected void setUp() throws java.lang.Exception {
+ try {
+ super.setUp();
+// Class.forName(classname).newInstance();
+// conn = DriverManager.getConnection(connectionURL);
+// tracker = new ErrorTracker();
+//
+// statement = conn.createStatement();
+
+ //Cleanup tables if necessary
+ DatabaseMetaData meta = conn.getMetaData();
+ ResultSet userTab = meta.getTables(null, null, null, null);
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ this.statement.execute("drop table "+tableName);
+ }
+
+
+ // Create default test table
+ statement = conn.createStatement();
+ statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
+
+ try {
+ db = new Database();
+ db.open(dbFile.getName(), 0);
+ db.busy_handler(null);
+ } catch (Exception e) {
+ System.out.println("2: Error opening File: Dir "+dbFile.getPath()+" Name: "+dbFile.getName());
+ } catch (java.lang.Exception e) {
+ System.err.println("Non SQLException "+e.getMessage());
+ }
+ } catch (Exception e) {
+ System.out.println("Database setup fails: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ }
+
+ public void tearDown() {
+ super.tearDown();
+ try {
+ db.close();
+ }catch (Exception e) {
+ if (! (e.getMessage().equals("database already closed"))) {
+ System.err.println("Error closing DB "+dbFile.getName());
+ }
+ }
+// conn.close();
+// dbFile.delete();
+ tracker.reset();
+ }
+
+ /**
+ * @tests Database#Database()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "constructor test",
+ method = "Database",
+ args = {}
+ )
+ public void testDatabase() {
+ // db closed
+ Database db2 = new Database();
+ try {
+ db.close();
+ db2 = new Database();
+ db2.open(dbFile.getName(), 0);
+ db2.close();
+ db.open(dbFile.getName(), 0);
+ } catch (Exception e) {
+ fail("Database object could not be created "+e.getMessage());
+ e.printStackTrace();
+ }
+ //db is open
+ try {
+ db2.open(dbFile.getName(), 0);
+ db2.close();
+ } catch (Exception e) {
+ fail("Second Database object could not be created "+e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests Database#finalize()
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "finalize",
+ args = {}
+ )
+ public void _testFinalize() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Database#open(String, int)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test. Test fails.",
+ method = "open",
+ args = {java.lang.String.class, int.class}
+ )
+ public void testOpen() {
+ try {
+ db.close();
+ db.open(dbFile.getName(), 0);
+ } catch (Exception e) {
+ fail("Database object could not be opened: " + e.getMessage());
+ e.printStackTrace();
+ }
+ // open second db while db1 still open
+ Database db2 = new Database();
+ try {
+ db2.open(dbFile.getName(), 0);
+ db2.open(dbFile.getName(), 0);
+ db2.close();
+ } catch (Exception e) {
+ fail("Database object could not be opened: " + e.getMessage());
+ e.printStackTrace();
+ }
+ // open non db file
+ File tempDir = Support_Resources.createTempFolder();
+ final String resourceName = "blob.c";
+ try {
+ URL file = Class.forName(this.getClass().getName())
+ .getResource("/blob.c");
+ db2.open(file.getPath(), 0);
+ fail("Should not be able to open non db file");
+ } catch (Exception e) {
+ assertEquals("unknown error in open", e.getMessage());
+ } catch (java.lang.Exception e) {
+ fail("Error in setup " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * @tests Database#open_aux_file(String)
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "not supported",
+ method = "open_aux_file",
+ args = {java.lang.String.class}
+ )
+ public void testOpen_aux_file() {
+ File temp = null;
+ try {
+ db.open_aux_file("");
+ fail("open should fail");
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+
+ /*
+ try {
+ temp = File.createTempFile("openAuxMethod", ".db");
+ db.open_aux_file("");
+ db.exec("create table AUX_TABLE", null);
+ db.close();
+ } catch (Exception e) {
+ temp.delete();
+ fail("Error handling temporary file "+e.getMessage());
+ e.printStackTrace();
+ } catch (IOException e) {
+ temp.delete();
+ fail("Could not create temporary File");
+ e.printStackTrace();
+ }
+ try {
+ db.open(dbFile.getName(),0);
+ db.exec("select * from AUX_TABLE", null);
+ fail("Statement should fail");
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ temp.delete();
+ */
+ }
+
+ /**
+ * @tests Database#close()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "close",
+ args = {}
+ )
+ public void testClose() {
+ try {
+ db.close();
+ db.get_table("test");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().equals("database already closed"));
+ try {
+ db.open(dbFile.getName(), 0);
+ } catch (Exception e1) {
+ fail("Database object could not be reopened after 'close': "
+ + e.getMessage());
+ e1.printStackTrace();
+ }
+ }
+
+ try {
+ db.close();
+ db.close();
+ } catch (Exception e) {
+ assertTrue(e.getMessage().equals("database already closed"));
+ try {
+ db.open(dbFile.getName(), 0);
+ } catch (Exception e1) {
+ fail("Database object could not be reopened after 'close': "
+ + e.getMessage());
+ e1.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * @tests Database#exec(String, Callback)
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "exec",
+ args = {java.lang.String.class, Callback.class}
+ )
+ public void testExecStringCallback() {
+ TableResult res = new TableResult();
+ try {
+ db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " VALUES(1, 10, 20)", null);
+ db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
+ db
+ .exec("delete from " + DatabaseCreator.SIMPLE_TABLE1
+ + " where 1", null);
+ } catch (Exception e) {
+ fail("Database error");
+ e.printStackTrace();
+ }
+ String row[] = (String[]) res.rows.elementAt(0);
+ assertEquals(Integer.parseInt(row[0]), 1);
+ assertEquals(Integer.parseInt(row[1]), 10);
+ assertEquals(Integer.parseInt(row[2]), 20);
+ }
+
+ /**
+ * @tests Database#exec(String, Callback, String[])
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "exec",
+ args = {java.lang.String.class, Callback.class, java.lang.String[].class}
+ )
+ public void testExecStringCallbackStringArray() {
+ TableResult res = new TableResult();
+ String args[] = new String[1];
+ args[0] = "table";
+ try {
+ db.exec("select name from sqlite_master where type = '%q';", res,
+ args);
+ String[] s = (String[]) res.rows.elementAt(0);
+ assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
+ } catch (Exception e) {
+ fail("DB Error occurred");
+ e.printStackTrace();
+ }
+
+ try {
+ db.exec("select name from sqlite_master where type = ", res, args);
+ fail("Testmethod should fail");
+ } catch (Exception e) {
+ // Ok
+ }
+ }
+
+ /**
+ * @tests {@link Database#last_insert_rowid()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "last_insert_rowid",
+ args = {}
+ )
+ public void testLast_insert_rowid() {
+ assertEquals(0, db.last_insert_rowid());
+ try {
+ db
+ .exec(
+ "create table TEST5(id integer, firstname text, lastname text);",
+ null);
+ db.exec("insert into TEST5 values (1,'James','Bond');", null);
+ db.exec("insert into TEST5 values (2,'Fiona','Apple');", null);
+ } catch (Exception e) {
+ fail("Error in test setup: " + e.getMessage());
+ e.printStackTrace();
+ }
+ assertEquals(2, db.last_insert_rowid());
+ assertEquals(db.last_insert_rowid(), db.last_insert_rowid());
+
+ try {
+ db.exec("drop table TEST5;", null);
+ } catch (Exception e) {
+ fail("Error in test setup: " + e.getMessage());
+ e.printStackTrace();
+ }
+ assertEquals(2, db.last_insert_rowid());
+ }
+
+ /**
+ * @tests {@link Database#interrupt()}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "How should this be tested?",
+ method = "interrupt",
+ args = {}
+ )
+ public void _testInterrupt() {
+ ThreadPool threadPool = new ThreadPool(numThreads);
+
+ // initialization
+ ResultSet userTabs;
+ try {
+ userTabs = conn.getMetaData().getTables(null, null, null, null);
+ while (userTabs.next()) {
+ String tableName = userTabs.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ }
+ }
+ db.exec(DatabaseCreator.CREATE_TABLE3, null);
+ db.exec(DatabaseCreator.CREATE_TABLE1, null);
+ } catch (SQLException e1) {
+ fail("Error initializing test " + e1.toString());
+ e1.printStackTrace();
+ } catch (Exception e) {
+ fail("Error initializing test " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ int id1 = numOfRecords - 3;
+ threadPool.runTask(createTask1(id1, dbFile.getName(), tracker));
+ int id2 = numOfRecords + 3;
+ threadPool.runTask(createTask2Interrupt(id2, dbFile.getName(), tracker));
+
+ threadPool.join();
+
+ List<String> errors = tracker.getErrors();
+ System.out.println("Last error: "+db.error_message());
+ if (errors.size() > 0) {
+// assertEquals(errors.get(0),
+// db.error_string(Constants.SQLITE_LOCKED));
+ for (String s: errors) {
+ System.out.println("INTERRUPT Error: "+s);
+
+ }
+ fail("Should not have any errors with interrupt");
+ } else {
+ System.out.println("INTERRUPT: No error happened");
+ }
+
+ // reset
+
+ try {
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
+ null);
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
+ null);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+
+
+ }
+
+ /**
+ * @tests {@link Database#changes()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "test fails",
+ method = "changes",
+ args = {}
+ )
+ public void _testChanges() {
+ TableResult res = new TableResult();
+ try {
+ assertTrue(db.changes() == 0);
+ db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
+ + " VALUES(2, 5, 7)", null);
+ int rows = (int) db.changes();
+ assertEquals(1,db.changes());
+ db.exec("update " + DatabaseCreator.SIMPLE_TABLE1
+ + " set speed = 7, size= 5 where id = 2", null);
+ assertEquals(1,db.changes());
+ db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res);
+ assertEquals(0,db.changes());
+ db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1
+ + " VALUES(8, 5, 7)", null);
+ db.exec("drop table "+DatabaseCreator.SIMPLE_TABLE1, null);
+ assertTrue(db.changes() > 1);
+ } catch (Exception e) {
+ fail("Could not get changes: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests {@link Database#busy_handler(BusyHandler)}
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test fails. Cannot be sure that exception is thrown wvery time.",
+ method = "busy_handler",
+ args = {BusyHandler.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test fails. Cannot be sure that exception is thrown every time.",
+ method = "busy",
+ clazz = BusyHandler.class,
+ args = {java.lang.String.class, int.class}
+ )
+ })
+ public void _testBusy_handler() {
+ TestBusyHandler bh = new TestBusyHandler();
+ db.busy_handler(bh);
+ int counter = 0;
+ ThreadPool threadPool = new ThreadPool(numThreads);
+
+ // initialization
+ ResultSet userTabs;
+ try {
+ userTabs = conn.getMetaData().getTables(null, null, null, null);
+ while (userTabs.next()) {
+ String tableName = userTabs.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ }
+ }
+ db.exec(DatabaseCreator.CREATE_TABLE3, null);
+ db.exec(DatabaseCreator.CREATE_TABLE1, null);
+ } catch (SQLException e1) {
+ fail("Error initializing test " + e1.toString());
+ e1.printStackTrace();
+ } catch (Exception e) {
+ fail("Error initializing test " + e.getMessage());
+ e.printStackTrace();
+ }
+
+
+// try {
+// DatabaseCreator.fillTestTable1(conn, numOfRecords);
+ // set to fail immediately if table is locked.
+// db.busy_handler(bh);
+// db.busy_timeout(0);
+ int id1 = numOfRecords - 3;
+ threadPool.runTask(createTask1(id1, dbFile.getName(), tracker));
+ int id2 = numOfRecords + 3;
+ threadPool.runTask(createTask2(id2, dbFile.getName(), tracker));
+ int oldID = 5;
+ int newID = 100;
+ threadPool.runTask(createTask3(oldID, dbFile.getName(), newID,
+ tracker));
+
+ threadPool.join();
+
+ List<String> errors = tracker.getErrors();
+ if (errors.size() > 0) {
+// assertEquals(errors.get(0),
+// db.error_string(Constants.SQLITE_LOCKED));
+ for (String s: errors) {
+ System.out.println("Round 2 Error: "+s);
+ }
+ } else {
+ System.out.println("BUSY: No error happened");
+ }
+
+ // reset
+
+ try{
+
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
+ null);
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
+ null);
+//
+// // increase timeout for retry
+// db.busy_timeout(1000);
+// db.busy_handler(bh);
+// tracker.reset();
+
+// threadPool = new ThreadPool(numThreads);
+//
+// threadPool.runTask(createTask1(id1, dbFile.getName(), tracker));
+// threadPool.runTask(createTask2(id2, dbFile.getName(), tracker));
+//
+// threadPool.join();
+//
+// errors = tracker.getErrors();
+// if (errors.size() > 0) {
+// // assertEquals(errors.get(0),
+// // db.error_string(Constants.SQLITE_LOCKED));
+// for (String s: errors) {
+// System.out.println("Round 2 Error"+s);
+// }
+// } else {
+// // ok
+// System.out.println("BUSY: No Error!");
+// }
+//
+//
+ } catch (Exception e) {
+ fail("Error in test setup " + e.getMessage());
+ try {
+ db.get_table("select * from " + DatabaseCreator.TEST_TABLE1,
+ null).toString();
+ } catch (Exception e1) {
+
+ e1.printStackTrace();
+ }
+ e.printStackTrace();
+// } catch (SQLException e2) {
+// System.out.println("Error in test setup "+e2.toString());
+// try {
+// db.get_table("select * from "+DatabaseCreator.TEST_TABLE1,null).
+// toString();
+// } catch (Exception e1) {
+// e2.printStackTrace();
+// }
+ }
+
+ try {
+ db.exec(DatabaseCreator.DROP_TABLE1, null);
+ db.exec(DatabaseCreator.DROP_TABLE3, null);
+ } catch (Exception e) {
+ fail("Error in test cleanup" + e.getMessage());
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#busy_timeout(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test fails. Cannot be sure that exception is thrown wvery time.",
+ method = "busy_timeout",
+ args = {int.class}
+ )
+ public void _testBusy_timeout() {
+ int counter = 0;
+ ThreadPool threadPool = new ThreadPool(numThreads);
+
+ // initialization
+ ResultSet userTabs;
+ try {
+ userTabs = conn.getMetaData().getTables(null, null, null, null);
+ while (userTabs.next()) {
+ String tableName = userTabs.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ }
+ }
+ db.exec(DatabaseCreator.CREATE_TABLE3, null);
+ db.exec(DatabaseCreator.CREATE_TABLE1, null);
+ } catch (SQLException e1) {
+ fail("Error initializing test " + e1.toString());
+ e1.printStackTrace();
+ } catch (Exception e) {
+ fail("Error initializing test " + e.getMessage());
+ e.printStackTrace();
+ }
+
+
+ try {
+// DatabaseCreator.fillTestTable1(conn, numOfRecords);
+ // set to fail immediately if table is locked.
+ db.busy_handler(null);
+ db.busy_timeout(0);
+ int id1 = numOfRecords - 3;
+ threadPool.runTask(createTask1(id1, dbFile.getName(), tracker));
+ int id2 = numOfRecords + 3;
+ threadPool.runTask(createTask2(id2, dbFile.getName(), tracker));
+ int oldID = 5;
+ int newID = 100;
+ threadPool.runTask(createTask3(oldID, dbFile.getName(), newID,
+ tracker));
+
+ threadPool.join();
+
+ List<String> errors = tracker.getErrors();
+ if (errors.size() > 0) {
+// assertEquals(errors.get(0),
+// db.error_string(Constants.SQLITE_LOCKED));
+ assertEquals(errors.get(0), "database is locked");
+ } else {
+ fail("Error in test setup");
+ }
+
+ // reset
+
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1",
+ null);
+ db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1",
+ null);
+
+ // increase timeout for retry
+ db.busy_timeout(10000);
+ db.busy_handler(null);
+ tracker.reset();
+ threadPool = new ThreadPool(numThreads);
+
+ threadPool.runTask(createTask1(id1, dbFile.getName(), tracker));
+ threadPool.runTask(createTask2(id2, dbFile.getName(), tracker));
+
+ threadPool.join();
+
+ errors = tracker.getErrors();
+ if (errors.size() > 0) {
+ // assertEquals(errors.get(0),
+ // db.error_string(Constants.SQLITE_LOCKED));
+ fail("busy timeout should prevent from lock exception!");
+ for (String s: errors) {
+ System.out.println("Round 2 Error"+s);
+ }
+ } else {
+ // ok
+ System.out.println("No Error!");
+ }
+
+
+ } catch (Exception e) {
+ fail("Error in test setup " + e.getMessage());
+ try {
+ db.get_table("select * from " + DatabaseCreator.TEST_TABLE1,
+ null).toString();
+ } catch (Exception e1) {
+
+ e1.printStackTrace();
+ }
+ e.printStackTrace();
+// } catch (SQLException e2) {
+// System.out.println("Error in test setup "+e2.toString());
+// try {
+// db.get_table("select * from "+DatabaseCreator.TEST_TABLE1,null).
+// toString();
+// } catch (Exception e1) {
+// e2.printStackTrace();
+// }
+ }
+
+ try {
+ db.exec(DatabaseCreator.DROP_TABLE1, null);
+ db.exec(DatabaseCreator.DROP_TABLE3, null);
+ } catch (Exception e) {
+ fail("Error in test cleanup" + e.getMessage());
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#get_table(String)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "get_table",
+ args = {java.lang.String.class}
+ )
+ public void testGet_tableString() {
+ TableResult emptyTable = new TableResult();
+ try {
+ //select from empty table
+ TableResult res = db.get_table("select * from "
+ + DatabaseCreator.SIMPLE_TABLE1);
+ assertEquals(res.toString(), emptyTable.toString());
+ //fill table-> t
+// DatabaseCreator.fillSimpleTable1(conn);
+// res = db.get_table("select * from "
+// + DatabaseCreator.SIMPLE_TABLE1);
+// assertFalse(emptyTable.toString().equals(res.toString()));
+
+ try {
+ db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " VALUES(1, 10, 20)", null);
+ res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ db
+ .exec("delete from " + DatabaseCreator.SIMPLE_TABLE1
+ + " where 1", null);
+ } catch (Exception e) {
+ fail("Database error");
+ e.printStackTrace();
+ }
+ String row[] = (String[]) res.rows.elementAt(0);
+ assertEquals(Integer.parseInt(row[0]), 1);
+ assertEquals(Integer.parseInt(row[1]), 10);
+ assertEquals(Integer.parseInt(row[2]), 20);
+ } catch (Exception e) {
+ fail("Error getting table " + e.getMessage());
+ e.printStackTrace();
+// } catch (SQLException e) {
+// fail("Error initialising table " + e.getMessage());
+// e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests {@link Database#get_table(String, String[])}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "get_table",
+ args = {java.lang.String.class, java.lang.String[].class}
+ )
+ public void testGet_tableStringStringArray() {
+ String args[] = new String[1];
+ args[0] = "table";
+ String argsFail[] = new String[1];
+ try {
+ TableResult res = db.get_table(
+ "select name from sqlite_master where type = ", argsFail);
+ fail("Testmethod should fail");
+ } catch (Exception e) {
+ try {
+ TableResult res = db.get_table(
+ "select name from sqlite_master where type = '%q'",
+ args);
+ String[] s = (String[]) res.rows.elementAt(0);
+ assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
+ } catch (Exception e2) {
+ fail("Testmethod failed: " + e2.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#get_table(String, String[], TableResult)}
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "get_table",
+ args = {java.lang.String.class, java.lang.String[].class, TableResult.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "toString",
+ clazz = TableResult.class,
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "types",
+ clazz = TableResult.class,
+ args = {String[].class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "TableResult",
+ clazz = TableResult.class,
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.NOT_NECESSARY,
+ notes = "method test",
+ method = "columns",
+ clazz = TableResult.class,
+ args = {String[].class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.NOT_NECESSARY,
+ notes = "method test",
+ method = "newrow",
+ clazz = TableResult.class,
+ args = {String[].class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.NOT_NECESSARY,
+ notes = "method test",
+ method = "clear",
+ clazz = TableResult.class,
+ args = {}
+ )
+
+ })
+ public void testGet_tableStringStringArrayTableResult() {
+ String args[] = new String[1];
+ String argsFail[] = new String[1];
+ TableResult res = new TableResult();
+ TableResult defaultTableRes = new TableResult();
+ args[0] = "table";
+
+ try {
+ db.get_table("select name from sqlite_master where type = '%q'",
+ argsFail, res);
+ assertEquals(defaultTableRes.toString(), res.toString());
+ } catch (Exception e) {
+ try {
+ db.get_table(
+ "select name from sqlite_master where type = '%q'",
+ args, res);
+ String[] s = (String[]) res.rows.elementAt(0);
+ assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1);
+ String[] types = res.types;
+ System.out
+ .println("DatabaseTest.testGet_tableStringStringArrayTableResult() "+types.toString());
+ } catch (Exception e2) {
+ fail("Testmethod failed: " + e2.getMessage());
+ e.printStackTrace();
+ }
+ }
+ }
+
+
+ /**
+ * @tests {@link Database#complete(String)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "complete",
+ args = {java.lang.String.class}
+ )
+ public void testComplete() {
+ assertFalse(db.complete("create"));
+ assertTrue(db.complete("create table TEST (res double);"));
+ }
+
+ /**
+ * @tests {@link Database#version()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "version",
+ args = {}
+ )
+ public void testVersion() {
+ String version = db.version();
+ if (version != null) {
+ assertTrue(Integer.parseInt(db.version().substring(0,1)) > 0);
+ assertEquals(db.version(), db.version());
+ } else {
+ fail("DB version info missing");
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#dbversion()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "dbversion",
+ args = {}
+ )
+ public void testDbversion() {
+ try {
+ String verNo = db.dbversion();
+ db.close();
+ assertEquals(db.dbversion(),"unknown");
+ db.open(dbFile.getName(), 0);
+ assertEquals(verNo,db.dbversion());
+ } catch (Exception e) {
+ try {
+ db.open(dbFile.getName(), 0);
+ } catch (Exception e1) {
+ fail("error in db setup "+e.getMessage());
+ e.printStackTrace();
+ }
+ fail("error in db setup "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#create_function(String, int, Function)}
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "create_function",
+ args = {java.lang.String.class, int.class, Function.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "create_function",
+ args = {java.lang.String.class, int.class, Function.class}
+ )
+ })
+ public void testCreate_function() {
+ try {
+ double input = 1.0;
+ db.exec("create table TEST (res double)", null);
+ db.exec("insert into TEST values (" + Double.toString(input) + ")",
+ null);
+ TableResult res = new TableResult();
+ Function sinFunc = (Function) new SinFunc();
+ db.create_function("sin", 1, sinFunc);
+ db.exec("select sin(res) from TEST WHERE res = "
+ + Double.toString(input), res);
+ String row[] = (String[]) res.rows.elementAt(0);
+ String val = row[0];
+ double sinusVal = Double.parseDouble(val);
+ double funcVal = Math.sin(input);
+
+ assertTrue(Math.round(funcVal) == Math.round(sinusVal));
+ } catch (Exception e) {
+ fail("Error happened creating function:" + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests {@link Database#create_aggregate(String, int, Function)}
+ */
+ @TestTargets({
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "create_aggregate",
+ args = {java.lang.String.class, int.class, Function.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "trace",
+ clazz = Trace.class,
+ args = {String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "step",
+ clazz = Function.class,
+ args = {FunctionContext.class, String[].class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "last_step",
+ clazz = Function.class,
+ args = {FunctionContext.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "function",
+ clazz = Function.class,
+ args = {FunctionContext.class, String[].class}
+ )
+ })
+ public void testCreate_aggregate() {
+ TestTrace t = new TestTrace();
+ MockFunction aggFunction = new MockFunction();
+ try {
+ db
+ .exec(
+ "create table TEST(id integer, firstname text, lastname text)",
+ null);
+ db.exec("insert into TEST values(3, 'James', 'Bond'); ", null);
+ db.exec("insert into TEST values(4, 'Fiona', 'Apple'); ", null);
+ db.trace((Trace) t);
+ db.create_aggregate("myaggfunc", 1, aggFunction);
+ db.function_type("myaggfunc", Constants.SQLITE_TEXT);
+ db.exec("PRAGMA show_datatypes = on", null);
+ db.exec("select myaggfunc(TEST.firstname) from TEST", t);
+ assertEquals("James Fiona ",aggFunction.getAggValue());
+ db.exec("drop table TEST", null);
+ } catch (Exception e) {
+ System.out.println(t.getTrace());
+ fail("Error in test setup: " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ db.create_aggregate("myaggfunc", 0, null);
+ } catch (Throwable e) {
+ assertEquals("null SQLite.Function not allowed",e.getMessage());
+ }
+
+ try {
+ db.create_aggregate("myaggfunc", 0, aggFunction);
+ } catch (Throwable e) {
+ assertEquals("wrong number of arguments to function myaggfunc()",e.getMessage());
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#function_type(String, int)}
+ * This method does not make sense
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test fails.",
+ method = "function_type",
+ args = {java.lang.String.class, int.class}
+ )
+ public void _testFunction_type() {
+
+ double input = 1.0;
+ TableResult res = new TableResult();
+ Function sinFunc = (Function) new SinFunc();
+
+ try {
+ db.exec("PRAGMA show_datatypes = on", null);
+ db.exec("create table TEST (res double)", null);
+ db.exec("insert into TEST values (" + Double.toString(input) + ")",
+ null);
+
+ db.create_function("sin", 1, sinFunc);
+ db.function_type("sin", Constants.SQLITE2_TEXT);
+ res = db.get_table("select sin(res) from TEST WHERE res = "
+ + Double.toString(input));
+ for(String s: res.types) {
+ System.out.println("DatabaseTest.testFunction_type()"+s);
+ }
+ db.function_type("sin", Constants.SQLITE2_TEXT);
+ Stmt s = db.prepare("select sin(res) from TEST WHERE res = "
+ + Double.toString(input));
+ s.step();
+
+// fail("Return type is not Text");
+
+
+ // System.out.println(res.toString());
+ // String row[] = (String[]) res.rows.elementAt(0);
+ // String val = row[0];
+ // System.out.println(db.get_table("select sin(1) from TEST"));
+ // } catch (SQLException e) {
+ // fail("Error happened creating function:"
+ // + e.getMessage());
+ // e.printStackTrace();
+ } catch (Exception e) {
+ fail("Error happened creating function:" + e.getMessage());
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#last_error()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "last_error",
+ args = {}
+ )
+ public void testLast_error() {
+ assertEquals(db.last_error(), Constants.SQLITE_OK);
+ try {
+ db.exec("create table TEST (res double)",null);
+ db.exec("create table TEST (res double)",null);
+ fail("Error should have happened");
+ } catch (Exception e) {
+ assertEquals(db.last_error(),db.last_error());
+ assertEquals(db.last_error(),Constants.SQLITE_ERROR);
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#set_last_error(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "set_last_error",
+ args = {int.class}
+ )
+ public void _testSet_last_error() {
+ assertEquals(db.last_error(), Constants.SQLITE_OK);
+ //db.set_last_error(Constants.SQLITE_MISMATCH);
+ //assertEquals(db.last_error(),Constants.SQLITE_MISMATCH);
+ //db.set_last_error(Constants.SQLITE3_TEXT);
+ //assertEquals(db.last_error(),Constants.SQLITE3_TEXT);
+ }
+
+ /**
+ * @tests {@link Database#error_message()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "error_message",
+ args = {}
+ )
+ public void testError_message() {
+ String statement = "create table TEST (res double)";
+ try {
+ db.exec(statement,null);
+ db.exec(statement,null);
+ fail("DB Error expected");
+ } catch (Exception e) {
+ String dbError = db.error_message();
+ assertTrue(e.getMessage().equals(dbError));
+
+ }
+ }
+
+ /**
+ * @tests {@link Database#error_string(int)}
+ */
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "not supported",
+ method = "error_string",
+ args = {int.class}
+ )
+ public void testError_string() {
+ TestTrace t = new TestTrace();
+ assertEquals(db.last_error(), Constants.SQLITE_OK);
+ String errorString = db.error_string(Constants.SQLITE_ERROR);
+ try {
+ db.trace((Trace) t);
+ db.exec("create table TEST (res double)", t);
+ db.exec("create table TEST (res double)", t);
+ } catch (Exception e) {
+ assertEquals(db.last_error(), Constants.SQLITE_ERROR);
+ if (db.is3()) {
+ assertEquals("Unsupported Method (sqlite 3): error_string", db
+ .error_string(db.last_error()), errorString);
+ }
+ }
+ }
+
+ /**
+ * @tests {@link Database#set_encoding(String)}
+ * Method unsupported? -> tests fail
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test fails.",
+ method = "set_encoding",
+ args = {java.lang.String.class}
+ )
+ public void _testSet_encoding() {
+ String input = "\u00bfMa\u00f1ana\u003f"; // ?Manana?
+ TableResult res = new TableResult();
+ String refOutput = null;
+ Stmt stat = null;
+
+ // DB setup
+ try {
+ db.exec("create table encodingTest (encoded text DEFAULT NULL);",
+ null);
+ stat = db
+ .prepare("insert into encodingTest(encoded) values(:one);");
+ stat.bind(1, input);
+ stat.step();
+ // stat.close();
+ db.exec("select * from encodingTest;", res);
+ String[] encInput = (String[]) res.rows.elementAt(0);
+ String output = encInput[0];
+ assertEquals(input, output);
+ // db.exec("delete from encodingTest where 1", null);
+ } catch (Exception e1) {
+ fail("Error in test setup: " + e1.getMessage());
+ e1.printStackTrace();
+ }
+
+ // Default tests
+ try {
+ db.set_encoding("");
+ fail("invalid input should fail");
+ } catch (Exception e) {
+ //ok
+ }
+
+ // Default tests
+ try {
+ db.set_encoding("UTF-16");
+ db.exec("select * from encodingTest;", res);
+ String[] encOutput1 = (String[]) res.rows.elementAt(0);
+
+ db.set_encoding("US-ASCII");
+ db.exec("select * from encodingTest;", res);
+ String[] encOutput2 = (String[]) res.rows.elementAt(0);
+
+ assertFalse(encOutput1[0].equals(encOutput2[0]));
+ } catch (Exception e) {
+ fail("Error setting the encoding." + e.getMessage());
+ e.printStackTrace();
+ }
+
+ // tests for different encoding schemes
+ // String[] charsetNames = { "ISO-8859-1","US-ASCII", "UTF-8",
+ // "UTF-16","UTF-16BE", "UTF-16LE"
+ String[] charsetNames = {"UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE"};
+ for (int i = 0; i < charsetNames.length; i++) {
+ try {
+ byte[] encInput = input.getBytes(charsetNames[i]);
+ db.set_encoding(charsetNames[i]);
+ // stat.reset();
+ // stat.bind(1, encInput);
+ // stat.step();
+ db.exec("select * from encodingTest;", res);
+ String[] encOutput = (String[]) res.rows.elementAt(0);
+ String inputAsString = new String(encInput);
+ System.out.println(charsetNames[i] + " input: " + inputAsString
+ + " output: " + encOutput[0]);
+ assertEquals(inputAsString, encOutput[0]);
+ } catch (Exception e4) {
+ fail("Error setting the encoding." + e4.getMessage());
+ e4.printStackTrace();
+ } catch (UnsupportedEncodingException e2) {
+ fail(e2.getMessage());
+ e2.printStackTrace();
+ }
+ }
+ // DB teardown
+ try {
+ stat.close();
+ db.exec("delete from encodingTest where 1", null);
+ // reset encoding
+ } catch (Exception e3) {
+ fail("Error in teardown of encoding environment");
+ e3.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Test fails -> implemented correctly?
+ * @tests {@link Database#set_authorizer(Authorizer)}
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test fails.",
+ method = "set_authorizer",
+ args = {Authorizer.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test fails.",
+ method = "authorize",
+ clazz = Authorizer.class,
+ args = {int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
+ )
+ })
+ public void _testSet_authorizer() {
+
+ TableResult resPriv = null;
+ TableResult resPub = null;
+ TableResult emptyTable = new TableResult();
+ String insertPublic = "insert into public_table values(1,2)";
+ String insertPrivate = "insert into private_table values(1,2)";
+ try {
+ // prepare, authorizer is not activated yet
+ db.exec("create table public_table(c1 integer, c2 integer);", null);
+ db.exec("create table private_table(c1 integer, c2 integer);", null);
+ // inserts
+ db.exec(insertPublic, null);
+ db.exec(insertPrivate, null);
+ // selects
+ resPriv = db.get_table("select * from private_table");
+ resPub = db.get_table("select * from public_table");
+
+// db.exec("delete from public_table where 1", null);
+// TableResult emptyPubTable = db.exec("select * from public");
+
+ // set Authorizer (positive case)
+ AuthorizerCallback cb = new AuthorizerCallback();
+ db.set_authorizer(cb);
+ System.out.println("Auth set.");
+ //select
+
+ db.exec("select * from private_table", cb);
+ fail("authorization failed");
+
+// TableResult res = db.get_table("select * from private_table");
+// assertEquals(emptyTable.toString(),res.toString());
+// assertFalse(emptyTable.equals(resPriv));
+//
+// res = db.get_table("select * from public_table");
+// assertEquals(resPub,res);
+
+ } catch (Exception e) {
+ fail("Error testing authorization: "+e.getMessage());
+ }
+
+ // Try insert
+ try {
+ db.exec(insertPublic, null);
+ fail("authorization failed");
+ } catch (Exception e) {
+ try {
+ db.exec(insertPrivate, null);
+ fail("authorization failed");
+ } catch (Exception e1) {
+ // ok
+ }
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#trace(Trace)}
+ */
+
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "trace",
+ args = {Trace.class}
+ )
+ public void testTrace() {
+ String stmt = "create table TEST (res double);";
+ TestTrace t = new TestTrace();
+ assertEquals(db.last_error(),Constants.SQLITE_OK);
+ try {
+ db.trace((Trace) t);
+ db.exec(stmt,t);
+ assertEquals(t.getTrace(),stmt);
+ } catch (Exception e) {
+ fail("Error testing traces: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ db.close();
+ db.exec(stmt,t);
+ fail("Exception Expected");
+ } catch (Exception e) {
+ //ok
+ }
+
+
+ }
+
+ /**
+ * @tests {@link Database#compile(String)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "compile",
+ args = {java.lang.String.class}
+ )
+ public void testCompileString() {
+ try {
+ db.compile("select name from sqlite_master;");
+ } catch (Exception e) {
+ fail("Error compiling sql statement " + e.getMessage());
+ e.printStackTrace();
+ }
+ try {
+ db.compile("test");
+ fail("Compiling of inaccurate statement does not fail.");
+ } catch (Exception e) {
+
+ }
+ }
+
+ /**
+ * @tests {@link Database#compile(String, String[])}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "compile",
+ args = {java.lang.String.class, java.lang.String[].class}
+ )
+ public void testCompileStringStringArray() {
+ String args[] = new String[1];
+ args[0] = "table";
+ try {
+ db.compile("select name from sqlite_master where type = '%q';",args);
+ } catch (Exception e) {
+ fail("Error compiling sql statement " + e.getMessage());
+ e.printStackTrace();
+ }
+ try {
+ db.compile("test",null);
+ fail("Compiling of inaccurate statement does not fail.");
+ } catch (Exception e) {
+
+ }
+ }
+
+ /**
+ * @tests {@link Database#prepare(String)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "prepare",
+ args = {java.lang.String.class}
+ )
+ public void testPrepare() {
+ Stmt st = null;
+ Stmt st2 = null;
+ // test empty statement
+ try {
+ st = db.prepare("");
+ assertEquals(0, st.bind_parameter_count());
+ st.step();
+ fail("stmt should not be prepared");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ // test statement with unbound arguments
+ try {
+ st2 = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(3, st2.bind_parameter_count());
+ assertEquals(3, st2.bind_parameter_index(":three"));
+ assertEquals(":two", st2.bind_parameter_name(2));
+ } catch (Exception e) {
+ fail("error in prepare method: " + e.getMessage());
+ e.printStackTrace();
+ } finally {
+ try {
+ st2.close();
+ } catch (Exception e) {
+ fail("error in prepare method cleanup: " + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ try {
+ db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values(:one,:two,:three,:four);");
+ } catch (Exception e) {
+ assertEquals("table " + DatabaseCreator.SIMPLE_TABLE1
+ + " has 3 columns but 4 values were supplied", e
+ .getMessage());
+ }
+
+ try {
+ db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values(5, '10, 20);");
+ } catch (Exception e) {
+ assertEquals("unrecognized token: \"'10, 20);\"", e.getMessage());
+ }
+
+ try {
+ db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values(5, 10 20);");
+ } catch (Exception e) {
+ assertEquals("near \"20\": syntax error", e.getMessage());
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#open_blob(String, String, String, long, boolean)}
+ * unsupported
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "",
+ method = "open_blob",
+ args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, long.class, boolean.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "",
+ method = "Exception",
+ clazz = Exception.class,
+ args = {java.lang.String.class}
+ )
+ })
+ public void _testOpen_blob() {
+ Stmt statement2;
+ Blob blobInput = new Blob();
+
+
+ // Create test input Blob
+ //File resources = Support_Resources.createTempFolder();
+ InputStream inStream = null;
+ byte[] in = new byte[20];
+ try {
+ db.exec("create table TEST (res blob)",null);
+ inStream = Class.forName(this.getClass().getName()).getResourceAsStream("/blob.c");
+ assertNotNull(inStream);
+ inStream.read(in);
+ inStream.close();
+ } catch (NullPointerException e) {
+ fail("Error reading file"+e.getMessage());
+ } catch (java.lang.Exception e2) {
+ fail("Error reading from input "+e2.getMessage());
+ }
+
+ // insert byte array in db
+ try {
+ statement2 = db.prepare("insert into TEST(res) values (?)");
+ statement2.bind(1,in);
+ statement2.step();
+ statement2.close();
+ } catch (Exception e) {
+ fail("Error happened inserting blob"+e.getMessage());
+ e.printStackTrace();
+ }
+ byte[] output = new byte[20];
+ Blob blob;
+ try {
+ blob = db.open_blob(dbFile.getName(), "TEST", "res", 1, true);
+ if (blob == null) {
+ fail("Blob could not be retrieved");
+ }
+ OutputStream os = blob.getOutputStream();
+ os.write(output);
+ os.close();
+ blob.close();
+ //read from blob and compare values (positive case)
+ InputStream is = blob.getInputStream();
+ assertEquals(in,is);
+ //read from blob and compare values (negative case)
+ db.exec("insert into TEST values(zeroblob(128))", null);
+ Blob blob2 = db.open_blob(dbFile.getName(), "TEST", "res", 2, true);
+ /*if (blob2 != null) {
+ assertEquals(0, blob2.size);
+ }*/
+ } catch (Exception e) {
+ assertEquals("Method opend_blob unsupported (sqlite 3)","unsupported", e.getMessage());
+ } catch (IOException e2) {
+ fail("error in setup: "+e2.getMessage());
+ e2.printStackTrace();
+ }
+
+ }
+
+ /**
+ * @tests {@link Database#is3()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "is3",
+ args = {}
+ )
+ public void testIs3() {
+ int ver = Integer.parseInt(db.version().substring(0,1));
+ if (db.is3()) {
+ assertTrue( ver == 3);
+ } else {
+ assertTrue(ver != 3);
+ }
+ }
+
+ /**
+ * @tests {@link Database#progress_handler(int, ProgressHandler)}
+ */
+ @TestTargets ({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "progress_handler",
+ args = {int.class, ProgressHandler.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "progress",
+ clazz = ProgressHandler.class,
+ args = {}
+ )
+ })
+ public void testProgress_handler() {
+ int inputVal = 3;
+ TestProgressHandler prog = new TestProgressHandler();
+ try {
+ db.exec("create table TEST5(id integer, firstname text, lastname text)",null);
+ Vm vm = db.compile("select * from TEST5; "
+ + "insert into TEST5 values(3, 'James', 'Bond'); "
+ + "delete from TEST5 where id = 3; "
+ + "select * from TEST5");
+ int stmt = 0;
+ do {
+ ++stmt;
+ if (stmt > inputVal) {
+ db.progress_handler(inputVal, prog);
+ } else {
+ assertEquals(0, prog.getCounts());
+ }
+ while (vm.step(prog)) {
+ }
+ } while (vm.compile());
+ assertEquals(inputVal,prog.getCounts());
+ } catch (Exception e) {
+ fail("Error in test setup: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ // Boundary value test
+ inputVal = 0;
+ TestProgressHandler progBoundary = new TestProgressHandler();
+ db.progress_handler(inputVal, progBoundary);
+ try {
+ Vm vm2 = db.compile("select * from TEST5; "
+ + "insert into TEST5 values(3, 'James', 'Bond'); "
+ + "delete from TEST5 where id = 3; "
+ + "select * from TEST5");
+ do {
+ vm2.step(progBoundary);
+ } while (vm2.compile());
+ assertEquals(inputVal, progBoundary.getCounts());
+ }catch (Exception e) {
+ fail("Error in test setup: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ db.exec("drop table TEST5",null);
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+
+
+ class SinFunc implements Function {
+
+
+ public void function(FunctionContext fc, String args[]) {
+ Double d = new Double(args[0]);
+ fc.set_result(Math.sin(d.doubleValue()));
+ }
+
+ public void last_step(FunctionContext fc) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void step(FunctionContext fc, String[] args) {
+ // TODO Auto-generated method stub
+
+ }
+ }
+
+ @TestTargetClass(Trace.class)
+ class TestTrace implements Trace,Callback {
+
+ private StringBuffer buf = new StringBuffer();
+
+ public String getTrace() {
+ return buf.toString();
+ }
+
+ public void trace(String stmt) {
+ buf.append(stmt);
+ }
+
+ public void columns(String[] coldata) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean newrow(String[] rowdata) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void types(String[] types) {
+ // TODO Auto-generated method stub
+
+ }
+ }
+
+ @TestTargetClass(Authorizer.class)
+ class AuthorizerCallback implements Authorizer,Callback {
+ private boolean isAuthorizing = false;
+
+ public boolean wasCalled() {
+ return isAuthorizing;
+ }
+
+ public int authorize(int action, String arg1, String arg2, String arg3,
+ String arg4) {
+ System.out.println("Authorize "+action+" "+arg1+" "+arg2+" "+arg3+" "+arg4+" ");
+ this.isAuthorizing = true;
+ if (action != Constants.SQLITE_SELECT || arg1 == "private_table" ) {
+ return Constants.SQLITE_DENY;
+ } else {
+ return Constants.SQLITE_OK;
+ }
+ }
+
+ public void columns(String[] coldata) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean newrow(String[] rowdata) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void types(String[] types) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ class TestBusyHandler implements BusyHandler, Callback {
+
+ public boolean busy(String table, int count) {
+ System.out.println("BUSY!");
+ return true;
+ }
+
+ public void columns(String[] coldata) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean newrow(String[] rowdata) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void types(String[] types) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+ class TestProgressHandler implements ProgressHandler,Callback {
+
+ private boolean progressed = false;
+
+ private int counter = 0;
+
+ public boolean isProgressed() {
+ return progressed;
+ }
+
+ public int getCounts() {
+ return counter;
+ }
+
+ public boolean progress() {
+ this.progressed = true;
+ counter++;
+ return true;
+ }
+
+ public void columns(String[] coldata) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean newrow(String[] rowdata) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void types(String[] types) {
+ // TODO Auto-generated method stub
+
+ }
+
+ }
+
+// class dbBusyThread implements Runnable {
+//
+// String dbName = "sqliteTest.db";
+//
+// Thread runner;
+// public dbBusyThread() {
+// }
+// public dbBusyThread(String threadName) {
+// runner = new Thread(this, threadName); // (1) Create a new thread.
+// System.out.println(runner.getName());
+// runner.start(); // (2) Start the thread.
+// }
+// public void run() {
+// insert(3000);
+// }
+//
+// public void runNoDelay() {
+// insert(0);
+// }
+//
+// synchronized private void insert(long delay) {
+// Database db2 = new Database();
+// try {
+// db2.open(dbName, 0);
+// db2.exec("insert into TEST5 values (4,'Anglina','Jolie');",
+// null);
+// wait(delay);
+// } catch (Exception e) {
+// System.out.println("Error in Thread " + e.getMessage());
+// e.printStackTrace();
+// } catch (InterruptedException e2) {
+// System.out.println("Error in Thread " + e2.getMessage());
+// e2.printStackTrace();
+// } finally {
+// try {
+// db2.close();
+// } catch (Exception e) {
+// // We do not handle this case
+// }
+// }
+// }
+// }
+
+ /**
+ * This method creates a Runnable that executes insert operation for the
+ * first table
+ */
+ private static Runnable createTask2Interrupt(final int id,
+ final String dbName, final ErrorTracker errorTracker) {
+ return new Runnable() {
+ public void run() {
+ Database db = new Database();
+ try {
+ String value = DatabaseCreator.defaultString + id;
+
+ db.open(dbName, 0);
+ String insertQuery = "INSERT INTO "
+ + DatabaseCreator.TEST_TABLE1
+ + " (id, field1, field2, field3) VALUES(" + id
+ + ", '" + value + "', " + id + ", " + id + ")";
+ db.exec(insertQuery, null);
+ } catch (Exception e) {
+ // errorTracker.registerException(this, e);
+ db.interrupt();
+
+ try {
+ db.exec("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1
+ + " WHERE id=" + id, null);
+ } catch (Exception e1) {
+ errorTracker.reset();
+ errorTracker.registerException(this, e1);
+ }
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes delete operation for the
+ * first table
+ */
+ private static Runnable createTask1(final int id,final String dbName, final ErrorTracker errorTracker) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Database db = new Database();
+ db.open(dbName, 0);
+ db.exec("DELETE FROM "
+ + DatabaseCreator.SIMPLE_TABLE1 + " WHERE id=" + id,null);
+ } catch (Exception e) {
+ errorTracker.registerException(this, e);
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes insert operation for the
+ * first table
+ */
+ private static Runnable createTask2(final int id, final String dbName, final ErrorTracker errorTracker ) {
+ return new Runnable() {
+ public void run() {
+ try {
+ String value = DatabaseCreator.defaultString + id;
+ Database db = new Database();
+ db.open(dbName, 0);
+ String insertQuery = "INSERT INTO "
+ + DatabaseCreator.TEST_TABLE1
+ + " (id, field1, field2, field3) VALUES(" + id
+ + ", '" + value + "', " + id + ", " + id + ")";
+ db.exec(insertQuery,null);
+ } catch (Exception e) {
+ errorTracker.registerException(this, e);
+
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes update operation for the one
+ * record of the first table
+ */
+ private static Runnable createTask3(final int oldID, final String dbName,
+ final int newID, final ErrorTracker errorTracker) {
+ return new Runnable() {
+ public void run() {
+ Database db = new Database();
+ try {
+ db.open(dbName, 0);
+ String value = DatabaseCreator.defaultString + newID;
+ String updateQuery = "UPDATE "
+ + DatabaseCreator.TEST_TABLE1 + " SET id=" + newID
+ + ", field1='" + value + "', field2=" + newID
+ + ", field3=" + newID + " WHERE id=" + oldID;
+ db.exec(updateQuery, null);
+ } catch (Exception e) {
+ errorTracker.registerException(this, e);
+ }
+ }
+ };
+ }
+
+ private class ErrorTracker {
+ private List<String> errors = new ArrayList<String>();
+
+ public void registerException(Runnable runnable, Exception e) {
+ System.out.println("Registered: "+e.getMessage());
+ errors.add(e.getMessage());
+ }
+
+ public List<String> getErrors() {
+ return errors;
+ }
+
+ public void reset() {
+ errors.clear();
+ }
+ }
+
+}
+
diff --git a/sql/src/test/java/tests/SQLite/ExceptionTest.java b/sql/src/test/java/tests/SQLite/ExceptionTest.java
new file mode 100644
index 0000000..cc37c2a
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/ExceptionTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.Exception;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetNew;
+
+import junit.framework.TestCase;
+
+public class ExceptionTest extends TestCase {
+
+ public ExceptionTest(String name) {
+ super(name);
+ }
+
+ protected void setUp() throws java.lang.Exception {
+ super.setUp();
+ }
+
+ protected void tearDown() throws java.lang.Exception {
+ super.tearDown();
+ }
+
+ /**
+ * @tests {@link Exception#Exception(String)}
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "constructor test",
+ method = "Exception",
+ args = {java.lang.String.class}
+ )
+ public void testException() {
+ fail("not yet implemented");
+ }
+
+}
diff --git a/sql/src/test/java/tests/SQLite/FunctionContextTest.java b/sql/src/test/java/tests/SQLite/FunctionContextTest.java
new file mode 100644
index 0000000..e07d7ca
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/FunctionContextTest.java
@@ -0,0 +1,156 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.FunctionContext;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargetClass;
+
+import junit.framework.TestCase;
+
+@TestTargetClass(FunctionContext.class)
+public class FunctionContextTest extends TestCase {
+
+ /**
+ * @param name
+ */
+ public FunctionContextTest(String name) {
+ super(name);
+ }
+
+ /* (non-Javadoc)
+ * @see junit.framework.TestCase#setUp()
+ */
+ protected void setUp() throws java.lang.Exception {
+ super.setUp();
+
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#FunctionContext()}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "constructor test",
+ method = "FunctionContext",
+ args = {}
+ )
+ public void testFunctionContext() {
+ fail("Not yet implemented");
+ }
+
+ /* (non-Javadoc)
+ * @see junit.framework.TestCase#tearDown()
+ */
+ protected void tearDown() throws java.lang.Exception {
+ super.tearDown();
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#set_result(java.lang.String)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "method test",
+ method = "set_result",
+ args = {java.lang.String.class}
+ )
+ public void testSet_resultString() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#set_result(int)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "method test",
+ method = "set_result",
+ args = {int.class}
+ )
+ public void testSet_resultInt() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#set_result(double)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "method test",
+ method = "set_result",
+ args = {double.class}
+ )
+ public void testSet_resultDouble() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#set_error(java.lang.String)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "method test",
+ method = "set_error",
+ args = {java.lang.String.class}
+ )
+ public void testSet_error() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#set_result(byte[])}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "method test",
+ method = "set_result",
+ args = {byte[].class}
+ )
+ public void testSet_resultByteArray() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#set_result_zeroblob(int)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "method test",
+ method = "set_result_zeroblob",
+ args = {int.class}
+ )
+ public void testSet_result_zeroblob() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.FunctionContext#count()}.
+ */
+ @TestTargetNew(
+ level = TestLevel.TODO,
+ notes = "method test",
+ method = "count",
+ args = {}
+ )
+ public void testCount() {
+ fail("Not yet implemented");
+ }
+
+}
diff --git a/sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java b/sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java
new file mode 100644
index 0000000..e872182
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.Exception;
+import SQLite.JDBCDriver;
+import dalvik.annotation.TestTargetClass;
+
+import java.io.File;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+
+/**
+ * Tests the SQLite.JDBCDriver.
+ */
+@TestTargetClass(JDBCDriver.class)
+public class JDBCDriverFunctionalTest extends AbstractSqlTest {
+
+
+
+ /**
+ * The SQLite db file.
+ */
+ private File dbFile = null;
+
+ private String connectionURL = "empty";
+
+ /**
+ * Creates a new instance of this class.
+ */
+ public JDBCDriverFunctionalTest(String testName) {
+ super(testName);
+ }
+
+ /**
+ * Sets up an unit test by loading the SQLite.JDBCDriver, getting two
+ * connections and calling the setUp method of the super class.
+ * @throws Exception
+ * @throws IllegalAccessException
+ * @throws InstantiationException
+ * @throws Exception
+ * @throws Exception
+ * @throws Exception
+ * @throws Exception
+ * @throws Exception
+ */
+ @Override
+ protected void setUp() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, Exception { // the Exception class needs to be fully
+ // qualified since there is an Exception
+ // class in the SQLite package.
+
+ super.setUp();
+ }
+
+ /**
+ * Tears down an unit test by calling the tearDown method of the super class
+ * and deleting the SQLite test db file.
+ */
+ @Override
+ protected void tearDown() throws SQLException {
+ super.tearDown();
+ dbFile.delete();
+ }
+
+
+ @Override
+ protected String getConnectionURL() {
+ if (connectionURL.equals("empty")) {
+ String tmp = System.getProperty("java.io.tmpdir");
+ File tmpDir = new File(tmp);
+ if (tmpDir.isDirectory()) {
+ try {
+ dbFile = File.createTempFile("JDBCDriverFunctionalTest",
+ ".db", tmpDir);
+ } catch (IOException e) {
+ System.err.println("error creating temporary DB file.");
+ }
+ dbFile.deleteOnExit();
+ } else {
+ System.err.println("ctsdir does not exist");
+ }
+
+ connectionURL = "jdbc:sqlite:/" + dbFile.getPath();
+
+ }
+
+ return connectionURL;
+ }
+
+ @Override
+ protected String getDriverClassName() {
+ return "SQLite.JDBCDriver";
+ }
+
+ @Override
+ protected int getTransactionIsolation() {
+ return Connection.TRANSACTION_SERIALIZABLE;
+ }
+
+
+}
diff --git a/sql/src/test/java/tests/SQLite/JDBCDriverTest.java b/sql/src/test/java/tests/SQLite/JDBCDriverTest.java
new file mode 100644
index 0000000..a252cd4
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/JDBCDriverTest.java
@@ -0,0 +1,280 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.Exception;
+import SQLite.JDBCDriver;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargets;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+
+
+@TestTargetClass(JDBCDriver.class)
+public class JDBCDriverTest extends JDBCDriverFunctionalTest {
+
+ public JDBCDriverTest(String testName) {
+ super(testName);
+ }
+
+ /**
+ * The SQLite db file.
+ */
+// private final File dbFile = new File("sqliteTest.db");
+//
+// private final String connectionURL = "jdbc:sqlite:/" + dbFile.getName();
+
+ private JDBCDriver jDriver;
+
+ private Driver returnedDriver;
+
+ public void setUp() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, Exception {
+
+ try {
+ super.setUp();
+ returnedDriver = DriverManager.getDriver(getConnectionURL());
+ if (returnedDriver instanceof JDBCDriver) {
+ this.jDriver = (JDBCDriver) returnedDriver;
+ }
+ } catch (SQLException e) {
+ System.out.println("Cannot get driver");
+ e.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("DB Setup failed");
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests JDBCDriver#JDBCDriver()
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "constructor test",
+ method = "JDBCDriver",
+ args = {}
+ )
+ public void testJDBCDriver() {
+ assertTrue(returnedDriver instanceof JDBCDriver);
+ }
+
+ /**
+ * @tests JDBCDriver#acceptsURL(String)
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "constructor test",
+ method = "acceptsURL",
+ args = {java.lang.String.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "constructor test",
+ // we have to list the Driver target explicitly, since SQLite
+ // is not part of the target packages
+ clazz = Driver.class,
+ method = "acceptsURL",
+ args = {java.lang.String.class}
+ )
+ })
+ public void testAcceptsURL() {
+ try {
+ if (this.jDriver != null) {
+ assertTrue(jDriver.acceptsURL(getConnectionURL()));
+ } else {
+ fail("no Driver available");
+ }
+ } catch (SQLException e) {
+ fail("Driver does not accept URL");
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests JDBCDriver#connect(String, java.util.Properties)
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "connect",
+ args = {java.lang.String.class, java.util.Properties.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ // we have to list the Driver target explicitly, since SQLite
+ // is not part of the target packages
+ clazz = Driver.class,
+ notes = "method test",
+ method = "connect",
+ args = {java.lang.String.class, java.util.Properties.class}
+ )
+ })
+ public void testConnect() {
+ try {
+ if (this.jDriver != null) {
+ Connection c = jDriver.connect(getConnectionURL(), null);
+ assertFalse(c.isClosed());
+ DriverManager.getConnection(getConnectionURL());
+ } else {
+ fail("no Driver available");
+ }
+ } catch (SQLException e) {
+ fail("Driver does not connect");
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests JDBCDriver#getMajorVersion()
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "getMajorVersion",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ // we have to list the Driver target explicitly, since SQLite
+ // is not part of the target packages
+ clazz = Driver.class,
+ notes = "method test",
+ method = "getMajorVersion",
+ args = {}
+ )
+ })
+ public void testGetMajorVersion() {
+ if (this.jDriver != null) {
+ assertTrue(jDriver.getMajorVersion() > 0);
+ } else {
+ fail("no Driver available");
+ }
+ }
+
+ /**
+ * @tests JDBCDriver#getMinorVersion()
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "getMinorVersion",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ // we have to list the Driver target explicitly, since SQLite
+ // is not part of the target packages
+ clazz = Driver.class,
+ method = "getMinorVersion",
+ args = {}
+ )
+ })
+ public void testGetMinorVersion() {
+ if (this.jDriver != null) {
+ assertTrue(jDriver.getMinorVersion() > 0);
+ } else {
+ fail("no version information available");
+ }
+ }
+
+ /**
+ * @tests JDBCDriver#getPropertyInfo(String, java.util.Properties)
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "getPropertyInfo",
+ args = {java.lang.String.class, java.util.Properties.class}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ // we have to list the Driver target explicitly, since SQLite
+ // is not part of the target packages
+ clazz = Driver.class,
+ method = "getPropertyInfo",
+ args = {java.lang.String.class, java.util.Properties.class}
+ )
+ })
+ public void testGetPropertyInfo() {
+ DriverPropertyInfo[] info = null;
+ try {
+ if (this.jDriver != null) {
+ info = jDriver.getPropertyInfo(getConnectionURL(), null);
+ assertNotNull(info);
+ assertTrue(info.length > 0);
+ } else {
+ fail("no Driver available");
+ }
+ } catch (SQLException e) {
+ fail("Driver property details not available");
+ e.printStackTrace();
+ }
+
+ assertNotNull(info);
+
+ }
+
+ /**
+ * @tests JDBCDriver#jdbcCompliant()
+ */
+ @TestTargets({
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "jdbcCompliant",
+ args = {}
+ ),
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ // we have to list the Driver target explicitly, since SQLite
+ // is not part of the target packages
+ clazz = Driver.class,
+ notes = "method test",
+ method = "jdbcCompliant",
+ args = {}
+ )
+ })
+ public void testJdbcCompliant() {
+ if (this.jDriver != null) {
+ assertFalse(jDriver.jdbcCompliant());
+ } else {
+ fail("no version information available");
+ }
+ }
+ /**
+ * Tears down an unit test by calling the tearDown method of the super class
+ * and deleting the SQLite test db file.
+ */
+ @Override
+ protected void tearDown() throws SQLException {
+ super.tearDown();
+ }
+
+}
diff --git a/sql/src/test/java/tests/SQLite/SQLiteTest.java b/sql/src/test/java/tests/SQLite/SQLiteTest.java
new file mode 100644
index 0000000..195b013
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/SQLiteTest.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import junit.framework.TestCase;
+
+import java.io.File;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+public class SQLiteTest extends TestCase {
+ public static Connection conn;
+ public static File dbFile = null;
+
+ public void setup() {
+ String tmp = System.getProperty("ctsdir");
+ File tmpDir = new File(tmp);
+ try {
+ if (tmpDir.isDirectory()) {
+ dbFile = File.createTempFile("sqliteTest", ".db", tmpDir);
+ dbFile.deleteOnExit();
+ } else {
+ System.out.println("ctsdir does not exist");
+ }
+
+ Class.forName("SQLite.JDBCDriver").newInstance();
+
+ if (dbFile.exists()) {
+ System.out.println("SQLTest.getSQLiteConnection()File:"
+ + dbFile.getName());
+ }
+ System.out.println("DB File created and Driver instantiated");
+ System.out.println("Path "+ dbFile.getPath());
+ conn = DriverManager.getConnection("jdbc:sqlite:/"
+ + dbFile.getPath());
+ assertNotNull("Connection created ",conn);
+
+ } catch (IOException e) {
+ System.out.println("Problem creating test file in " + tmp);
+ } catch (SQLException e) {
+ // TODO Auto-generated catch block
+ fail("Exception: " + e.toString());
+ } catch (java.lang.Exception e) {
+ fail("Exception: " + e.toString());
+ }
+
+ }
+
+ public void tearDown() {
+ try {
+ if (!conn.isClosed()) {
+ conn.close();
+ }
+ } catch (SQLException e) {
+ fail("Couldn't close Connection: " + e.getMessage());
+ }
+
+ }
+
+}
diff --git a/sql/src/test/java/tests/SQLite/ShellTest.java b/sql/src/test/java/tests/SQLite/ShellTest.java
new file mode 100644
index 0000000..208341c
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/ShellTest.java
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.Shell;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetClass;
+import dalvik.annotation.TestTargetNew;
+
+import junit.framework.TestCase;
+
+import java.io.PrintStream;
+import java.io.PrintWriter;
+
+@TestTargetClass(Shell.class)
+public class ShellTest extends TestCase {
+
+ /**
+ * Test method for {@link SQLite.Shell#Shell(java.io.PrintWriter, java.io.PrintWriter)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "Shell",
+ args = {PrintWriter.class, PrintWriter.class}
+ )
+ public void testShellPrintWriterPrintWriter() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.Shell#Shell(java.io.PrintStream, java.io.PrintStream)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "Shell",
+ args = {PrintStream.class, PrintStream.class}
+ )
+ public void testShellPrintStreamPrintStream() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.Shell#clone()}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "clone",
+ args = {}
+ )
+ public void testClone() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.Shell#sql_quote_dbl(java.lang.String)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "sql_quote_dbl",
+ args = {String.class}
+ )
+ public void testSql_quote_dbl() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.Shell#sql_quote(java.lang.String)}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "sql_quote",
+ args = {String.class}
+ )
+ public void testSql_quote() {
+ fail("Not yet implemented");
+ }
+
+
+ /**
+ * Test method for {@link SQLite.Shell#columns(java.lang.String[])}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "columns",
+ args = {String[].class}
+ )
+ public void testColumns() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.Shell#types(java.lang.String[])}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "types",
+ args = {String[].class}
+ )
+ public void testTypes() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * Test method for {@link SQLite.Shell#newrow(java.lang.String[])}.
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "newrow",
+ args = {String[].class}
+ )
+ public void testNewrow() {
+ fail("Not yet implemented");
+ }
+
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "",
+ method = "main",
+ args = {String[].class}
+ )
+ public void testMain() {
+
+ }
+
+}
diff --git a/sql/src/test/java/tests/SQLite/StmtTest.java b/sql/src/test/java/tests/SQLite/StmtTest.java
new file mode 100644
index 0000000..fc611db
--- /dev/null
+++ b/sql/src/test/java/tests/SQLite/StmtTest.java
@@ -0,0 +1,962 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.SQLite;
+
+import SQLite.Database;
+import SQLite.Exception;
+import SQLite.Stmt;
+import SQLite.TableResult;
+import dalvik.annotation.TestTargets;
+import dalvik.annotation.TestLevel;
+import dalvik.annotation.TestTargetNew;
+import dalvik.annotation.TestTargetClass;
+
+import junit.framework.TestCase;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+@TestTargetClass(Stmt.class)
+public class StmtTest extends SQLiteTest {
+
+ private static Database db = null;
+
+ private static Stmt st = null;
+
+// private final File dbFile = new File("sqliteTest.db");
+
+ protected void setUp() throws java.lang.Exception {
+ super.setUp();
+ Support_SQL.loadDriver();
+ db = new Database();
+ db.open(dbFile.getName(), 0);
+ db.exec(DatabaseCreator.CREATE_TABLE_SIMPLE1, null);
+ DatabaseCreator.fillSimpleTable1(Support_SQL.getConnection());
+
+ st = new Stmt();
+ }
+
+ public void tearDown() {
+ super.tearDown();
+ try {
+ db.close();
+ Connection con = Support_SQL.getConnection();
+ con.close();
+// dbFile.delete();
+ } catch (Exception e) {
+ fail("Exception in tearDown: "+e.getMessage());
+ } catch (SQLException e) {
+ fail("SQLException in tearDown: "+e.getMessage());
+ }
+
+ }
+
+ /**
+ * @tests {@link Stmt#Stmt()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "constructor test",
+ method = "Stmt",
+ args = {}
+ )
+ public void _testStmt() {
+ Stmt st = new Stmt();
+ assertNotNull(st);
+ try {
+ Stmt actual = db.prepare("");
+ assertNotNull(st);
+ // no black box test assertEquals(actual.error_code,st.error_code);
+ } catch (Exception e) {
+ fail("Statement setup fails: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.step();
+ fail("Cannot execute non prepared Stmt");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#finalize()}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "finalize",
+ args = {}
+ )
+ public void _testFinalize() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#prepare()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "prepare",
+ args = {}
+ )
+ public void testPrepare() {
+ try {
+ st = db.prepare("");
+ st.prepare();
+ fail("statement is closed");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ try {
+ st = new Stmt();
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ assertFalse(st.prepare());
+ st = new Stmt();
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertFalse(st.prepare());
+ st = new Stmt();
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ st.bind(1, 1);
+ st.bind(2, 10);
+ st.bind(3, 30);
+ assertFalse(st.prepare());
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1
+ + "; " + "delete from " + DatabaseCreator.SIMPLE_TABLE1
+ + " where id = 5; " + "insert into "
+ + DatabaseCreator.SIMPLE_TABLE1 + " values(5, 10, 20); "
+ + "select * from " + DatabaseCreator.SIMPLE_TABLE1 + ";");
+ assertTrue(st.prepare());
+ assertTrue(st.prepare());
+ assertTrue(st.prepare());
+ assertFalse(st.prepare());
+ } catch (Exception e) {
+ fail("statement should be ready for execution: "
+ + e.getMessage());
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#step()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "step",
+ args = {}
+ )
+ public void testStep() {
+ try {
+ st.step();
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ try {
+ st = new Stmt();
+ st = db.prepare("select name from sqlite_master where type = 'table'");
+ st.step();
+ } catch (Exception e) {
+ fail("test fails");
+ }
+
+ }
+
+ /**
+ * @tests {@link Stmt#close()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "close",
+ args = {}
+ )
+ public void testClose() {
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ st.close();
+ } catch (Exception e) {
+ fail("Test fails");
+ e.printStackTrace();
+ }
+
+ try {
+ st.step();
+ fail("Test fails");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#reset()}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "reset",
+ args = {}
+ )
+ public void _testReset() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#clear_bindings()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "not supported",
+ method = "clear_bindings",
+ args = {}
+ )
+ public void testClear_bindings() {
+ try {
+ st.clear_bindings();
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind(int, int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind",
+ args = {int.class, int.class}
+ )
+ public void testBindIntInt() {
+ try {
+ int input = 0;
+ int maxVal = Integer.MAX_VALUE;
+ int minVal = Integer.MIN_VALUE;
+
+ db.exec("create table TEST (res integer)", null);
+ st = db.prepare("insert into TEST values (:one);");
+ st.bind(1, input);
+ st.step();
+
+ st.reset();
+ st.bind(1,maxVal);
+ st.step();
+
+ st.reset();
+ st.bind(1,minVal);
+ st.step();
+
+ TableResult r = db.get_table("select * from TEST");
+
+ String[] row0 = (String[]) r.rows.elementAt(0);
+ assertEquals(input,Integer.parseInt(row0[0]));
+
+ String[] row1 = (String[]) r.rows.elementAt(1);
+ assertEquals(maxVal,Integer.parseInt(row1[0]));
+
+ String[] row2 = (String[]) r.rows.elementAt(2);
+ assertEquals(minVal,Integer.parseInt(row2[0]));
+
+ } catch (Exception e) {
+ fail("Error in test setup: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.close();
+ st.bind(1,Integer.MIN_VALUE);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind(int, long)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind",
+ args = {int.class, long.class}
+ )
+ public void testBindIntLong() {
+ try {
+ long input = 0;
+ long maxVal = Long.MAX_VALUE;
+ long minVal = Long.MIN_VALUE;
+
+ db.exec("create table TEST (res long)", null);
+ st = db.prepare("insert into TEST values (:one);");
+ st.bind(1, input);
+ st.step();
+
+ st.reset();
+ st.bind(1,maxVal);
+ st.step();
+
+ st.reset();
+ st.bind(1,minVal);
+ st.step();
+
+ TableResult r = db.get_table("select * from TEST");
+
+ String[] row0 = (String[]) r.rows.elementAt(0);
+ assertEquals(input,Long.parseLong(row0[0]));
+
+ String[] row1 = (String[]) r.rows.elementAt(1);
+ assertEquals(maxVal,Long.parseLong(row1[0]));
+
+ String[] row2 = (String[]) r.rows.elementAt(2);
+ assertEquals(minVal,Long.parseLong(row2[0]));
+
+ } catch (Exception e) {
+ fail("Error in test setup: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.close();
+ st.bind(1,Long.MIN_VALUE);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind(int, double)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind",
+ args = {int.class, double.class}
+ )
+ public void testBindIntDouble() {
+ try {
+ double input = 0.0;
+ double maxVal = Double.MAX_VALUE;
+ double minVal = Double.MIN_VALUE;
+ double negInf = Double.NEGATIVE_INFINITY;
+ double posInf = Double.POSITIVE_INFINITY;
+ double nan = Double.NaN;
+
+ db.exec("create table TEST (res double)", null);
+ st = db.prepare("insert into TEST values (:one);");
+ st.bind(1, input);
+ st.step();
+
+ st.reset();
+ st.bind(1, maxVal);
+ st.step();
+
+ st.reset();
+ st.bind(1, minVal);
+ st.step();
+
+ st.reset();
+ st.bind(1, negInf);
+ st.step();
+
+ st.reset();
+ st.bind(1, posInf);
+ st.step();
+
+ st.reset();
+ st.bind(1, nan);
+ st.step();
+
+
+ TableResult r = db.get_table("select * from TEST");
+
+ String[] row0 = (String[]) r.rows.elementAt(0);
+ assertTrue(Double.compare(input, Double.parseDouble(row0[0])) == 0);
+
+ String[] row1 = (String[]) r.rows.elementAt(1);
+ assertFalse(Double.compare(maxVal, Double.parseDouble(row1[0])) == 0);
+ assertTrue(Double.compare(maxVal, Double.parseDouble(row1[0])) < 0);
+ assertTrue(Double.isInfinite(Double.parseDouble(row1[0])));
+
+ String[] row2 = (String[]) r.rows.elementAt(2);
+ assertTrue(Double.compare(minVal, Double.parseDouble(row2[0])) == 0);
+
+ String[] row3 = (String[]) r.rows.elementAt(3);
+ assertEquals("Double.NEGATIVE_INFINITY SQLite representation",
+ "-Inf", row3[0]);
+
+ String[] row4 = (String[]) r.rows.elementAt(4);
+ assertEquals("Double.POSITIVE_INFINITY SQLite representation",
+ "Inf", row4[0]);
+
+ String[] row5 = (String[]) r.rows.elementAt(4);
+ assertEquals("Double.Nan SQLite representation", "Inf", row5[0]);
+
+ } catch (Exception e) {
+ fail("Error in test setup: " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.close();
+ st.bind(1,0.0);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind(int, byte[])}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "",
+ method = "bind",
+ args = {int.class, byte[].class}
+ )
+ public void testBindIntByteArray() {
+
+ String name = "Hello World";
+
+ try {
+ byte[] b = new byte[name.getBytes().length];
+ b = name.getBytes();
+ String stringInHex = "";
+
+ db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
+ st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
+ + " values (:one, :two);");
+ st.bind(1, 2);
+ st.bind(2, b);
+ st.step();
+
+ //compare what was stored with input based on Hex representation
+ // since type of column is CHAR
+ TableResult r = db.get_table("select * from "
+ + DatabaseCreator.PARENT_TABLE);
+ String[] row = (String[]) r.rows.elementAt(0);
+
+ for (byte aByte : b) {
+ stringInHex += Integer.toHexString(aByte);
+ }
+ stringInHex = "X'" + stringInHex + "'";
+ assertTrue(stringInHex.equalsIgnoreCase(row[1]));
+
+ } catch (Exception e) {
+ fail("Error in test setup: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.close();
+ st.bind(1,name.getBytes());
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind(int, String)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind",
+ args = {int.class, java.lang.String.class}
+ )
+ public void testBindIntString() {
+ String name = "Hello World";
+
+ try {
+
+ db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null);
+ st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE
+ + " values (:one, :two);");
+ st.bind(1, 2);
+ st.bind(2, name);
+ st.step();
+
+ TableResult r = db.get_table("select * from "
+ + DatabaseCreator.PARENT_TABLE);
+ String[] row = (String[]) r.rows.elementAt(0);
+ assertEquals(name,row[1]);
+
+ } catch (Exception e) {
+ fail("Error in test setup: "+e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.close();
+ st.bind(1,name);
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind",
+ args = {int.class}
+ )
+ public void testBindInt() {
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ st.bind(4);
+ st.bind(1, 4);
+ st.bind(2, 10);
+ st.bind(3, 30);
+ st.step();
+ fail("Test failes");
+ } catch (Exception e) {
+ // What happens if null is bound to non existing variable position
+ assertEquals("parameter position out of bounds" , e.getMessage());
+ }
+
+ // functional tests
+
+ try {
+ st.reset();
+ st.bind(1);
+ st.bind(2, 10);
+ st.bind(3, 30);
+ st.step();
+ fail("Test failes");
+ } catch (Exception e) {
+ // What happens if null is bound to NON NULL field
+ assertEquals("SQL logic error or missing database", e.getMessage());
+ }
+
+ try {
+ st.reset();
+ st.bind(1, 3);
+ st.bind(2);
+ st.bind(3, 30);
+ st.step();
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ }
+
+ }
+
+ /**
+ * @tests {@link Stmt#bind_zeroblob(int, int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "not supported",
+ method = "bind_zeroblob",
+ args = {int.class, int.class}
+ )
+ public void testBind_zeroblob() {
+ try {
+ st.bind_zeroblob(1, 128);
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind_parameter_count()}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind_parameter_count",
+ args = {}
+ )
+ public void testBind_parameter_count() {
+ try {
+ st.bind_parameter_count();
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(3, st.bind_parameter_count());
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (?, ?, ?)");
+ assertEquals(3, st.bind_parameter_count());
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1);
+ assertEquals(0, st.bind_parameter_count());
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.close();
+ st.bind_parameter_count();
+ fail("Exception expected");
+ } catch (Exception e) {
+ //ok
+ }
+
+ }
+
+ /**
+ * @tests {@link Stmt#bind_parameter_name(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind_parameter_name",
+ args = {int.class}
+ )
+ public void testBind_parameter_name() {
+ try {
+ st.bind_parameter_name(1);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(":one", st.bind_parameter_name(1));
+ assertEquals(":two", st.bind_parameter_name(2));
+ assertEquals(":three", st.bind_parameter_name(3));
+ String name = st.bind_parameter_name(4);
+ } catch (Exception e) {
+ assertEquals("parameter position out of bounds",e.getMessage());
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#bind_parameter_index(String)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "bind_parameter_index",
+ args = {java.lang.String.class}
+ )
+ public void testBind_parameter_index() {
+
+ try {
+ st.bind_parameter_index("");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("stmt already closed", e.getMessage());
+ }
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(3, st.bind_parameter_index(":three"));
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ assertEquals(0, st.bind_parameter_index(":t"));
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (?, ?, ?)");
+ assertEquals(0, st.bind_parameter_index("?"));
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * @tests {@link Stmt#column_int(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_int",
+ args = {int.class}
+ )
+ public void _testColumn_int() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#column_long(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "column_long",
+ args = {int.class}
+ )
+ public void testColumn_long() {
+ Object columnObject = null;
+ int columnObjectCastFromLong;
+ long longColumn = 0;
+ try {
+ String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
+ TableResult res = db.get_table(selectStmt);
+ st = db.prepare(selectStmt);
+ st.step();
+ columnObject = st.column(1);
+ longColumn = st.column_long(1);
+ assertNotNull(longColumn);
+ // column declared as integer
+ assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
+ int stSpeed = Integer.parseInt(columnObject.toString());
+ assertNotNull(stSpeed);
+ assertEquals( longColumn, stSpeed);
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ st.column_long(4);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+
+ try {
+ st.column_long(-1);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#column_double(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_double",
+ args = {int.class}
+ )
+ public void _testColumn_double() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#column_bytes(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "not supported",
+ method = "column_bytes",
+ args = {int.class}
+ )
+ public void testColumn_bytes() {
+ try {
+ st.column_bytes(1);
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#column_string(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_string",
+ args = {int.class}
+ )
+ public void _testColumn_string() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#column_type(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_type",
+ args = {int.class}
+ )
+ public void _testColumn_type() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#column_count() )}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_count",
+ args = {}
+ )
+ public void _testColumn_count() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#column(int) )}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "method test",
+ method = "column",
+ args = {int.class}
+ )
+ public void testColumn() {
+ Object columnObject = null;
+ int columnObjectCastFromLong;
+ int intColumn = 0;
+ try {
+ String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1;
+ TableResult res = db.get_table(selectStmt);
+ st = db.prepare(selectStmt);
+ st.step();
+ columnObject = st.column(1);
+ intColumn = st.column_int(1);
+ assertNotNull(intColumn);
+ assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1)));
+ int stSpeed = Integer.parseInt(columnObject.toString());
+ assertNotNull(stSpeed);
+ assertEquals( intColumn, stSpeed);
+ } catch (Exception e) {
+ fail("Error in test setup : " + e.getMessage());
+ e.printStackTrace();
+ }
+
+ try {
+ assertNotNull(columnObject);
+ int dummy = ((Integer) columnObject).intValue();
+ fail("Cast to Integer should fail");
+ } catch (ClassCastException e) {
+ assertEquals("java.lang.Long", e.getMessage());
+ }
+
+ try {
+ st.column(4);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+
+ try {
+ st.column(-1);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals( "column out of bounds" , e.getMessage());
+ }
+ }
+
+ /**
+ * @tests {@link Stmt#column_table_name(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_table_name",
+ args = {int.class}
+ )
+ public void _testColumn_table_name() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#column_database_name(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.COMPLETE,
+ notes = "not supported",
+ method = "column_database_name",
+ args = {int.class}
+ )
+ public void testColumn_database_name() {
+ try {
+ st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1
+ + " values (:one,:two,:three)");
+ String name = st.column_database_name(1);
+ fail("test fails");
+ } catch (Exception e) {
+ assertEquals("unsupported", e.getMessage());
+ }
+
+ }
+
+ /**
+ * @tests {@link Stmt#column_decltype(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_decltype",
+ args = {int.class}
+ )
+ public void _testColumn_decltype() {
+ fail("Not yet implemented");
+ }
+
+ /**
+ * @tests {@link Stmt#column_origin_name(int)}
+ */
+ @TestTargetNew(
+ level = TestLevel.NOT_FEASIBLE,
+ notes = "method test",
+ method = "column_origin_name",
+ args = {int.class}
+ )
+ public void _testColumn_origin_name() {
+ fail("Not yet implemented");
+ }
+}