diff options
author | The Android Open Source Project <initial-contribution@android.com> | 2009-02-10 15:43:57 -0800 |
---|---|---|
committer | The Android Open Source Project <initial-contribution@android.com> | 2009-02-10 15:43:57 -0800 |
commit | b7926325a1c1a370c84c81db80372f59af240a53 (patch) | |
tree | b1d0214be443ea674d0ded8c502a8e074e50bdd2 /sql | |
parent | 687f18b91f4a0a728a027579110953ee729adcb8 (diff) | |
download | libcore-b7926325a1c1a370c84c81db80372f59af240a53.zip libcore-b7926325a1c1a370c84c81db80372f59af240a53.tar.gz libcore-b7926325a1c1a370c84c81db80372f59af240a53.tar.bz2 |
auto import from //branches/cupcake/...@130745
Diffstat (limited to 'sql')
21 files changed, 2135 insertions, 1348 deletions
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java index d459a63..a4b12ab 100644 --- a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java +++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java @@ -82,12 +82,11 @@ public class DriverManagerTest extends TestCase { * @throws SQLException */ @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SQLException checking missed: not feasible. test fails, Disabled due to potential implementation error ticket #60.", + level = TestLevel.SUFFICIENT, + notes = "SQLException checking missed: not feasible.", method = "deregisterDriver", args = {java.sql.Driver.class} ) - @BrokenTest("Error creating Test Helper in test setup") public void testDeregisterDriver() throws Exception { // First get one of the drivers loaded by the test Driver aDriver; diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java index f82271e..773684e 100644 --- a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java +++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java @@ -22,6 +22,7 @@ import dalvik.annotation.TestTargetClass; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; +import java.util.logging.Logger; import junit.framework.TestCase; @@ -49,7 +50,7 @@ public class TestHelper_DriverManager extends TestCase { public static void setDriver(Driver theDriver) { testDriver = theDriver; - // System.out.println("TestHelper_DriverManager: Test Driver set!"); + // Logger.global.info("TestHelper_DriverManager: Test Driver set!"); theHelper.checkDeregister(); } // end method setDriver( Driver ) @@ -58,19 +59,16 @@ public class TestHelper_DriverManager extends TestCase { String baseURL = "jdbc:mikes1"; - // System.out.println("Calling checkDeregister in - // TestHelper_DriverManager...."); + // Logger.global.info("Calling checkDeregister in TestHelper_DriverManager...."); Driver aDriver; - // System.out.println("checkDeregister classloader: " + - // this.getClass().getClassLoader() ); + // Logger.global.info("checkDeregister classloader: this.getClass().getClassLoader()"); // Try to get a driver from the general pool... this should fail try { aDriver = DriverManager.getDriver(baseURL); - fail( - "testDeregisterDriver: Didn't get exception when getting valid driver from other classloader."); + fail("testDeregisterDriver: Didn't get exception when getting valid driver from other classloader."); } catch (SQLException e) { // e.printStackTrace(); assertTrue( @@ -92,15 +90,13 @@ public class TestHelper_DriverManager extends TestCase { // prevent subsequent tests from failing due to inability to get to // this driver... DriverManager.registerDriver(aDriver); - fail( - "checkDeregisterDriver: Didn't get Security Exception deregistering invalid driver."); + fail("checkDeregisterDriver: Didn't get Security Exception deregistering invalid driver."); } catch (SecurityException s) { // This is the exception we should get... // System.out.println("checkDeregisterDriver: got expected Security // Exception"); } catch (Exception e) { - fail( - "checkDeregisterDriver: Got wrong exception type when deregistering invalid driver."); + fail("checkDeregisterDriver: Got wrong exception type when deregistering invalid driver."); } // end try } // end method testDeRegister diff --git a/sql/src/test/java/tests/SQLite/AbstractSqlTest.java b/sql/src/test/java/tests/SQLite/AbstractSqlTest.java index f580f70..0c7fa61 100644 --- a/sql/src/test/java/tests/SQLite/AbstractSqlTest.java +++ b/sql/src/test/java/tests/SQLite/AbstractSqlTest.java @@ -76,8 +76,8 @@ abstract class AbstractSqlTest extends TestCase { private final String[] ones_updated; /** Creates a new instance of this class */ - public AbstractSqlTest(String testName) { - super(testName); + public AbstractSqlTest() { + super(); ones_updated = new String[ones.length]; for (int i = 0; i < ones.length; i++) { ones_updated[i] = ones[i] + twos[i]; diff --git a/sql/src/test/java/tests/SQLite/AllTests.java b/sql/src/test/java/tests/SQLite/AllTests.java index bb41f58..2cf0f61 100644 --- a/sql/src/test/java/tests/SQLite/AllTests.java +++ b/sql/src/test/java/tests/SQLite/AllTests.java @@ -31,6 +31,8 @@ public class AllTests { suite.addTestSuite(ConstantsTest.class); suite.addTestSuite(BlobTest.class); suite.addTestSuite(StmtTest.class); + suite.addTestSuite(ExceptionTest.class); + suite.addTestSuite(FunctionContextTest.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 index 25c1274..71f2005 100644 --- a/sql/src/test/java/tests/SQLite/BlobTest.java +++ b/sql/src/test/java/tests/SQLite/BlobTest.java @@ -17,33 +17,61 @@ package tests.SQLite; import SQLite.Blob; +import SQLite.Database; +import SQLite.Exception; +import SQLite.Stmt; +import dalvik.annotation.KnownFailure; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; +import dalvik.annotation.TestTargets; import junit.framework.TestCase; +import tests.support.DatabaseCreator; +import tests.support.Support_SQL; + +import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @TestTargetClass(Blob.class) -public class BlobTest extends TestCase { +public class BlobTest extends SQLiteTest { private static Blob testBlob = null; private byte[] blobInput= null; private static InputStream file = null; - - public BlobTest(String name) { - super(name); + private static Database db = null; + + private static Stmt st = null; + + public class MockBlob extends Blob { + public void finalize() { + try { + super.finalize(); + } catch (Throwable exception) { + fail("Test activity faild!"); + } + } } - protected void setUp() throws java.lang.Exception { + public void setUp() throws java.lang.Exception { super.setUp(); testBlob = new Blob(); + super.setUp(); + Support_SQL.loadDriver(); + db = new Database(); + db.open(dbFile.getPath(), 0); + + db.exec("create table B(id integer primary key, val blob)",null); + db.exec("insert into B values(1, zeroblob(128))", null); + db.exec("insert into B values(2, zeroblob(128))", null); + db.exec("insert into B values(3, zeroblob(128))", null); + // can not fill Blob with data at this point... /* File resources = Support_Resources.createTempFolder(); @@ -69,23 +97,58 @@ public class BlobTest extends TestCase { */ } - protected void tearDown() throws java.lang.Exception { - super.tearDown(); + public void tearDown() { + testBlob.close(); + super.tearDown(); } + /** + * @throws Exception + * @throws IOException * @tests Blob#Blob() */ + @TestTargets ( { @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "constructor test", + level = TestLevel.NOT_FEASIBLE, + notes = "db.open_blob is not supported also for Stmt, therefore cannot test Blobs", method = "Blob", args = {} + ), + @TestTargetNew( + level = TestLevel.NOT_FEASIBLE, + notes = "functional test", + method = "getOutputStream", + args = {} + ), + @TestTargetNew( + level = TestLevel.NOT_FEASIBLE, + notes = "functional test", + method = "getInputStream", + args = {} ) - public void _testBlob() { - Blob b = new Blob(); - assertNotNull(b); - //assertEquals(0, b.size); + }) + @KnownFailure("db.open_blob is not supported.") + public void testBlob() throws Exception, IOException { + byte[] b = new byte[4]; + byte[] b128 = new byte[128]; + for (int i = 0; i < b128.length; i++) { + b128[i] = (byte) i; + } + Blob blob = db.open_blob(dbFile.getPath(), "B", "val", 1, true); + try { + + OutputStream os = blob.getOutputStream(); + os.write(b128); + os.close(); + + InputStream is = blob.getInputStream(); + is.skip(96); + assertEquals(4,is.read(b)); + is.close(); + } finally { + blob.close(); + } } /** @@ -93,53 +156,32 @@ public class BlobTest extends TestCase { */ @TestTargetNew( level = TestLevel.NOT_FEASIBLE, - notes = "method test", + notes = "Can not be checked. Should be tested in DX test package.", method = "finalize", args = {} ) - public void _testFinalize() { - fail("Not yet implemented"); + public void testFinalize() { + } /** * @tests Blob.getInputStream() */ @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "method test", + level = TestLevel.PARTIAL_COMPLETE, + notes = "Exception test", method = "getInputStream", args = {} ) public void testGetInputStream() { InputStream in = testBlob.getInputStream(); - assertNotNull(in); + try { in.read(); - fail("Read operation unsupported"); + fail("Exception not thrown for invalid Blob."); } 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(); - } - */ + } } /** @@ -147,13 +189,13 @@ public class BlobTest extends TestCase { */ @TestTargetNew( level = TestLevel.COMPLETE, - notes = "method test", + notes = "Exception test", method = "getOutputStream", args = {} ) public void testGetOutputStream() { OutputStream out = testBlob.getOutputStream(); - assertNotNull(out); + try { out.write(null); fail("Write operation unsupported"); @@ -166,58 +208,28 @@ public class BlobTest extends TestCase { * @tests Blob#close() */ @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "method test", + level = TestLevel.SUFFICIENT, + notes = "not clear from spec what should happen when Blob is closed.", method = "close", args = {} ) - public void _testClose() { - try { - testBlob.close(); - testBlob.close(); - testBlob.getInputStream(); - //assertEquals(0, testBlob.size); - } catch (Throwable e) { - fail("Tests failed"); - } + @KnownFailure("Blob does not clean up inputStream.") + public void testClose() { + assertNotNull(testBlob); + + testBlob.close(); + // inputStream eithter null or some error occurs + try { + assertNull(testBlob.getInputStream()); + } catch (Throwable e) { + //ok } - - // 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 -// } -// } + try { + assertNull(testBlob.getOutputStream()); + } catch (Throwable e) { + //ok + } + + } } diff --git a/sql/src/test/java/tests/SQLite/DatabaseTest.java b/sql/src/test/java/tests/SQLite/DatabaseTest.java index 6cb2b4e..50eb6cc 100644 --- a/sql/src/test/java/tests/SQLite/DatabaseTest.java +++ b/sql/src/test/java/tests/SQLite/DatabaseTest.java @@ -16,6 +16,7 @@ package tests.SQLite; +import dalvik.annotation.KnownFailure; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; @@ -52,7 +53,9 @@ import SQLite.Trace; import SQLite.Vm; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.logging.Logger; @TestTargetClass(Database.class) public class DatabaseTest extends SQLiteTest { @@ -62,7 +65,7 @@ public class DatabaseTest extends SQLiteTest { */ // protected final File dbFile = new File("sqliteTest.db"); // -// private final String connectionURL = "jdbc:sqlite:/" + dbFile.getName(); +// private final String connectionURL = "jdbc:sqlite:/" + dbFile.getPath(); // // private final String classname = "SQLite.JDBCDriver"; // @@ -78,34 +81,37 @@ public class DatabaseTest extends SQLiteTest { private static final int numOfRecords = 30; - protected void setUp() throws java.lang.Exception { + public void setUp() throws java.lang.Exception { try { super.setUp(); -// Class.forName(classname).newInstance(); -// conn = DriverManager.getConnection(connectionURL); -// tracker = new ErrorTracker(); -// -// statement = conn.createStatement(); + assertNotNull("Could not establish DB connection",conn); + tracker = new ErrorTracker(); + + statement = conn.createStatement(); //Cleanup tables if necessary + DatabaseMetaData meta = conn.getMetaData(); + assertNotNull(meta); + if (meta != null) { 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 = conn.createStatement(); statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1); + statement.close(); try { db = new Database(); - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 0); db.busy_handler(null); } catch (Exception e) { - System.out.println("2: Error opening File: Dir "+dbFile.getPath()+" Name: "+dbFile.getName()); + System.out.println("2: Error opening File: Dir "+dbFile.getPath()+" Name: "+dbFile.getPath()); } catch (java.lang.Exception e) { System.err.println("Non SQLException "+e.getMessage()); } @@ -117,17 +123,18 @@ public class DatabaseTest extends SQLiteTest { } 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()); + System.err.println("Error closing DB "+dbFile.getPath()); } } // conn.close(); // dbFile.delete(); tracker.reset(); + super.tearDown(); } /** @@ -145,16 +152,16 @@ public class DatabaseTest extends SQLiteTest { try { db.close(); db2 = new Database(); - db2.open(dbFile.getName(), 0); + db2.open(dbFile.getPath(), 0); db2.close(); - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 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.open(dbFile.getPath(), 0); db2.close(); } catch (Exception e) { fail("Second Database object could not be created "+e.getMessage()); @@ -171,8 +178,7 @@ public class DatabaseTest extends SQLiteTest { method = "finalize", args = {} ) - public void _testFinalize() { - fail("Not yet implemented"); + public void testFinalize() { } /** @@ -187,7 +193,7 @@ public class DatabaseTest extends SQLiteTest { public void testOpen() { try { db.close(); - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 0); } catch (Exception e) { fail("Database object could not be opened: " + e.getMessage()); e.printStackTrace(); @@ -195,8 +201,8 @@ public class DatabaseTest extends SQLiteTest { // open second db while db1 still open Database db2 = new Database(); try { - db2.open(dbFile.getName(), 0); - db2.open(dbFile.getName(), 0); + db2.open(dbFile.getPath(), 0); + db2.open(dbFile.getPath(), 0); db2.close(); } catch (Exception e) { fail("Database object could not be opened: " + e.getMessage()); @@ -223,7 +229,7 @@ public class DatabaseTest extends SQLiteTest { * @tests Database#open_aux_file(String) */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "not supported", method = "open_aux_file", args = {java.lang.String.class} @@ -253,7 +259,7 @@ public class DatabaseTest extends SQLiteTest { e.printStackTrace(); } try { - db.open(dbFile.getName(),0); + db.open(dbFile.getPath(),0); db.exec("select * from AUX_TABLE", null); fail("Statement should fail"); } catch (Exception e) { @@ -281,7 +287,7 @@ public class DatabaseTest extends SQLiteTest { } catch (Exception e) { assertTrue(e.getMessage().equals("database already closed")); try { - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 0); } catch (Exception e1) { fail("Database object could not be reopened after 'close': " + e.getMessage()); @@ -295,7 +301,7 @@ public class DatabaseTest extends SQLiteTest { } catch (Exception e) { assertTrue(e.getMessage().equals("database already closed")); try { - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 0); } catch (Exception e1) { fail("Database object could not be reopened after 'close': " + e.getMessage()); @@ -398,17 +404,20 @@ public class DatabaseTest extends SQLiteTest { } /** + * @throws Exception * @tests {@link Database#interrupt()} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "How should this be tested?", + level = TestLevel.COMPLETE, + notes = "", method = "interrupt", args = {} ) - public void _testInterrupt() { + @KnownFailure("Reason for failure unknown: Database should be locked. " + + "Specification of interrupt is scarce.") + public void testInterrupt() throws Exception { ThreadPool threadPool = new ThreadPool(numThreads); - + // initialization ResultSet userTabs; try { @@ -428,41 +437,39 @@ public class DatabaseTest extends SQLiteTest { fail("Error initializing test " + e.getMessage()); e.printStackTrace(); } - + int id1 = numOfRecords - 3; - threadPool.runTask(createTask1(id1, dbFile.getName(), tracker)); + threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); + // should not be able to do any other insertions since task 1 holds lock int id2 = numOfRecords + 3; - threadPool.runTask(createTask2Interrupt(id2, dbFile.getName(), tracker)); + threadPool + .runTask(createTask2Interrupt(id2, dbFile.getPath(), tracker)); threadPool.join(); List<String> errors = tracker.getErrors(); - System.out.println("Last error: "+db.error_message()); + 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"); + assertEquals(errors.get(0), db + .error_string(Constants.SQLITE_LOCKED)); + for (String s : errors) { + Logger.global.info("INTERRUPT Error: " + s); + } + } else { - System.out.println("INTERRUPT: No error happened"); + fail("Should have one exception: database should be locked."); } - + // 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(); - } - - + db + .exec( + "delete from " + DatabaseCreator.TEST_TABLE1 + + " where 1", null); + db + .exec( + "delete from " + DatabaseCreator.TEST_TABLE3 + + " where 1", null); } @@ -475,23 +482,24 @@ public class DatabaseTest extends SQLiteTest { method = "changes", args = {} ) - public void _testChanges() { + @KnownFailure("Returns wrong number for updates: returns value > 1 for select.") + public void testChanges() { TableResult res = new TableResult(); try { assertTrue(db.changes() == 0); db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1 - + " VALUES(2, 5, 7)", null); + + " 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); + + " 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); + + " VALUES(8, 5, 7);", null); + db.exec("Update "+DatabaseCreator.SIMPLE_TABLE1+" set speed = 10;",null); + assertTrue(db.changes() > 2); } catch (Exception e) { fail("Could not get changes: " + e.getMessage()); e.printStackTrace(); @@ -499,24 +507,28 @@ public class DatabaseTest extends SQLiteTest { } /** + * @throws SQLException + * @throws Exception * @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.", + notes = "method test fails once in a while. Cannot be sure that exception is thrown every 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.", + notes = "method test fails once in a while. 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() { + @KnownFailure("method test fails once in a while. "+ + "Cannot be sure that exception is thrown in every test execution.") + public void testBusy_handler() throws SQLException, Exception { TestBusyHandler bh = new TestBusyHandler(); db.busy_handler(bh); int counter = 0; @@ -542,19 +554,21 @@ public class DatabaseTest extends SQLiteTest { e.printStackTrace(); } - + // try { // DatabaseCreator.fillTestTable1(conn, numOfRecords); // set to fail immediately if table is locked. // db.busy_handler(bh); // db.busy_timeout(0); + try { + conn.setAutoCommit(false); int id1 = numOfRecords - 3; - threadPool.runTask(createTask1(id1, dbFile.getName(), tracker)); + threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); int id2 = numOfRecords + 3; - threadPool.runTask(createTask2(id2, dbFile.getName(), tracker)); + threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); int oldID = 5; int newID = 100; - threadPool.runTask(createTask3(oldID, dbFile.getName(), newID, + threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID, tracker)); threadPool.join(); @@ -567,12 +581,11 @@ public class DatabaseTest extends SQLiteTest { System.out.println("Round 2 Error: "+s); } } else { - System.out.println("BUSY: No error happened"); + fail("No error happened"); } // reset - try{ db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", null); @@ -586,8 +599,8 @@ public class DatabaseTest extends SQLiteTest { // threadPool = new ThreadPool(numThreads); // -// threadPool.runTask(createTask1(id1, dbFile.getName(), tracker)); -// threadPool.runTask(createTask2(id2, dbFile.getName(), tracker)); +// threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); +// threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); // // threadPool.join(); // @@ -622,31 +635,29 @@ public class DatabaseTest extends SQLiteTest { // } catch (Exception e1) { // e2.printStackTrace(); // } - } - - try { + } finally { + conn.setAutoCommit(true); db.exec(DatabaseCreator.DROP_TABLE1, null); db.exec(DatabaseCreator.DROP_TABLE3, null); - } catch (Exception e) { - fail("Error in test cleanup" + e.getMessage()); - e.printStackTrace(); } - } /** + * @throws Exception + * @throws SQLException * @tests {@link Database#busy_timeout(int)} */ @TestTargetNew( level = TestLevel.NOT_FEASIBLE, - notes = "method test fails. Cannot be sure that exception is thrown wvery time.", + notes = "test fails. Cannot be sure that exception is thrown every time.", method = "busy_timeout", args = {int.class} ) - public void _testBusy_timeout() { + @KnownFailure("Database does not lock values") + public void testBusy_timeout() throws Exception, SQLException { int counter = 0; ThreadPool threadPool = new ThreadPool(numThreads); - + // initialization ResultSet userTabs; try { @@ -666,33 +677,35 @@ public class DatabaseTest extends SQLiteTest { fail("Error initializing test " + e.getMessage()); e.printStackTrace(); } - - + + + // test run try { + conn.setAutoCommit(false); + // 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)); + + threadPool.runTask(createTask2(id1, dbFile.getPath(), tracker)); int id2 = numOfRecords + 3; - threadPool.runTask(createTask2(id2, dbFile.getName(), tracker)); + threadPool.runTask(createTask1(id2, dbFile.getPath(), tracker)); int oldID = 5; int newID = 100; - threadPool.runTask(createTask3(oldID, dbFile.getName(), newID, + threadPool.runTask(createTask3(oldID, dbFile.getPath(), 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"); - } + assertTrue("No error occurred on DB but should have",errors.size() > 0); + assertEquals(errors.get(0), + db.error_string(Constants.SQLITE_LOCKED)); + assertEquals(errors.get(0), "database is locked"); + // reset db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", @@ -706,22 +719,19 @@ public class DatabaseTest extends SQLiteTest { tracker.reset(); threadPool = new ThreadPool(numThreads); - threadPool.runTask(createTask1(id1, dbFile.getName(), tracker)); - threadPool.runTask(createTask2(id2, dbFile.getName(), tracker)); + threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); + threadPool.runTask(createTask2(id2, dbFile.getPath(), 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!"); } @@ -735,24 +745,12 @@ public class DatabaseTest extends SQLiteTest { 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 { + } finally { + conn.setAutoCommit(true); + // cleanup db.exec(DatabaseCreator.DROP_TABLE1, null); db.exec(DatabaseCreator.DROP_TABLE3, null); - } catch (Exception e) { - fail("Error in test cleanup" + e.getMessage()); - e.printStackTrace(); } - } /** @@ -837,33 +835,33 @@ public class DatabaseTest extends SQLiteTest { * @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( + @TestTargetNew( level = TestLevel.COMPLETE, notes = "method test", - method = "toString", - clazz = TableResult.class, - args = {} + method = "get_table", + args = {java.lang.String.class, java.lang.String[].class, TableResult.class} ), - @TestTargetNew( + @TestTargetNew( level = TestLevel.COMPLETE, notes = "method test", - method = "types", + method = "toString", clazz = TableResult.class, - args = {String[].class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "method test", - method = "TableResult", - clazz = TableResult.class, - args = {} - ), + 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", @@ -871,20 +869,20 @@ public class DatabaseTest extends SQLiteTest { 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 = {} - ) + @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() { @@ -960,15 +958,16 @@ public class DatabaseTest extends SQLiteTest { args = {} ) public void testDbversion() { + String verNo = ""; try { - String verNo = db.dbversion(); + verNo = db.dbversion(); db.close(); assertEquals(db.dbversion(),"unknown"); - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 0); assertEquals(verNo,db.dbversion()); } catch (Exception e) { try { - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 0); } catch (Exception e1) { fail("error in db setup "+e.getMessage()); e.printStackTrace(); @@ -977,6 +976,8 @@ public class DatabaseTest extends SQLiteTest { e.printStackTrace(); } + assertTrue(Integer.parseInt(verNo.substring(0, 1))>= 3 ); + } /** @@ -990,10 +991,10 @@ public class DatabaseTest extends SQLiteTest { 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} + level = TestLevel.COMPLETE, + notes = "method test", + method = "create_function", + args = {java.lang.String.class, int.class, Function.class} ) }) public void testCreate_function() { @@ -1031,37 +1032,32 @@ public class DatabaseTest extends SQLiteTest { 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} + 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} + 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} + 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( @@ -1073,7 +1069,15 @@ public class DatabaseTest extends SQLiteTest { db.create_aggregate("myaggfunc", 1, aggFunction); db.function_type("myaggfunc", Constants.SQLITE_TEXT); db.exec("PRAGMA show_datatypes = on", null); + + assertFalse(aggFunction.functionCalled); + assertFalse(aggFunction.stepCalled); + assertFalse(aggFunction.lastStepCalled); db.exec("select myaggfunc(TEST.firstname) from TEST", t); + assertTrue(aggFunction.stepCalled); + assertTrue(aggFunction.lastStepCalled); + assertTrue(aggFunction.functionCalled); + assertEquals("James Fiona ",aggFunction.getAggValue()); db.exec("drop table TEST", null); } catch (Exception e) { @@ -1097,54 +1101,52 @@ public class DatabaseTest extends SQLiteTest { } /** + * @throws Exception * @tests {@link Database#function_type(String, int)} * This method does not make sense */ @TestTargetNew( level = TestLevel.COMPLETE, - notes = "method test fails.", + notes = "Method does not make sense: for functions, return type is already set.", method = "function_type", args = {java.lang.String.class, int.class} ) - public void _testFunction_type() { + public void testFunction_type() throws Exception { 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"); - + 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.SQLITE_NUMERIC); + res = db.get_table("select sin(res) from TEST WHERE res = " + + Double.toString(input)); + + String row[] = (String[]) res.rows.elementAt(0); + String val = row[0]; + assertTrue("double".equalsIgnoreCase(res.types[0])); + assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val))); + + // function determines return type: test that Double type is returned. + db.function_type("sin", Constants.SQLITE_BLOB); + Stmt s = db.prepare("select sin(res) from TEST WHERE res = ?"); + s.bind(1,input); + s.step(); + + res = db.get_table("select sin(res) from TEST WHERE res = " + + Double.toString(input)); + assertTrue("double".equalsIgnoreCase(res.types[0])); + row = (String[]) res.rows.elementAt(0); + val = row[0]; + assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val))); + - // 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(); - } + } @@ -1174,17 +1176,19 @@ public class DatabaseTest extends SQLiteTest { * @tests {@link Database#set_last_error(int)} */ @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "method test", + level = TestLevel.SUFFICIENT, + notes = "don't now which other errors may occur from black-box approach.", method = "set_last_error", args = {int.class} ) - public void _testSet_last_error() { + 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); + + try { + db.exec("sel from test;", null); + } catch (Exception e) { + assertEquals(Constants.SQLITE_ERROR,db.last_error()); + } } /** @@ -1237,6 +1241,7 @@ public class DatabaseTest extends SQLiteTest { } /** + * @throws UnsupportedEncodingException * @tests {@link Database#set_encoding(String)} * Method unsupported? -> tests fail */ @@ -1246,7 +1251,9 @@ public class DatabaseTest extends SQLiteTest { method = "set_encoding", args = {java.lang.String.class} ) - public void _testSet_encoding() { + @KnownFailure("ASCII encoding does not work: a UTF encoded val is returned. Spec is not sufficient. " + + "Might be that test impl is wrong or String constructor for the ASCII encoding.") + public void testSet_encoding() throws UnsupportedEncodingException { String input = "\u00bfMa\u00f1ana\u003f"; // ?Manana? TableResult res = new TableResult(); String refOutput = null; @@ -1271,46 +1278,15 @@ public class DatabaseTest extends SQLiteTest { 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" + // tests for different encoding schemes 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]); + String inputAsString = new String(encInput,charsetNames[i]); assertEquals(inputAsString, encOutput[0]); } catch (Exception e4) { fail("Error setting the encoding." + e4.getMessage()); @@ -1320,15 +1296,41 @@ public class DatabaseTest extends SQLiteTest { e2.printStackTrace(); } } + + // Default tests + try { + db.set_encoding("UTF-16"); + db.exec("select * from encodingTest;", res); + String[] encOutput1 = (String[]) res.rows.elementAt(0); + assertEquals("Got "+encOutput1[0]+" as UTF-16",input,encOutput1[0]); + + db.set_encoding("US-ASCII"); + db.exec("select * from encodingTest;", res); + String[] encOutput2 = (String[]) res.rows.elementAt(0); + assertEquals(new String(input.getBytes(),"US-ASCII"),encOutput2[0]); + } catch (Exception e) { + fail("Error setting the encoding." + e.getMessage()); + e.printStackTrace(); + } + + // DB teardown try { stat.close(); - db.exec("delete from encodingTest where 1", null); + db.exec("delete from encodingTest", null); // reset encoding } catch (Exception e3) { fail("Error in teardown of encoding environment"); e3.printStackTrace(); } + + // Default tests + try { + db.set_encoding(""); + fail("invalid input should fail"); + } catch (Exception e) { + //ok + } } @@ -1351,7 +1353,9 @@ public class DatabaseTest extends SQLiteTest { args = {int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} ) }) - public void _testSet_authorizer() { + @KnownFailure("Callback never made for authorization. "+ + "Results of private table are returned withouth furhter checks.") + public void testSet_authorizer() { TableResult resPriv = null; TableResult resPub = null; @@ -1372,22 +1376,22 @@ public class DatabaseTest extends SQLiteTest { // db.exec("delete from public_table where 1", null); // TableResult emptyPubTable = db.exec("select * from public"); - // set Authorizer (positive case) + // set Authorizer (positive case): denies private table 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); + assertTrue(cb.wasCalled()); + /* + 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()); } @@ -1420,10 +1424,12 @@ public class DatabaseTest extends SQLiteTest { public void testTrace() { String stmt = "create table TEST (res double);"; TestTrace t = new TestTrace(); + assertFalse(t.traceCalled); assertEquals(db.last_error(),Constants.SQLITE_OK); try { db.trace((Trace) t); db.exec(stmt,t); + assertTrue(t.traceCalled); assertEquals(t.getTrace(),stmt); } catch (Exception e) { fail("Error testing traces: "+e.getMessage()); @@ -1558,82 +1564,76 @@ public class DatabaseTest extends SQLiteTest { } /** + * @throws Exception + * @throws java.lang.Exception * @tests {@link Database#open_blob(String, String, String, long, boolean)} * unsupported */ - @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, - notes = "", + notes = "not supported", 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() { + ) + @KnownFailure("not supported") + public void testOpen_blob() throws Exception, java.lang.Exception { 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()); - } + byte[] in = {(byte) 1, (byte) 2, (byte) 3, (byte) 4}; + + // setup test input + db.exec("create table TEST (res blob)",null); + inStream = Class.forName(this.getClass().getName()).getResourceAsStream("/blob.c"); + assertNotNull(inStream); + // insert byte array in db try { - statement2 = db.prepare("insert into TEST(res) values (?)"); - statement2.bind(1,in); - statement2.step(); - statement2.close(); + 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()); + fail("Error happened inserting blob" + e.getMessage()); e.printStackTrace(); } - byte[] output = new byte[20]; + + // read from db + byte[] output = null; Blob blob; - try { - blob = db.open_blob(dbFile.getName(), "TEST", "res", 1, true); + + blob = db.open_blob(dbFile.getPath(), "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) + + int i = 0; + int outByte = 0; + byte[] out = new byte[4]; + while ((outByte = is.read()) > -1) { + out[i] = (byte) outByte; + i++; + } + is.close(); + + blob.close(); + + assertTrue(Arrays.equals(in, out)); + + //read from blob and compare values (default blob) 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(); - } - + Blob blob2 = db.open_blob(dbFile.getPath(), "TEST", "res", 2, true); + is = blob2.getInputStream(); + for (i = 0; i < 128; i++) { + assertEquals(0, is.read()); + } + is.close(); } /** @@ -1750,11 +1750,14 @@ public class DatabaseTest extends SQLiteTest { private StringBuffer buf = new StringBuffer(); + public boolean traceCalled = false; + public String getTrace() { return buf.toString(); } public void trace(String stmt) { + traceCalled = true; buf.append(stmt); } @@ -1784,9 +1787,9 @@ public class DatabaseTest extends SQLiteTest { public int authorize(int action, String arg1, String arg2, String arg3, String arg4) { - System.out.println("Authorize "+action+" "+arg1+" "+arg2+" "+arg3+" "+arg4+" "); + Logger.global.info("DB authorization callback "+action+" "+arg1+" "+arg2+" "+arg3+" "+arg4+" "); this.isAuthorizing = true; - if (action != Constants.SQLITE_SELECT || arg1 == "private_table" ) { + if (action != Constants.SQLITE_SELECT || arg1.contains("private_table")) { return Constants.SQLITE_DENY; } else { return Constants.SQLITE_OK; @@ -1933,14 +1936,12 @@ public class DatabaseTest extends SQLiteTest { + ", '" + value + "', " + id + ", " + id + ")"; db.exec(insertQuery, null); } catch (Exception e) { - // errorTracker.registerException(this, e); - db.interrupt(); - + errorTracker.registerException(this, e); try { + db.interrupt(); db.exec("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1 + " WHERE id=" + id, null); } catch (Exception e1) { - errorTracker.reset(); errorTracker.registerException(this, e1); } } diff --git a/sql/src/test/java/tests/SQLite/ExceptionTest.java b/sql/src/test/java/tests/SQLite/ExceptionTest.java index cc37c2a..fe86e8f 100644 --- a/sql/src/test/java/tests/SQLite/ExceptionTest.java +++ b/sql/src/test/java/tests/SQLite/ExceptionTest.java @@ -16,24 +16,26 @@ package tests.SQLite; +import SQLite.Database; import SQLite.Exception; +import dalvik.annotation.TestTargetClass; 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); - } +@TestTargetClass(SQLite.Exception.class) +public class ExceptionTest extends SQLiteTest { + + private Database db = null; - protected void setUp() throws java.lang.Exception { + public void setUp() throws java.lang.Exception { super.setUp(); + db = new Database(); } - - protected void tearDown() throws java.lang.Exception { + + public void tearDown() { super.tearDown(); } @@ -41,13 +43,18 @@ public class ExceptionTest extends TestCase { * @tests {@link Exception#Exception(String)} */ @TestTargetNew( - level = TestLevel.TODO, + level = TestLevel.COMPLETE, notes = "constructor test", method = "Exception", args = {java.lang.String.class} ) public void testException() { - fail("not yet implemented"); + try { + db.open(dbFile.getName(), 0); + } catch (Exception e) { + assertNotNull(e); + assertNotNull(e.getMessage()); + } } } diff --git a/sql/src/test/java/tests/SQLite/FunctionContextTest.java b/sql/src/test/java/tests/SQLite/FunctionContextTest.java index e07d7ca..1bb5cf5 100644 --- a/sql/src/test/java/tests/SQLite/FunctionContextTest.java +++ b/sql/src/test/java/tests/SQLite/FunctionContextTest.java @@ -16,7 +16,14 @@ package tests.SQLite; +import SQLite.Database; +import SQLite.Exception; +import SQLite.Function; import SQLite.FunctionContext; +import SQLite.Stmt; +import SQLite.TableResult; +import dalvik.annotation.AndroidOnly; +import dalvik.annotation.KnownFailure; import dalvik.annotation.TestTargets; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; @@ -24,133 +31,422 @@ import dalvik.annotation.TestTargetClass; import junit.framework.TestCase; +import java.io.UnsupportedEncodingException; +import java.sql.SQLException; +import java.sql.Statement; + +import tests.support.DatabaseCreator; + @TestTargetClass(FunctionContext.class) -public class FunctionContextTest extends TestCase { +public class FunctionContextTest extends SQLiteTest { - /** - * @param name - */ - public FunctionContextTest(String name) { - super(name); - } + private Database db = null; - /* (non-Javadoc) - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws java.lang.Exception { + public void setUp() throws java.lang.Exception { + Statement st = null; 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"); + db = new Database(); + db.open(dbFile.getPath(), 0); + st = conn.createStatement(); + st.execute(DatabaseCreator.CREATE_TABLE2); + st.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1); + st.close(); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ - protected void tearDown() throws java.lang.Exception { + public void tearDown() { super.tearDown(); } /** * Test method for {@link SQLite.FunctionContext#set_result(java.lang.String)}. + * @throws Exception */ @TestTargetNew( - level = TestLevel.TODO, - notes = "method test", + level = TestLevel.SUFFICIENT, + notes = "indirectly tested invoking function", method = "set_result", args = {java.lang.String.class} ) - public void testSet_resultString() { - fail("Not yet implemented"); + public void testSet_resultString() throws Exception { + TestFCString testString = new TestFCString(); + db.exec("insert into " + DatabaseCreator.TEST_TABLE2 + + " (ftext) values ('TestInput')", null); + db.create_function("test", 1, testString); + TableResult res = db.get_table("select test(ftext) from " + + DatabaseCreator.TEST_TABLE2); + String row[] = (String[]) res.rows.elementAt(0); + String val = row[0]; + + assertEquals("TestInput", val); } /** * Test method for {@link SQLite.FunctionContext#set_result(int)}. + * @throws Exception */ @TestTargetNew( - level = TestLevel.TODO, + level = TestLevel.SUFFICIENT, notes = "method test", method = "set_result", args = {int.class} ) - public void testSet_resultInt() { - fail("Not yet implemented"); + public void testSet_resultInt() throws Exception { + TestFCInt testInt = new TestFCInt(); + db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 + + " values (1,'" + testInt.intVal + "',3)", null); + db.create_function("testInt", 1, testInt); + TableResult res = db.get_table("select testInt(speed) from " + + DatabaseCreator.SIMPLE_TABLE1); + String row[] = (String[]) res.rows.elementAt(0); + String val = row[0]; + + assertEquals(testInt.intVal, Integer.parseInt(val)); } /** * Test method for {@link SQLite.FunctionContext#set_result(double)}. + * @throws Exception */ @TestTargetNew( - level = TestLevel.TODO, - notes = "method test", + level = TestLevel.SUFFICIENT, + notes = "indirectly tested", method = "set_result", args = {double.class} ) - public void testSet_resultDouble() { - fail("Not yet implemented"); + public void testSet_resultDouble() throws Exception { + SinFunc testD = new SinFunc(); + db.exec("insert into " + DatabaseCreator.TEST_TABLE2 + + " (fdouble) values (" + testD.testDouble + ")", null); + db.create_function("testDouble", 1, testD); + TableResult res = db.get_table("select testDouble(fdouble) from " + + DatabaseCreator.TEST_TABLE2); + String row[] = (String[]) res.rows.elementAt(0); + String val = row[0]; + + assertEquals(testD.testDouble, Double.parseDouble(val)); + + assertTrue(testD.functionCalled); } /** * Test method for {@link SQLite.FunctionContext#set_error(java.lang.String)}. + * @throws Exception */ @TestTargetNew( - level = TestLevel.TODO, + level = TestLevel.COMPLETE, notes = "method test", method = "set_error", args = {java.lang.String.class} ) - public void testSet_error() { - fail("Not yet implemented"); + public void testSet_error() throws Exception { + TestFCError testError = new TestFCError(); + SinFunc testD = new SinFunc(); + db.exec("insert into " + DatabaseCreator.TEST_TABLE2 + + " (fdouble) values (" + testD.testDouble + ")", null); + db.create_function("testError", 1, testError); + + try { + TableResult res = db.get_table("select testError(fdouble) from " + + DatabaseCreator.TEST_TABLE2); + fail("Should get Exception"); + } catch (Exception e) { + assertEquals("error in step", e.getMessage()); + } + + assertFalse(testD.functionCalled); } /** * Test method for {@link SQLite.FunctionContext#set_result(byte[])}. + * @throws Exception + * @throws UnsupportedEncodingException */ @TestTargetNew( - level = TestLevel.TODO, + level = TestLevel.COMPLETE, notes = "method test", method = "set_result", args = {byte[].class} ) - public void testSet_resultByteArray() { - fail("Not yet implemented"); + public void testSet_resultByteArray() throws Exception, UnsupportedEncodingException { + Stmt st = null; + TestFCByteArray testBinArrayFnc = new TestFCByteArray(); + String expected = ""; + expected = "X'" + getHexString(testBinArrayFnc.byteVal) + "'"; + + // setup + db.exec("create table testBinaryData (binVal BINARY) ;", null); + + try { + st = db.prepare("insert into testBinaryData values (?)"); + st.bind(1, testBinArrayFnc.byteVal); + st.step(); + + + db.create_function("testBinArray", 1, testBinArrayFnc); + TableResult res = db + .get_table("select testBinArray(binVal) from testBinaryData"); + + String row[] = (String[]) res.rows.elementAt(0); + String val = row[0]; + + assertTrue(expected.equalsIgnoreCase(val)); + + assertTrue(testBinArrayFnc.functionCalled); + + } finally { + //teardown + db.exec("drop table testBinaryData;", null); + } } /** * Test method for {@link SQLite.FunctionContext#set_result_zeroblob(int)}. + * @throws Exception + * @throws UnsupportedEncodingException */ @TestTargetNew( - level = TestLevel.TODO, + level = TestLevel.COMPLETE, notes = "method test", method = "set_result_zeroblob", args = {int.class} ) - public void testSet_result_zeroblob() { - fail("Not yet implemented"); + public void testSet_result_zeroblob() throws Exception, + UnsupportedEncodingException { + Stmt st = null; + TestFCZeroBlob testZeroBlobFnc = new TestFCZeroBlob(); + byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3}; + + + // setup + db.exec("create table testBinaryData (binVal BINARY) ;", null); + + try { + st = db.prepare("insert into testBinaryData values (?)"); + st.bind(1, byteVal); + st.step(); + + + db.create_function("testZeroBlob", 0, testZeroBlobFnc); + TableResult res = db + .get_table("select testZeroBlob() from testBinaryData"); + TableResult res2 = db.get_table("select zeroblob(" + + testZeroBlobFnc.numBytes + ") from testBinaryData"); + + String row[] = (String[]) res.rows.elementAt(0); + String val = row[0]; + + assertNotNull(val); + + assertEquals(((String[]) res2.rows.elementAt(0))[0], val); + assertTrue(testZeroBlobFnc.functionCalled); + + } finally { + // teardown + db.exec("drop table if exists testBinaryData;", null); + } } /** * Test method for {@link SQLite.FunctionContext#count()}. + * @throws SQLException + * @throws Exception */ @TestTargetNew( - level = TestLevel.TODO, + level = TestLevel.COMPLETE, notes = "method test", method = "count", args = {} ) - public void testCount() { - fail("Not yet implemented"); + @AndroidOnly("Test Method results in a segmentation fault.") + public void testCount() throws SQLException, Exception { + TestFCCount countTest = new TestFCCount(); + int inputCount = 10; + + assertFalse(countTest.functionCalled); + + DatabaseCreator.fillTestTable2(conn, inputCount); + db.create_function("testCount", 0, countTest); + // the invokation of testCount leads to a Segmentation fault + /* + TableResult res = db + .get_table("select testCount() from "+DatabaseCreator.TEST_TABLE2); + + String row[] = (String[]) res.rows.elementAt(0); + String val = row[0]; + + assertTrue(countTest.functionCalled); + assertEquals(inputCount,Integer.parseInt(val)); + */ + + } + + class TestFCError implements Function { + public boolean functionCalled = false; + public String errorMsg = "FunctionError"; + + public void function(FunctionContext fc, String args[]) { + functionCalled = true; + fc.set_error(errorMsg); + } + + public void last_step(FunctionContext fc) { + // TODO Auto-generated method stub + + } + + public void step(FunctionContext fc, String[] args) { + // TODO Auto-generated method stub + + } + } + + class TestFCCount implements Function { + public boolean functionCalled = false; + public int noOfRows = 0; + + public void function(FunctionContext fc, String args[]) { + functionCalled = true; + noOfRows = fc.count(); + fc.set_result(noOfRows); + } + + public void last_step(FunctionContext fc) { + // TODO Auto-generated method stub + + } + + public void step(FunctionContext fc, String[] args) { + // TODO Auto-generated method stub + + } + } + + class TestFCZeroBlob implements Function { + public int numBytes = 16; + public boolean functionCalled = false; + + public void function(FunctionContext fc, String args[]) { + functionCalled = true; + fc.set_result_zeroblob(numBytes); + } + + public void last_step(FunctionContext fc) { + // TODO Auto-generated method stub + + } + + public void step(FunctionContext fc, String[] args) { + // TODO Auto-generated method stub + + } + } + + class TestFCString implements Function { + public String testString = "TestString"; + public boolean functionCalled; + + public void function(FunctionContext fc, String args[]) { + assertNotNull(args); + functionCalled = true; + fc.set_result(args[0]); + } + + public void last_step(FunctionContext fc) { + // TODO Auto-generated method stub + + } + + public void step(FunctionContext fc, String[] args) { + // TODO Auto-generated method stub + + } + } + + class TestFCInt implements Function { + public int intVal = Integer.MAX_VALUE; + public boolean functionCalled; + + public void function(FunctionContext fc, String args[]) { + assertNotNull(args); + functionCalled = true; + fc.set_result(Integer.parseInt(args[0])); + } + + public void last_step(FunctionContext fc) { + // TODO Auto-generated method stub + + } + + public void step(FunctionContext fc, String[] args) { + // TODO Auto-generated method stub + + } + } + + class TestFCByteArray implements Function { + public byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3}; + public boolean functionCalled; + + public void function(FunctionContext fc, String args[]) { + assertNotNull(args); + functionCalled = true; + fc.set_result(args[0].getBytes()); + } + + public void last_step(FunctionContext fc) { + // TODO Auto-generated method stub + + } + + public void step(FunctionContext fc, String[] args) { + // TODO Auto-generated method stub + + } + } + + class SinFunc implements Function { + + public Double testDouble = 3.0; + public boolean functionCalled = false; + + public void function(FunctionContext fc, String args[]) { + Double d = new Double(args[0]); + functionCalled = true; + fc.set_result(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 + + } + } + + static final byte[] HEX_CHAR_TABLE = { + (byte)'0', (byte)'1', (byte)'2', (byte)'3', + (byte)'4', (byte)'5', (byte)'6', (byte)'7', + (byte)'8', (byte)'9', (byte)'a', (byte)'b', + (byte)'c', (byte)'d', (byte)'e', (byte)'f' + }; + + public static String getHexString(byte[] raw) + throws UnsupportedEncodingException { + byte[] hex = new byte[2 * raw.length]; + int index = 0; + + for (byte b : raw) { + int v = b & 0xFF; + hex[index++] = HEX_CHAR_TABLE[v >>> 4]; + hex[index++] = HEX_CHAR_TABLE[v & 0xF]; + } + return new String(hex, "ASCII"); } } diff --git a/sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java b/sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java index e872182..ed2c0b3 100644 --- a/sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java +++ b/sql/src/test/java/tests/SQLite/JDBCDriverFunctionalTest.java @@ -1,117 +1,110 @@ -/*
- * 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;
- }
-
-
-}
+/* + * 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"; + + /** + * 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 + public 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("java.io.tmpdir 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 index a252cd4..c6fd677 100644 --- a/sql/src/test/java/tests/SQLite/JDBCDriverTest.java +++ b/sql/src/test/java/tests/SQLite/JDBCDriverTest.java @@ -33,17 +33,9 @@ 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; diff --git a/sql/src/test/java/tests/SQLite/SQLiteTest.java b/sql/src/test/java/tests/SQLite/SQLiteTest.java index 195b013..0463dcb 100644 --- a/sql/src/test/java/tests/SQLite/SQLiteTest.java +++ b/sql/src/test/java/tests/SQLite/SQLiteTest.java @@ -23,13 +23,14 @@ import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.util.logging.Logger; public class SQLiteTest extends TestCase { public static Connection conn; public static File dbFile = null; - public void setup() { - String tmp = System.getProperty("ctsdir"); + public void setUp() throws Exception { + String tmp = System.getProperty("java.io.tmpdir"); File tmpDir = new File(tmp); try { if (tmpDir.isDirectory()) { @@ -41,16 +42,13 @@ public class SQLiteTest extends TestCase { 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()); + if (!dbFile.exists()) { + Logger.global.severe("DB file could not be created. Tests can not be executed."); + } else { conn = DriverManager.getConnection("jdbc:sqlite:/" + dbFile.getPath()); - assertNotNull("Connection created ",conn); - + } + assertNotNull("Error creating connection",conn); } catch (IOException e) { System.out.println("Problem creating test file in " + tmp); } catch (SQLException e) { diff --git a/sql/src/test/java/tests/SQLite/StmtTest.java b/sql/src/test/java/tests/SQLite/StmtTest.java index fc611db..20f8221 100644 --- a/sql/src/test/java/tests/SQLite/StmtTest.java +++ b/sql/src/test/java/tests/SQLite/StmtTest.java @@ -16,21 +16,20 @@ package tests.SQLite; +import SQLite.Constants; import SQLite.Database; import SQLite.Exception; import SQLite.Stmt; import SQLite.TableResult; -import dalvik.annotation.TestTargets; +import dalvik.annotation.AndroidOnly; 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; @@ -41,21 +40,71 @@ public class StmtTest extends SQLiteTest { private static Stmt st = null; -// private final File dbFile = new File("sqliteTest.db"); + private static final String createAllTypes = + "create table type (" + - protected void setUp() throws java.lang.Exception { + " BoolVal BOOLEAN," + " IntVal INT," + " LongVal LONG," + + " Bint BIGINT," + " Tint TINYINT," + " Sint SMALLINT," + + " Mint MEDIUMINT, " + + + " IntegerVal INTEGER, " + " RealVal REAL, " + + " DoubleVal DOUBLE, " + " FloatVal FLOAT, " + + " DecVal DECIMAL, " + + + " NumVal NUMERIC, " + " charStr CHAR(20), " + + " dateVal DATE, " + " timeVal TIME, " + " TS TIMESTAMP, " + + + + " DT DATETIME, " + " TBlob TINYBLOB, " + " BlobVal BLOB, " + + " MBlob MEDIUMBLOB, " + " LBlob LONGBLOB, " + + + " TText TINYTEXT, " + " TextVal TEXT, " + + " MText MEDIUMTEXT, " + " LText LONGTEXT, " + + + " MaxLongVal BIGINT, MinLongVal BIGINT, "+ + + " validURL URL, invalidURL URL "+ + + ");"; + + static final String insertAllTypes = + "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint," + + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal," + + "NumVal, charStr, dateVal, timeVal, TS," + + "DT, TBlob, BlobVal, MBlob, LBlob," + + "TText, TextVal, MText, LText, MaxLongVal, MinLongVal," + + " validURL, invalidURL" + + ") " + + "values (1, -1, 22, 2, 33," + + "3, 1, 2, 3.9, 23.2, 33.3, 44," + + "5, 'test string', '1799-05-26', '12:35:45', '2007-10-09 14:28:02.0'," + + "'1221-09-22 10:11:55', 1, 2, 3, 4," + + "'Test text message tiny', 'Test text'," + + " 'Test text message medium', 'Test text message long', " + + Long.MAX_VALUE+", "+Long.MIN_VALUE+", " + + "null, null "+ + ");"; + + static final String allTypesTable = "type"; + + public void setUp() throws java.lang.Exception { super.setUp(); Support_SQL.loadDriver(); db = new Database(); - db.open(dbFile.getName(), 0); + db.open(dbFile.getPath(), 0); db.exec(DatabaseCreator.CREATE_TABLE_SIMPLE1, null); - DatabaseCreator.fillSimpleTable1(Support_SQL.getConnection()); - - st = new Stmt(); + DatabaseCreator.fillSimpleTable1(conn); + } public void tearDown() { - super.tearDown(); + if (st != null) { + try { + st.close(); + } catch (Exception e) { + + } + } try { db.close(); Connection con = Support_SQL.getConnection(); @@ -66,7 +115,7 @@ public class StmtTest extends SQLiteTest { } catch (SQLException e) { fail("SQLException in tearDown: "+e.getMessage()); } - + super.tearDown(); } /** @@ -78,7 +127,7 @@ public class StmtTest extends SQLiteTest { method = "Stmt", args = {} ) - public void _testStmt() { + public void testStmt() { Stmt st = new Stmt(); assertNotNull(st); try { @@ -107,8 +156,8 @@ public class StmtTest extends SQLiteTest { method = "finalize", args = {} ) - public void _testFinalize() { - fail("Not yet implemented"); + public void testFinalize() { + } /** @@ -215,16 +264,40 @@ public class StmtTest extends SQLiteTest { } /** + * @throws Exception * @tests {@link Stmt#reset()} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, + level = TestLevel.TODO, notes = "method test", method = "reset", args = {} ) - public void _testReset() { - fail("Not yet implemented"); + @AndroidOnly("Tableresult is not cleared when resetting statement: "+ + "Either complete spec or change implementation accordingly.") + public void testReset() throws Exception { + db.exec("create table TEST (res integer not null)", null); + + st = db.prepare("insert into TEST values (:one);"); + st.bind(1, 1); + st.step(); + + // verify that parameter is still bound + st.reset(); + assertEquals(1,st.bind_parameter_count()); + st.step(); + + TableResult count = db.get_table("select count(*) from TEST where res=1", null); + + String[] row0 = (String[]) count.rows.elementAt(0); + assertEquals(2, Integer.parseInt(row0[0])); + + //Verify that rest (tableResult) is cleared + st = db.prepare("select * from TEST;"); + st.step(); + assertEquals(1, st.column_count()); + st.reset(); + assertEquals(0,st.column_count()); } /** @@ -578,7 +651,7 @@ public class StmtTest extends SQLiteTest { * @tests {@link Stmt#bind_zeroblob(int, int)} */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.NOT_FEASIBLE, notes = "not supported", method = "bind_zeroblob", args = {int.class, int.class} @@ -720,16 +793,47 @@ public class StmtTest extends SQLiteTest { } /** + * @throws Exception * @tests {@link Stmt#column_int(int)} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, + level = TestLevel.COMPLETE, notes = "method test", method = "column_int", args = {int.class} ) - public void _testColumn_int() { - fail("Not yet implemented"); + public void testColumn_int() throws Exception { + db.exec(createAllTypes, null); + db.exec(insertAllTypes, null); + + int columnObjectCastFromLong; + Object columnObject = null; + int intColumn = 0; + String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; + + st = db.prepare(selectStmt); + st.step(); + // select 'speed' value + 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); + assertEquals(10,stSpeed); + + selectStmt = "select TextVal from "+allTypesTable; + + st = db.prepare(selectStmt); + st.step(); + // select double value + try { + st.column_int(0); + } catch (Exception e) { + //ok + } } /** @@ -747,7 +851,6 @@ public class StmtTest extends SQLiteTest { 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); @@ -779,75 +882,219 @@ public class StmtTest extends SQLiteTest { } /** + * @throws Exception * @tests {@link Stmt#column_double(int)} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, + level = TestLevel.COMPLETE, notes = "method test", method = "column_double", args = {int.class} ) - public void _testColumn_double() { - fail("Not yet implemented"); + public void testColumn_double() throws Exception { + db.exec(createAllTypes, null); + db.exec(insertAllTypes, null); + + Object columnObject = null; + double doubleColumn = 0; + double actualVal = 23.2; + String selectStmt = "select DoubleVal from "+allTypesTable; + + st = db.prepare(selectStmt); + st.step(); + // select double value + doubleColumn = st.column_double(0); + assertNotNull(doubleColumn); + + assertTrue("DOUBLE".equalsIgnoreCase(st.column_decltype(0))); + assertNotNull(doubleColumn); + assertEquals( actualVal, doubleColumn); + + // Exception test + selectStmt = "select dateVal from "+allTypesTable; + + st = db.prepare(selectStmt); + st.step(); + // select double value + try { + st.column_double(0); + } catch (Exception e) { + //ok + } + + } /** + * @throws Exception * @tests {@link Stmt#column_bytes(int)} */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.NOT_FEASIBLE, notes = "not supported", method = "column_bytes", args = {int.class} ) - public void testColumn_bytes() { + public void testColumn_bytes() throws Exception { + + db.exec("create table B(id integer primary key, val blob)",null); + db.exec("insert into B values(1, zeroblob(128))", null); + st = db.prepare("select val from B where id = 1"); + assertTrue(st.step()); try { - st.column_bytes(1); + st.column_bytes(0); } catch (Exception e) { assertEquals("unsupported", e.getMessage()); } } /** + * @throws Exception * @tests {@link Stmt#column_string(int)} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, + level = TestLevel.COMPLETE, notes = "method test", method = "column_string", args = {int.class} ) - public void _testColumn_string() { - fail("Not yet implemented"); + public void testColumn_string() throws Exception { + db.exec(createAllTypes, null); + db.exec(insertAllTypes, null); + + Object columnObject = null; + String stringColumn = ""; + String actualVal = "test string"; + String selectStmt = "select charStr from "+allTypesTable; + + st = db.prepare(selectStmt); + st.step(); + // select string value + stringColumn = st.column_string(0); + assertNotNull(stringColumn); + + assertTrue("CHAR(20)".equalsIgnoreCase(st.column_decltype(0))); + assertNotNull(stringColumn); + assertEquals( actualVal, stringColumn); + + // Exception test + selectStmt = "select DoubleVal from "+allTypesTable; + + st = db.prepare(selectStmt); + st.step(); + // select double value + try { + st.column_string(0); + } catch (Exception e) { + //ok + } } /** + * @throws Exception * @tests {@link Stmt#column_type(int)} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, + level = TestLevel.SUFFICIENT, notes = "method test", method = "column_type", args = {int.class} ) - public void _testColumn_type() { - fail("Not yet implemented"); + @AndroidOnly("For numeric, float and blob wrong type is returned") + public void testColumn_type() throws Exception { + db.exec(createAllTypes, null); + db.exec(insertAllTypes, null); + st = db.prepare("select * from " + allTypesTable); + st.step(); + + // Exception test + try { + st.column_type(100); + } catch (Exception e) { + // ok + } + + /* + Dictionary + + public static final int SQLITE_INTEGER = 1; + public static final int SQLITE_FLOAT = 2; + public static final int SQLITE_BLOB = 4; + public static final int SQLITE_NULL = 5; + public static final int SQLITE3_TEXT = 3; + public static final int SQLITE_NUMERIC = -1; + */ + + assertEquals(Constants.SQLITE3_TEXT, st.column_type(23)); // ok TEXT + assertEquals(Constants.SQLITE3_TEXT, st.column_type(13)); // CHAR(20) + + assertEquals(Constants.SQLITE_FLOAT, st.column_type(8)); + assertEquals(Constants.SQLITE_FLOAT, st.column_type(9)); + assertEquals(Constants.SQLITE_FLOAT, st.column_type(10)); // FLOAT + + for (int i = 0; i < 8; i++) { + assertEquals("Expected Integer at position " + i, + Constants.SQLITE_INTEGER, st.column_type(i)); + } + + assertEquals(Constants.SQLITE_NULL, st.column_type(28)); + assertEquals(Constants.SQLITE_NULL, st.column_type(29)); + + // Failing tests + assertTrue("NUMERIC".equalsIgnoreCase(st.column_decltype(12))); + assertEquals(Constants.SQLITE_NUMERIC, st.column_type(12)); // NUMERIC + // -> got + // INTEGER + + assertTrue("FLOAT".equalsIgnoreCase(st.column_decltype(11))); + assertEquals(Constants.SQLITE_FLOAT, st.column_type(11)); // FLOAT -> + // got INTEGER + assertTrue("BLOB".equalsIgnoreCase(st.column_decltype(19))); + assertEquals(Constants.SQLITE_BLOB, st.column_type(19)); // Blob got + // INTEGER + } /** + * @throws Exception * @tests {@link Stmt#column_count() )} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, + level = TestLevel.COMPLETE, notes = "method test", method = "column_count", args = {} ) - public void _testColumn_count() { - fail("Not yet implemented"); + @AndroidOnly("Wrong value is returned in case of a prepared statment to "+ + "which a '*' bound ") + public void testColumn_count() throws Exception { + + String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; + st = db.prepare(selectStmt); + + assertEquals(3, st.column_count()); + + st.step(); + int columnCount = st.column_count(); + assertNotNull(columnCount); + assertEquals( 3, columnCount); + + // actual prepared statement + selectStmt = "select ? from "+DatabaseCreator.SIMPLE_TABLE1; + st = db.prepare(selectStmt); + + assertEquals(3, st.column_count()); + + st.bind(1, "*"); + st.step(); + columnCount = st.column_count(); + assertNotNull(columnCount); + assertEquals( 3, columnCount); + } /** + * @throws Exception * @tests {@link Stmt#column(int) )} */ @TestTargetNew( @@ -856,7 +1103,7 @@ public class StmtTest extends SQLiteTest { method = "column", args = {int.class} ) - public void testColumn() { + public void testColumn() throws Exception { Object columnObject = null; int columnObjectCastFromLong; int intColumn = 0; @@ -905,19 +1152,25 @@ public class StmtTest extends SQLiteTest { */ @TestTargetNew( level = TestLevel.NOT_FEASIBLE, - notes = "method test", + notes = "not supported", method = "column_table_name", args = {int.class} ) - public void _testColumn_table_name() { - fail("Not yet implemented"); + public void testColumn_table_name() { + try { + st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); + String name = st.column_table_name(1); + fail("Function is now supported."); + } catch (Exception e) { + assertEquals("unsupported", e.getMessage()); + } } /** * @tests {@link Stmt#column_database_name(int)} */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.NOT_FEASIBLE, notes = "not supported", method = "column_database_name", args = {int.class} @@ -927,7 +1180,7 @@ public class StmtTest extends SQLiteTest { st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 + " values (:one,:two,:three)"); String name = st.column_database_name(1); - fail("test fails"); + fail("Function is now supported."); } catch (Exception e) { assertEquals("unsupported", e.getMessage()); } @@ -935,16 +1188,66 @@ public class StmtTest extends SQLiteTest { } /** + * @throws Exception * @tests {@link Stmt#column_decltype(int)} */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, + level = TestLevel.SUFFICIENT, notes = "method test", method = "column_decltype", args = {int.class} ) - public void _testColumn_decltype() { - fail("Not yet implemented"); + public void testColumn_decltype() throws Exception { + db.exec(createAllTypes, null); + db.exec(insertAllTypes, null); + st = db.prepare("select * from " + allTypesTable); + st.step(); + + // Exception test + try { + st.column_decltype(100); + } catch (Exception e) { + // ok + } + + assertTrue(st.column_decltype(0), "BOOLEAN".equalsIgnoreCase(st + .column_decltype(0))); + assertTrue(st.column_decltype(1), "INT".equalsIgnoreCase(st + .column_decltype(1))); + assertTrue(st.column_decltype(2), "LONG".equalsIgnoreCase(st + .column_decltype(2))); + assertTrue(st.column_decltype(3), "BIGINT".equalsIgnoreCase(st + .column_decltype(3))); + assertTrue(st.column_decltype(4), "TINYINT".equalsIgnoreCase(st + .column_decltype(4))); + assertTrue(st.column_decltype(5), "SMALLINT".equalsIgnoreCase(st + .column_decltype(5))); + assertTrue(st.column_decltype(6), "MEDIUMINT".equalsIgnoreCase(st + .column_decltype(6))); + assertTrue(st.column_decltype(7), "INTEGER".equalsIgnoreCase(st + .column_decltype(7))); + assertTrue(st.column_decltype(8), "REAL".equalsIgnoreCase(st + .column_decltype(8))); + assertTrue(st.column_decltype(9), "DOUBLE".equalsIgnoreCase(st + .column_decltype(9))); + assertTrue(st.column_decltype(10), "FLOAT".equalsIgnoreCase(st + .column_decltype(10))); + assertTrue(st.column_decltype(11), "DECIMAL".equalsIgnoreCase(st + .column_decltype(11))); + assertTrue(st.column_decltype(12), "NUMERIC".equalsIgnoreCase(st + .column_decltype(12))); + assertTrue(st.column_decltype(13), "CHAR(20)".equalsIgnoreCase(st + .column_decltype(13))); + + assertTrue(st.column_decltype(19), "BLOB".equalsIgnoreCase(st + .column_decltype(19))); + + assertTrue(st.column_decltype(23), "TEXT".equalsIgnoreCase(st + .column_decltype(23))); + assertTrue(st.column_decltype(28), "URL".equalsIgnoreCase(st + .column_decltype(28))); + assertTrue(st.column_decltype(29), "URL".equalsIgnoreCase(st + .column_decltype(29))); } /** @@ -952,11 +1255,17 @@ public class StmtTest extends SQLiteTest { */ @TestTargetNew( level = TestLevel.NOT_FEASIBLE, - notes = "method test", + notes = "not supported", method = "column_origin_name", args = {int.class} ) - public void _testColumn_origin_name() { - fail("Not yet implemented"); + public void testColumn_origin_name() { + try { + st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); + String name = st.column_origin_name(1); + fail("Function is now supported."); + } catch (Exception e) { + assertEquals("unsupported", e.getMessage()); + } } } diff --git a/sql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java b/sql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java index 8476915..fe7b227 100755 --- a/sql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java +++ b/sql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java @@ -15,7 +15,6 @@ */ package tests.java.sql; -import dalvik.annotation.BrokenTest; import dalvik.annotation.KnownFailure; import dalvik.annotation.TestTargets; import dalvik.annotation.TestLevel; @@ -933,12 +932,12 @@ public class DatabaseMetaDataTest extends TestCase { * @tests java.sql.DatabaseMetaData#getNumericFunctions() */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "Test fails. Not implemented correctly. SQLException checking test fails", method = "getNumericFunctions", args = {} ) - @BrokenTest("Not supported feature, Ticket 98. Broken because "+ + @KnownFailure("Not supported feature, Ticket 98. Broken because "+ "NUMERIC_FUNCTIONS not complete. When fixed change to @KnownFailure") public void test_getNumericFunctions() throws SQLException { escapedFunctions(NUMERIC_FUNCTIONS, meta.getNumericFunctions()); @@ -1172,8 +1171,7 @@ public class DatabaseMetaDataTest extends TestCase { method = "getStringFunctions", args = {} ) - @BrokenTest("not supported, complete STRING_FUNCTIONS"+ - " to complete test, Ticket 98") + @KnownFailure("not supported") public void test_getStringFunctions() throws SQLException { escapedFunctions(STRING_FUNCTIONS, meta.getStringFunctions()); @@ -1201,8 +1199,7 @@ public class DatabaseMetaDataTest extends TestCase { method = "getSystemFunctions", args = {} ) - @BrokenTest("not supported, complete SYSTEM_FUNCTIONS"+ - " to complete test, Ticket 98") + @KnownFailure("not supported") public void test_getSystemFunctions() throws SQLException { escapedFunctions(SYSTEM_FUNCTIONS, meta.getSystemFunctions()); @@ -1345,8 +1342,7 @@ public class DatabaseMetaDataTest extends TestCase { method = "getTimeDateFunctions", args = {} ) - @BrokenTest("not supported, complete TIMEDATE_FUNCTIONS"+ - " to complete test, Ticket 98.") + @KnownFailure("not supported") public void test_getTimeDateFunctions() throws SQLException { escapedFunctions(TIMEDATE_FUNCTIONS, meta.getTimeDateFunctions()); diff --git a/sql/src/test/java/tests/java/sql/SelectFunctionalityTest.java b/sql/src/test/java/tests/java/sql/SelectFunctionalityTest.java index 53e6243..5c8f189 100755 --- a/sql/src/test/java/tests/java/sql/SelectFunctionalityTest.java +++ b/sql/src/test/java/tests/java/sql/SelectFunctionalityTest.java @@ -16,6 +16,7 @@ package tests.java.sql; +import dalvik.annotation.KnownFailure; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargets; import dalvik.annotation.TestLevel; @@ -144,7 +145,7 @@ public class SelectFunctionalityTest extends TestCase { * from the table */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects all records from the table", method = "executeQuery", args = {java.lang.String.class} @@ -193,7 +194,7 @@ public class SelectFunctionalityTest extends TestCase { * from the table using parametric query */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects all records from the table using parametric query", method = "executeQuery", args = {java.lang.String.class} @@ -261,7 +262,7 @@ public class SelectFunctionalityTest extends TestCase { * table using subselect */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from the table using subselect", method = "executeQuery", args = {java.lang.String.class} @@ -296,7 +297,7 @@ public class SelectFunctionalityTest extends TestCase { * from a few tables */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a few tables", method = "executeQuery", args = {java.lang.String.class} @@ -340,7 +341,7 @@ public class SelectFunctionalityTest extends TestCase { * from a table using union */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a table using union", method = "executeQuery", args = {java.lang.String.class} @@ -374,7 +375,7 @@ public class SelectFunctionalityTest extends TestCase { * records from a table using left join */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a table using left join", method = "executeQuery", args = {java.lang.String.class} @@ -411,7 +412,14 @@ public class SelectFunctionalityTest extends TestCase { * * TODO RIGHT and FULL OUTER JOINs are not supported */ -/* public void test_SelectRightOuterJoin() throws SQLException { + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "tests right outer joins. RIGHT and FULL OUTER JOINs are not supported", + method = "executeQuery", + args = {java.lang.String.class} + ) + @KnownFailure("not supported") + public void test_SelectRightOuterJoin() throws SQLException { String sql = "SELECT distinct s.snum as ssnum, c.snum as ccnum FROM " + DatabaseCreator.CUSTOMERS_TABLE + " c right outer join " + DatabaseCreator.SALESPEOPLE_TABLE + " s on s.snum=c.snum"; @@ -437,13 +445,13 @@ public class SelectFunctionalityTest extends TestCase { value.isEmpty()); result.close(); } -*/ + /** * @tests SelectFunctionalityTest#test_SelectGroupBy(). Selects records from * a table using group by */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a table using group by", method = "executeQuery", args = {java.lang.String.class} @@ -476,7 +484,7 @@ public class SelectFunctionalityTest extends TestCase { * a table using order by */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a table using order by", method = "executeQuery", args = {java.lang.String.class} @@ -515,7 +523,7 @@ public class SelectFunctionalityTest extends TestCase { * from a table using distinct */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a table using distinct", method = "executeQuery", args = {java.lang.String.class} @@ -545,7 +553,7 @@ public class SelectFunctionalityTest extends TestCase { * records from a table using agregate functions */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a table using agregate functions", method = "executeQuery", args = {java.lang.String.class} @@ -570,11 +578,21 @@ public class SelectFunctionalityTest extends TestCase { } private void func(String name, String query, int expected) { + int res = 0; + double resDouble = 0.0; try { ResultSet result = statement.executeQuery(query); while (result.next()) { - assertEquals("wrong value of " + name + " field", expected, - result.getInt(name)); + res = result.getInt(name); + if (res != 0 ) { + assertEquals(expected,res); + break; + } + // for Double: getInt not supported yet + resDouble = Double.parseDouble(result.getString(name)); + res = (int) Math.rint(resDouble); + assertEquals(expected,res); + } assertFalse("wrong size of result set", result.next()); result.close(); @@ -588,7 +606,7 @@ public class SelectFunctionalityTest extends TestCase { * a table using having */ @TestTargetNew( - level = TestLevel.PARTIAL, + level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality test: Selects records from a table using having", method = "executeQuery", args = {java.lang.String.class} diff --git a/sql/src/test/java/tests/sql/PreparedStatementTest.java b/sql/src/test/java/tests/sql/PreparedStatementTest.java index e2d9909..68d5117 100755 --- a/sql/src/test/java/tests/sql/PreparedStatementTest.java +++ b/sql/src/test/java/tests/sql/PreparedStatementTest.java @@ -43,6 +43,7 @@ import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; +import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; @@ -87,7 +88,8 @@ public class PreparedStatementTest extends SQLTest { + "'1221-09-22 10:11:55', 1, 2, 3, 4," + "'Test text message tiny', 'Test text message', 'Test text message medium', 'Test text message long');" }; - public void createTables() { + public void setUp() { + super.setUp(); Statement st = null; try { st = conn.createStatement(); @@ -104,7 +106,7 @@ public class PreparedStatementTest extends SQLTest { } } - public void clearTables() { + public void tearDown() { Statement st = null; try { st = conn.createStatement(); @@ -117,6 +119,7 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException ee) { } } + super.tearDown(); } /** @@ -157,7 +160,7 @@ public class PreparedStatementTest extends SQLTest { } } } catch (SQLException e) { - fail("SQLException is thrown"); + fail("SQLException is thrown "+e.getMessage()); } finally { try { ps.close(); @@ -201,25 +204,29 @@ public class PreparedStatementTest extends SQLTest { notes = "", method = "execute", args = {} - ) + ) + @KnownFailure("preparedStatement.execute() does not return false on update.") public void testExecute() { Statement st = null; PreparedStatement ps = null; try { + //update String query = "insert into zoo(id, family, name) values(?, ?, 'unknown animal')"; ps = conn.prepareStatement(query); ps.setInt(1, 3); ps.setString(2, "No name"); + assertFalse(ps.execute()); + assertEquals(1,ps.getUpdateCount()); + + // select + ps = conn.prepareStatement("select * from zoo"); assertTrue(ps.execute()); - st = conn.createStatement(); - st.execute("select * from zoo"); - assertEquals(3, getCount(st.getResultSet())); + assertEquals(3, getCount(ps.getResultSet())); } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { ps.close(); - st.close(); } catch (Exception ee) { } } @@ -229,7 +236,7 @@ public class PreparedStatementTest extends SQLTest { ps = conn.prepareStatement(query); ps.setString(1, "cat"); ps.setInt(2, 2); - assertTrue(ps.execute()); + assertFalse(ps.execute()); assertEquals(1, ps.getUpdateCount()); st = conn.createStatement(); st.execute("select family from zoo where id=2"); @@ -250,7 +257,8 @@ public class PreparedStatementTest extends SQLTest { conn.createStatement().execute("drop table if exists hutch"); String query = "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));"; ps = conn.prepareStatement(query); - assertTrue(ps.execute()); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { @@ -286,6 +294,21 @@ public class PreparedStatementTest extends SQLTest { } catch (Exception ee) { } } + //Exception test + try { + String query = "update zoo set name='Masha', family=? where id=?;"; + ps = conn.prepareStatement(query); + ps.setString(1, "cat"); + ps.setInt(2, 2); + assertTrue(ps.execute("update zoo set name='Masha', family='cat' where id=2;")); + } catch (SQLException e) { + // ok Should not provide string argument for a prepared Statement + } finally { + try { + ps.close(); + } catch (Exception ee) { + } + } } @@ -421,7 +444,8 @@ public class PreparedStatementTest extends SQLTest { args = {} ) @KnownFailure("it is not possible to invoke the method getMetaData on a " + - "PreparedStatement object before it is executed") + "PreparedStatement object before it is executed: got NullPointerException."+ + "Test passes on RI.") public void testGetMetaData() { PreparedStatement ps = null; @@ -472,6 +496,7 @@ public class PreparedStatementTest extends SQLTest { } /** + * @throws SQLException * @test java.sql.PreparedStatement#getParameterMetaData() */ @TestTargetNew( @@ -481,11 +506,12 @@ public class PreparedStatementTest extends SQLTest { args = {} ) @KnownFailure("not supported") - public void testGetParameterMetaData() { + public void testGetParameterMetaData() throws SQLException { PreparedStatement ps = null; + String query = "select * from zoo where id = ?"; + ps = conn.prepareStatement(query); + try { - String query = "select * from zoo where id = ?"; - ps = conn.prepareStatement(query); ParameterMetaData rsmd = ps.getParameterMetaData(); } catch (SQLException e) { assertEquals("not supported",e.getMessage()); @@ -496,7 +522,8 @@ public class PreparedStatementTest extends SQLTest { } } - // ps closed + ps.close(); + try { ps.getParameterMetaData(); fail("SQLException expected"); @@ -525,6 +552,7 @@ public class PreparedStatementTest extends SQLTest { ps.clearParameters(); try { ps.execute(); + fail("SQLException is not thrown during execute method after calling clearParameters()"); } catch (SQLException sql) { } @@ -574,7 +602,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, int.class} ) public void testSetInt() throws SQLException { - createTables(); + PreparedStatement ps = null; Statement st = null; try { @@ -592,11 +620,12 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + sqle.getMessage()); } finally { try { + ps.close(); st.close(); } catch (Exception ee) { } } - + ps = conn.prepareStatement(query); try { ps.setInt(1, Integer.MIN_VALUE); ps.execute(); @@ -609,29 +638,25 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + sqle.getMessage()); } finally { try { + ps.close(); st.close(); } catch (SQLException ee) { } } - + ps = conn.prepareStatement(query); + ps.close(); try { - ps.setInt(2, Integer.MIN_VALUE); + ps.setInt(1, Integer.MIN_VALUE); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected } - try { - ps.setInt(-2, 0); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (SQLException ee) { } @@ -648,7 +673,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, long.class} ) public void testSetLong() { - createTables(); + PreparedStatement ps = null; try { String query = "insert into type (LongVal) values (?);"; @@ -689,25 +714,20 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException ee) { } } - + + ps.close(); try { - ps.setLong(2, Long.MIN_VALUE); + ps.setLong(1, Long.MIN_VALUE); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected } - try { - ps.setLong(-2, 0); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (SQLException ee) { } @@ -716,6 +736,7 @@ public class PreparedStatementTest extends SQLTest { } /** + * @throws SQLException * @test java.sql.PreparedStatement#setFloat(int parameterIndex, float x) */ @TestTargetNew( @@ -724,14 +745,16 @@ public class PreparedStatementTest extends SQLTest { method = "setFloat", args = {int.class, float.class} ) - public void testSetFloat() { + public void testSetFloat() throws SQLException { float value1 = 12345678.12345689f; float value2 = -12345678.12345689f; - createTables(); + PreparedStatement ps = null; + String query = "insert into type (FloatVal) values (?);"; + ps = conn.prepareStatement(query); + try { - String query = "insert into type (FloatVal) values (?);"; - ps = conn.prepareStatement(query); + Statement st = null; try { ps.setFloat(1, value1); @@ -765,27 +788,19 @@ public class PreparedStatementTest extends SQLTest { } } - + ps.close(); try { - ps.setFloat(2, Float.MIN_VALUE); + ps.setFloat(1, Float.MIN_VALUE); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } - try { - ps.setFloat(-2, 0); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - assertEquals("bad parameter index", sqle.getMessage()); - } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (SQLException ee) { } @@ -793,6 +808,7 @@ public class PreparedStatementTest extends SQLTest { } /** + * @throws SQLException * @test java.sql.PreparedStatement#setDouble(int parameterIndex, double x) */ @TestTargetNew( @@ -801,12 +817,14 @@ public class PreparedStatementTest extends SQLTest { method = "setDouble", args = {int.class, double.class} ) - public void testSetDouble() { - createTables(); + public void testSetDouble() throws SQLException { + PreparedStatement ps = null; + String query = "insert into type (DoubleVal) values (?);"; + ps = conn.prepareStatement(query); + try { - String query = "insert into type (DoubleVal) values (?);"; - ps = conn.prepareStatement(query); + Statement st = null; try { ps.setDouble(1, Double.MAX_VALUE); @@ -841,27 +859,20 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException ee) { } } - + + ps.close(); try { - ps.setDouble(2, 2.0); + ps.setDouble(1, 2.0); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } - try { - ps.setDouble(-2, 2.0); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - assertEquals("bad parameter index", sqle.getMessage()); - } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (SQLException ee) { } @@ -879,12 +890,14 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.lang.String.class} ) public void testSetString_charField() { - createTables(); + PreparedStatement ps = null; + try { - String str = "test^text$test%"; String query = "insert into type (charStr) values (?);"; ps = conn.prepareStatement(query); + + String str = "test^text$test%"; Statement st = null; try { ps.setString(1, str); @@ -934,23 +947,7 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException ee) { } } - - try { - ps.setString(2, "test text"); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - assertEquals("bad parameter index", sqle.getMessage()); - } - - try { - ps.setString(-2, "test text"); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - assertEquals("bad parameter index", sqle.getMessage()); - } - + try { ps.setString(1, " test & text * test % text * test ^ text "); ps.execute(); @@ -964,11 +961,21 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); } + + ps.close(); + + try { + ps.setString(1, "test text"); + fail("SQLException is not thrown"); + } catch (SQLException sqle) { + // expected + } + } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (SQLException ee) { } @@ -984,8 +991,9 @@ public class PreparedStatementTest extends SQLTest { method = "setString", args = {int.class, java.lang.String.class} ) + @KnownFailure("statment.close() does not wrap up") public void testSetString_tinyTextField() { - createTables(); + PreparedStatement ps = null; try { String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test"; @@ -1040,21 +1048,7 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException ee) { } } - - try { - ps.setString(2, "test text"); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } - - try { - ps.setString(-2, "test text"); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } - + try { ps.setString( 1, @@ -1070,11 +1064,22 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); } + + ps.close(); + + try { + ps.setString(1, "test text"); + fail("SQLException is not thrown"); + } catch (SQLException sqle) { + // expected + } + + } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (SQLException ee) { } @@ -1091,7 +1096,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.lang.String.class} ) public void testSetString_textField() { - createTables(); + PreparedStatement ps = null; try { String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test"; @@ -1147,19 +1152,6 @@ public class PreparedStatementTest extends SQLTest { } } - try { - ps.setString(2, "test text"); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } - - try { - ps.setString(-2, "test text"); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } try { String longString = " test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/"; @@ -1179,11 +1171,20 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); } + + ps.close(); + + try { + ps.setString(2, "test text"); + fail("SQLException is not thrown"); + } catch (SQLException sqle) { + // expected + } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (SQLException ee) { } @@ -1200,7 +1201,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.lang.String.class} ) public void testSetString_mediumTextField() { - createTables(); + PreparedStatement ps = null; try { String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test"; @@ -1255,32 +1256,30 @@ public class PreparedStatementTest extends SQLTest { } catch (Exception ee) { } } - + try { - ps.setString(2, "test text"); - fail("SQLException is not thrown"); + ps.setString(1, null); + ps.execute(); } catch (SQLException sqle) { - // expected + fail("SQLException is thrown: " + sqle.getMessage()); } + + ps.close(); try { - ps.setString(-2, "test text"); + ps.setString(2, "test text"); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected } - try { - ps.setString(1, null); - ps.execute(); - } catch (SQLException sqle) { - fail("SQLException is thrown: " + sqle.getMessage()); - } + + } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (Exception ee) { } @@ -1297,7 +1296,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.lang.String.class} ) public void testSetString_longTextField() { - createTables(); + PreparedStatement ps = null; try { String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test"; @@ -1352,32 +1351,29 @@ public class PreparedStatementTest extends SQLTest { } catch (Exception ee) { } } - + try { - ps.setString(2, "test text"); - fail("SQLException is not thrown"); + ps.setString(1, null); + ps.execute(); } catch (SQLException sqle) { - // expected + fail("SQLException is thrown: " + sqle.getMessage()); } + + ps.close(); try { - ps.setString(-2, "test text"); + ps.setString(1, "test text"); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected } - try { - ps.setString(1, null); - ps.execute(); - } catch (SQLException sqle) { - fail("SQLException is thrown: " + sqle.getMessage()); - } + } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (Exception ee) { } @@ -1394,7 +1390,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, short.class} ) public void testSetShort() { - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; @@ -1433,28 +1429,22 @@ public class PreparedStatementTest extends SQLTest { } catch (Exception ee) { } } + + ps.close(); try { - ps.setShort(2, Short.MAX_VALUE); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } - - try { - ps.setShort(-2, Short.MIN_VALUE); + ps.setShort(1, Short.MIN_VALUE); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected } - String query1 = "insert type(Tint) values (?);"; + String query1 = "insert into type (Tint) values (?);"; ps1 = conn.prepareStatement(query1); try { ps1.setShort(1, Short.MAX_VALUE); - fail("SQLException is not thrown"); } catch (SQLException sqle) { - // expected + fail("SQLException is thrown: "+sqle.getMessage()); } String query2 = "insert into type (IntVal) values (?);"; @@ -1475,7 +1465,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); ps1.close(); ps2.close(); @@ -1495,7 +1485,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, boolean.class} ) public void testSetBoolean() { - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -1533,20 +1523,14 @@ public class PreparedStatementTest extends SQLTest { } catch (Exception ee) { } } + + ps.close(); try { - ps.setBoolean(2, true); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected - } - - try { - ps.setBoolean(-2, false); + ps.setBoolean(1, false); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } String query1 = "insert into type (Tint) values (?);"; @@ -1562,7 +1546,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); ps1.close(); } catch (Exception ee) { @@ -1580,7 +1564,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, byte.class} ) public void testSetByte() { - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -1622,17 +1606,17 @@ public class PreparedStatementTest extends SQLTest { try { ps.setByte(2, Byte.MAX_VALUE); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } + + ps.close(); try { - ps.setByte(-2, Byte.MIN_VALUE); + ps.setByte(1, Byte.MIN_VALUE); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } String query1 = "insert into type (IntVal) values (?);"; @@ -1648,7 +1632,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); ps1.close(); } catch (Exception ee) { @@ -1661,67 +1645,62 @@ public class PreparedStatementTest extends SQLTest { */ @TestTargetNew( level = TestLevel.COMPLETE, - notes = "ps.execute() should be removed in exception part (for exception testing)", + notes = "", method = "setBytes", args = {int.class, byte[].class} ) + @KnownFailure("preparedStatement.execute() does not return false on update.") public void testSetBytes() { byte[] bytesArray = {1, 0}; - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { String query = "insert into type (LBlob) values (?);"; ps = conn.prepareStatement(query); - Statement st = null; + try { ps.setBytes(1, bytesArray); - ps.execute(); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); - } finally { - try { - st.close(); - } catch (Exception ee) { - } - } + } try { ps.setBytes(2, bytesArray); fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected + } catch (Exception sqle) { + // expected RuntimeException or SQLException } + + ps.close(); try { - ps.setBytes(-2, bytesArray); + ps.setBytes(1, bytesArray); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } String query1 = "insert into type (TBlob) values (?);"; ps1 = conn.prepareStatement(query1); try { ps.setBytes(1, bytesArray); - ps.execute(); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); - } finally { - try { - st.close(); - } catch (Exception ee) { - } - } + } + } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); - ps.close(); - ps1.close(); + + if (ps != null) ps.close(); + if (ps1 != null) ps1.close(); } catch (Exception ee) { } } @@ -1737,10 +1716,11 @@ public class PreparedStatementTest extends SQLTest { method = "setBigDecimal", args = {int.class, java.math.BigDecimal.class} ) + @KnownFailure("preparedStatement.execute() does not return false on update.") public void testSetBigDecimal() { BigDecimal bd = new BigDecimal("50"); - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -1749,19 +1729,12 @@ public class PreparedStatementTest extends SQLTest { Statement st = null; try { ps.setBigDecimal(1, bd); - ps.execute(); - st = conn.createStatement(); - st.execute("select * from type where DecVal=" + bd); - ResultSet rs = st.getResultSet(); - assertEquals(1, getCount(rs)); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); - } finally { - try { - st.close(); - } catch (SQLException ee) { - } - } + } + try { ps.setBigDecimal(2, bd); @@ -1790,9 +1763,9 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); - ps.close(); - ps1.close(); + + if (ps != null) ps.close(); + if (ps1 != null) ps1.close(); } catch (SQLException ee) { } } @@ -1808,14 +1781,16 @@ public class PreparedStatementTest extends SQLTest { method = "setDate", args = {int.class, java.sql.Date.class} ) - @KnownFailure("Setting a data for a declared INTEGER should throw Exception") + @KnownFailure("preparedStatement.execute() does not return false on update. "+ + "Setting a data for a declared INTEGER should throw Exception") public void testSetDate_int_Date() { - Calendar cal = new GregorianCalendar(1799,5,26); + Calendar cal = new GregorianCalendar(1799, 5, 26); + + Date[] dates = { + new Date(cal.getTimeInMillis()), new Date(Integer.MAX_VALUE), + new Date(123456789)}; - Date[] dates = { new Date(cal.getTimeInMillis()), new Date(Integer.MAX_VALUE), - new Date(123456789) }; - createTables(); PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -1823,58 +1798,49 @@ public class PreparedStatementTest extends SQLTest { ps = conn.prepareStatement(query); for (int i = 0; i < dates.length; i++) { - Statement st = null; try { ps.setDate(1, dates[i]); - ps.execute(); - st = conn.createStatement(); - st.execute("select * from type where dateVal='" - + dates[i].toString() + "'"); - ResultSet rs = st.getResultSet(); - assertEquals(1, getCount(rs)); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); - } finally { - try { - st.close(); - } catch (SQLException ee) { - } } } try { ps.setDate(2, dates[0]); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } + ps.close(); + try { - ps.setDate(-2, dates[0]); + ps.setDate(1, dates[0]); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } - - String query1 = "insert type(Tint) values (?);"; + + String query1 = "insert into type (Tint) values (?);"; ps1 = conn.prepareStatement(query1); - + try { ps1.setDate(1, dates[0]); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected - assertEquals("SQLite.Exception: error in prepare", sqle.getMessage()); + assertEquals("SQLite.Exception: error in prepare", sqle + .getMessage()); } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); - ps.close(); - ps1.close(); + + if (ps != null) ps.close(); + if (ps1 != null) ps1.close(); } catch (SQLException ee) { } } @@ -1890,6 +1856,7 @@ public class PreparedStatementTest extends SQLTest { method = "setDate", args = {int.class, java.sql.Date.class, java.util.Calendar.class} ) + @KnownFailure("preparedStatement.execute() does not return false on update.") public void testSetDate_int_Date_Calendar() { Calendar[] cals = { Calendar.getInstance(), @@ -1900,7 +1867,7 @@ public class PreparedStatementTest extends SQLTest { Date[] dates = { new Date(cal.getTimeInMillis()), new Date(Integer.MAX_VALUE), new Date(123456789) }; - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -1908,22 +1875,13 @@ public class PreparedStatementTest extends SQLTest { ps = conn.prepareStatement(query); for (int i = 0; i < dates.length; i++) { - Statement st = null; + try { ps.setDate(1, dates[i], cals[i]); - ps.execute(); - st = conn.createStatement(); - st.execute("select * from type where dateVal='" - + dates[i].toString() + "'"); - ResultSet rs = st.getResultSet(); - assertEquals(1, getCount(rs)); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); - } finally { - try { - st.close(); - } catch (SQLException ee) { - } } } @@ -1931,17 +1889,17 @@ public class PreparedStatementTest extends SQLTest { ps.setDate(2, dates[0], cals[0]); ps.execute(); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } - + + ps.close(); + try { - ps.setDate(-2, dates[0], cals[1]); + ps.setDate(1, dates[0], cals[1]); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected - assertEquals("bad parameter index", sqle.getMessage()); } String query1 = "insert into type (Tint) values (?);"; ps1 = conn.prepareStatement(query1); @@ -1957,9 +1915,9 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); - ps.close(); - ps1.close(); + + if (ps != null) ps.close(); + if (ps1 != null) ps1.close(); } catch (SQLException ee) { } } @@ -1977,7 +1935,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, int.class} ) public void testSetNull_int_int() { - createTables(); + PreparedStatement ps = null; try { String query = "insert into type (BoolVal, IntVal) values ('true', ?);"; @@ -1990,23 +1948,22 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + sqle.getMessage()); } finally { try { - st.close(); + ps.close(); } catch (Exception ee) { } } - query = "insert into type (BoolVal, LongVal) values (true, ?);"; + query = "insert into type (BoolVal, LongVal) values ('true', ?);"; ps = conn.prepareStatement(query); try { ps.setNull(1, Types.BIGINT); - fail("SQLException is not thrown"); - } catch (SQLException sqle) { - //expected - assertEquals("SQLite.Exception: error in prepare", sqle.getMessage()); + ps.execute(); + } catch (SQLException sqle) { + fail("SQLException is thrown: " + sqle.getMessage()); } finally { try { - st.close(); + ps.close(); } catch (Exception ee) { } } @@ -2021,62 +1978,55 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + sqle.getMessage()); } finally { try { - st.close(); + ps.close(); } catch (Exception ee) { } } - query = "insert into type (BoolVal, dateVal) values (true, ?);"; + query = "insert into type (BoolVal, dateVal) values ('true', ?);"; ps = conn.prepareStatement(query); try { ps.setNull(1, Types.DATE); - fail("SQLException is not thrown"); + ps.execute(); } catch (SQLException sqle) { - //expected + fail("SQLException is thrown: " + sqle.getMessage()); } finally { try { - st.close(); + ps.close(); } catch (Exception ee) { } } - query = "insert into type (BoolVal, BlobVal) values (true, ?);"; + query = "insert into type (BoolVal, BlobVal) values ('true', ?);"; ps = conn.prepareStatement(query); try { ps.setNull(1, Types.BLOB); - fail("SQLException is not thrown"); + ps.execute(); } catch (SQLException sqle) { - //expected - assertEquals("SQLite.Exception: error in prepare", sqle.getMessage()); + fail("SQLException is thrown: " + sqle.getMessage()); } finally { try { - st.close(); + ps.close(); } catch (Exception ee) { } } - query = "insert into type (BoolVal, TextVal) values (true, ?);"; + query = "insert into type (BoolVal, TextVal) values ('true', ?);"; ps = conn.prepareStatement(query); try { ps.setNull(1, Types.CHAR); - fail("SQLException is not thrown"); + ps.execute(); } catch (SQLException sqle) { - //expected - assertEquals("SQLite.Exception: error in prepare", sqle.getMessage()); - } finally { - try { - st.close(); - } catch (Exception ee) { - } + fail("SQLException is thrown: " + sqle.getMessage()); } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (Exception ee) { } @@ -2123,7 +2073,7 @@ public class PreparedStatementTest extends SQLTest { } catch (SQLException e) { // UDTs or Ref types not supported - assertEquals("SQLite.Exception: error in prepare/compile",e.getMessage()); + // ok } finally { try { st.execute("drop table if exists person"); @@ -2212,7 +2162,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.lang.Object.class} ) public void testSetObject_int_Object() { - createTables(); + PreparedStatement ps = null; try { String query = "insert into type (IntVal) values (?);"; @@ -2266,13 +2216,14 @@ public class PreparedStatementTest extends SQLTest { query = "insert into type (dateVal) values (?);"; ps = conn.prepareStatement(query); + Date d = new Date(123456789); try { - ps.setObject(1, new Date(123456789)); + ps.setObject(1, d); ps.execute(); st = conn.createStatement(); st.execute("select * from type where dateVal='" - + new Date(123456789) + "';"); + + d.getTime() + "';"); ResultSet rs = st.getResultSet(); assertEquals(1, getCount(rs)); } catch (SQLException sqle) { @@ -2304,7 +2255,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (Exception ee) { } @@ -2331,10 +2282,10 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.lang.Object.class, int.class} ) public void testSetObject_int_Object_int() { - createTables(); + PreparedStatement ps = null; try { - String query = "insert into type(IntVal) values (?);"; + String query = "insert into type (IntVal) values (?);"; ps = conn.prepareStatement(query); Statement st = null; try { @@ -2385,13 +2336,15 @@ public class PreparedStatementTest extends SQLTest { query = "insert into type (dateVal) values (?);"; ps = conn.prepareStatement(query); + Date d = new Date(123456789); + try { - ps.setObject(1, new Date(123456789), Types.DATE); + ps.setObject(1, d, Types.DATE); ps.execute(); st = conn.createStatement(); st.execute("select * from type where dateVal='" - + new Date(123456789) + "';"); + + d.getTime() + "';"); ResultSet rs = st.getResultSet(); assertEquals(1, getCount(rs)); } catch (SQLException sqle) { @@ -2423,7 +2376,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (Exception ee) { } @@ -2451,7 +2404,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.lang.Object.class, int.class, int.class} ) public void testSetObject_int_Object_int_int() { - createTables(); + PreparedStatement ps = null; try { String query = "insert into type (IntVal) values (?);"; @@ -2507,13 +2460,13 @@ public class PreparedStatementTest extends SQLTest { query = "insert into type (dateVal) values (?);"; ps = conn.prepareStatement(query); - + Date d = new Date(123456789); try { - ps.setObject(1, new Date(123456789), Types.DATE, -1); + ps.setObject(1, d , Types.DATE, -1); ps.execute(); st = conn.createStatement(); st.execute("select * from type where dateVal='" - + new Date(123456789) + "';"); + + d.getTime() + "';"); ResultSet rs = st.getResultSet(); assertEquals(1, getCount(rs)); } catch (SQLException sqle) { @@ -2545,7 +2498,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); } catch (Exception ee) { } @@ -2568,12 +2521,13 @@ public class PreparedStatementTest extends SQLTest { method = "setTime", args = {int.class, java.sql.Time.class} ) + @KnownFailure("statment.close() does not wrap up") public void testSetTimeint_Time() { Time[] times = { new Time(24, 25, 26), new Time(Integer.MAX_VALUE), new Time(123456789) }; - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -2586,7 +2540,7 @@ public class PreparedStatementTest extends SQLTest { ps.execute(); st = conn.createStatement(); st.execute("select * from type where timeVal='" - + times[i].toString() + "'"); + + times[i].getTime() + "'"); ResultSet rs = st.getResultSet(); assertEquals(1, getCount(rs)); } catch (SQLException sqle) { @@ -2602,12 +2556,14 @@ public class PreparedStatementTest extends SQLTest { try { ps.setTime(2, times[0]); fail("SQLException is not thrown"); - } catch (SQLException sqle) { - // expected + } catch (Exception sqle) { + // expected index out of bounds } - + + ps.close(); + try { - ps.setTime(-2, times[0]); + ps.setTime(1, times[0]); fail("SQLException is not thrown"); } catch (SQLException sqle) { // expected @@ -2626,7 +2582,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); ps1.close(); } catch (Exception ee) { @@ -2644,6 +2600,7 @@ public class PreparedStatementTest extends SQLTest { method = "setTime", args = {int.class, java.sql.Time.class, java.util.Calendar.class} ) + @KnownFailure("preparedStatement.execute() does not return False on update.") public void testSetTime_int_Time_Calendar() { Calendar[] cals = { Calendar.getInstance(), @@ -2653,7 +2610,7 @@ public class PreparedStatementTest extends SQLTest { Time[] times = { new Time(24, 25, 26), new Time(Integer.MAX_VALUE), new Time(123456789) }; - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -2663,12 +2620,8 @@ public class PreparedStatementTest extends SQLTest { for (int i = 0; i < times.length; i++) { try { ps.setTime(1, times[i], cals[i]); - ps.execute(); - st = conn.createStatement(); - st.execute("select * from type where timeVal='" - + times[i].toString() + "'"); - ResultSet rs = st.getResultSet(); - assertEquals(1, getCount(rs)); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); } finally { @@ -2682,14 +2635,16 @@ public class PreparedStatementTest extends SQLTest { try { ps.setTime(2, times[0], cals[0]); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected } + + ps.close(); try { ps.setTime(-2, times[0], cals[1]); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected } String query1 = "insert into type (Tint) values (?);"; @@ -2706,7 +2661,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); ps1.close(); } catch (Exception ee) { @@ -2724,48 +2679,40 @@ public class PreparedStatementTest extends SQLTest { method = "setTimestamp", args = {int.class, java.sql.Timestamp.class} ) + @KnownFailure("preparedStatement.execute() does not return false on update.") public void testSetTimestamp_int_Timestamp() { Timestamp[] timestamps = { new Timestamp(2007, 10, 17, 19, 06, 50, 23), new Timestamp(123) }; - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { String query = "insert into type (TS) values (?);"; ps = conn.prepareStatement(query); - Statement st = null; + for (int i = 0; i < timestamps.length; i++) { try { ps.setTimestamp(1, timestamps[i]); - ps.execute(); - st = conn.createStatement(); - st.execute("select * from type where TS='" - + timestamps[i].toString() + "'"); - ResultSet rs = st.getResultSet(); - assertEquals(1, getCount(rs)); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); - } finally { - try { - st.close(); - } catch (SQLException ee) { - } } } try { ps.setTimestamp(2, timestamps[0]); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected } try { ps.setTimestamp(-2, timestamps[0]); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected } String query1 = "insert into type (Tint) values (?);"; @@ -2782,7 +2729,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); ps1.close(); } catch (Exception ee) { @@ -2807,8 +2754,9 @@ public class PreparedStatementTest extends SQLTest { String neverExecutedQuery = "select TBlob from type;"; ps = conn.prepareStatement(neverExecutedQuery); ps.setBlob(1,mock); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok } } @@ -2829,8 +2777,9 @@ public class PreparedStatementTest extends SQLTest { String neverExecutedQuery = "select TBlob from type;"; ps = conn.prepareStatement(neverExecutedQuery); ps.setClob(1,mock); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok } } @@ -2844,6 +2793,7 @@ public class PreparedStatementTest extends SQLTest { method = "setTimestamp", args = {int.class, java.sql.Timestamp.class, java.util.Calendar.class} ) + @KnownFailure("preparedStatement.execute() does not return false on update.") public void testSetTimestampIntTimestampCalendar() { Calendar[] cals = { Calendar.getInstance(), Calendar.getInstance(Locale.GERMANY), @@ -2852,7 +2802,7 @@ public class PreparedStatementTest extends SQLTest { Timestamp[] timestamps = { new Timestamp(2007, 10, 17, 19, 06, 50, 23), new Timestamp(123) }; - createTables(); + PreparedStatement ps = null; PreparedStatement ps1 = null; try { @@ -2862,12 +2812,8 @@ public class PreparedStatementTest extends SQLTest { for (int i = 0; i < timestamps.length; i++) { try { ps.setTimestamp(1, timestamps[i], cals[i]); - ps.execute(); - st = conn.createStatement(); - st.execute("select * from type where timeVal='" - + timestamps[i].toString() + "'"); - ResultSet rs = st.getResultSet(); - assertEquals(1, getCount(rs)); + assertFalse(ps.execute()); + assertTrue(ps.getUpdateCount() > 0); } catch (SQLException sqle) { fail("SQLException is thrown: " + sqle.getMessage()); } finally { @@ -2882,12 +2828,12 @@ public class PreparedStatementTest extends SQLTest { ps.setTimestamp(2, timestamps[0], cals[0]); ps.execute(); fail("SQLException is not thrown"); - } catch (SQLException sqle) { + } catch (Exception sqle) { // expected } - + ps.close(); try { - ps.setTimestamp(-2, timestamps[0], cals[1]); + ps.setTimestamp(1, timestamps[0], cals[1]); ps.execute(); fail("SQLException is not thrown"); } catch (SQLException sqle) { @@ -2907,7 +2853,7 @@ public class PreparedStatementTest extends SQLTest { fail("SQLException is thrown: " + e.getMessage()); } finally { try { - clearTables(); + ps.close(); ps1.close(); } catch (Exception ee) { @@ -2932,8 +2878,9 @@ public class PreparedStatementTest extends SQLTest { String query = "insert into type (TText) values (?);"; ps = conn.prepareStatement(query); ps.setURL(1, new URL("http://www.android.com")); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok } catch (Exception e) { fail("Error in test setup "+e.getMessage()); e.printStackTrace(); @@ -2959,8 +2906,9 @@ public class PreparedStatementTest extends SQLTest { String query = "insert into type (TText) values (?);"; ps = conn.prepareStatement(query); ps.setArray(1, new MockArray()); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok } catch (Exception e) { fail("Error in test setup "+e.getMessage()); e.printStackTrace(); @@ -2986,8 +2934,9 @@ public class PreparedStatementTest extends SQLTest { String neverExecutedQuery = "select TBlob from type;"; ps = conn.prepareStatement(neverExecutedQuery); ps.setRef(1,mock); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok } } @@ -3011,8 +2960,9 @@ public class PreparedStatementTest extends SQLTest { InputStream file = Class.forName(this.getClass().getName()) .getResourceAsStream("/blob.c"); ps.setUnicodeStream(0, file, 100); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok } catch (Exception e) { fail("Error in test setup "+e.getMessage()); e.printStackTrace(); @@ -3037,10 +2987,12 @@ public class PreparedStatementTest extends SQLTest { ps = conn.prepareStatement(query); InputStream file = Class.forName(this.getClass().getName()) .getResourceAsStream("/blob.c"); + assertNotNull("Error in test setup: file not found",file); Reader reader = new InputStreamReader(file); ps.setCharacterStream(1, reader, 100); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + // ok } catch (Exception e) { fail("Error in test setup "+e.getMessage()); e.printStackTrace(); @@ -3066,8 +3018,9 @@ public class PreparedStatementTest extends SQLTest { InputStream file = Class.forName(this.getClass().getName()) .getResourceAsStream("/blob.c"); ps.setAsciiStream(0, file, 100); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + // ok } catch (Exception e) { fail("Error in test setup "+e.getMessage()); e.printStackTrace(); @@ -3085,6 +3038,7 @@ public class PreparedStatementTest extends SQLTest { args = {int.class, java.io.InputStream.class, int.class} ) public void testSetBinaryStream() { + ResultSet res = null; PreparedStatement ps = null; try { @@ -3093,8 +3047,9 @@ public class PreparedStatementTest extends SQLTest { InputStream file = Class.forName(this.getClass().getName()) .getResourceAsStream("/blob.c"); ps.setBinaryStream(0, file, 100); + fail("Exception expected not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + // ok } catch (Exception e) { fail("Error in test setup "+e.getMessage()); e.printStackTrace(); diff --git a/sql/src/test/java/tests/sql/ResultSetGetterTests.java b/sql/src/test/java/tests/sql/ResultSetGetterTests.java index 3bd8859..302dbee 100644 --- a/sql/src/test/java/tests/sql/ResultSetGetterTests.java +++ b/sql/src/test/java/tests/sql/ResultSetGetterTests.java @@ -23,11 +23,12 @@ import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargetClass; -import java.io.UnsupportedEncodingException; + import java.net.MalformedURLException; import java.net.URL; import java.sql.DatabaseMetaData; import java.sql.Date; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; @@ -125,7 +126,7 @@ public class ResultSetGetterTests extends SQLTest { static Class[] typeMap = new Class[]{ java.lang.String.class, // java.lang.Integer.class,//Types.INTEGER, - java.lang.String.class, //Types.LONG, not a JDBC 1.0 type + java.lang.Integer.class, //Types.LONG, not a JDBC 1.0 type java.lang.Long.class, // Types.BIGINT, java.lang.Byte.class, // Types.TINYINT, java.lang.Short.class, // Types.SMALLINT, @@ -263,7 +264,7 @@ public class ResultSetGetterTests extends SQLTest { ) public void testGetBytesInt() { int i = 1; - /* + // null value try { @@ -284,93 +285,229 @@ public class ResultSetGetterTests extends SQLTest { } catch (SQLException e) { //ok } - */ + } /** * Test method for {@link java.sql.ResultSet#getBytes(int)}. + * @throws SQLException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, - notes = "Integer, test fails", + notes = "VARBINARY value", method = "getBytes", args = {int.class} ) - @KnownFailure("res.close() does not wrap up") - public void testGetBytesIntInteger() { - try { + @KnownFailure("last assertion fails: invalid conversion. Test passes on RI") + public void testGetBytesIntVarbinary() throws SQLException { - Integer input = -1; - String output = ""; + Statement st = null; + Statement stQuery = null; + PreparedStatement stPrep = null; + ResultSet res = null; - Byte inputB = Byte.valueOf(input.toString()); - String hexInput = Integer.toHexString(inputB); - // byte[] inputBytes = - byte[] outputBytes = res.getBytes(2); - for (byte b : outputBytes) { - output += Integer.toHexString(b); + // setup + try { + String testString = "HelloWorld"; + st = conn.createStatement(); + st.executeUpdate("create table testBinary (VARBINARY value);"); + stPrep = conn + .prepareStatement("insert into testBinary values (?);"); + stPrep.setBytes(1, testString.getBytes()); + stPrep.execute(); + + stQuery = conn.createStatement(); + res = stQuery.executeQuery("select * from testBinary"); + try { + assertTrue(res.next()); + byte[] output = res.getBytes(1); + String helloTest = new String(output); + assertNotNull(helloTest); + assertEquals(testString, helloTest); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); } - - assertEquals(1, outputBytes.length); - assertEquals(hexInput, output); + } finally { + if (res != null) res.close(); + if (stPrep != null) stPrep.close(); + if (st != null) st.close(); + if (stQuery != null) stQuery.close(); + } + + } + + /** + * Test method for {@link java.sql.ResultSet#getBytes(int)}. + * @throws SQLException + */ + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "BINARY value", + method = "getBytes", + args = {int.class} + ) + @KnownFailure("last assertion fails: invalid conversion. Test passes on RI") + public void testGetBytesIntBinary() throws SQLException { + Statement st = null; + Statement stQuery = null; + PreparedStatement stPrep = null; + ResultSet res = null; - } catch (SQLException e) { - fail("Unexpected exception: " + e.getMessage()); + // setup + + String testString = "HelloWorld"; + st = conn.createStatement(); + st.executeUpdate("create table testBinary (BINARY value);"); + stPrep = conn.prepareStatement("insert into testBinary values (?);"); + stPrep.setBytes(1, testString.getBytes()); + stPrep.execute(); + try { + stQuery = conn.createStatement(); + res = stQuery.executeQuery("select * from testBinary"); + try { + assertTrue(res.next()); + byte[] output = res.getBytes(1); + String helloTest = new String(output); + assertNotNull(helloTest); + assertEquals(testString, helloTest); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + } finally { + if (res != null) res.close(); + if (stPrep != null) stPrep.close(); + if (st != null) st.close(); + if (stQuery != null) stQuery.close(); } + } + + /** + * Test method for {@link java.sql.ResultSet#getBytes(String)}. + */ + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "Exception testing", + method = "getBytes", + args = {String.class} + ) + public void testGetBytesString() { + int i = 1; - // null value + // null value try { - assertTrue(res.next()); - byte[] b = res.getBytes(2); - assertNull(b); + + res.next(); + for (String t : colNames) { + assertNull(res.getBytes(t)); + } } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } try { res.close(); - res.getBytes(2); + res.getBytes(colNames.get(24)); fail("Should get Exception"); } catch (SQLException e) { //ok } } - - + /** - * Test method for {@link java.sql.ResultSet#getBytes(java.lang.String)}. + * Test method for {@link java.sql.ResultSet#getBytes(int)}. + * @throws SQLException */ @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "no BINARY type supported", + level = TestLevel.PARTIAL_COMPLETE, + notes = "VARBINARY value", method = "getBytes", - args = {java.lang.String.class} + args = {String.class} ) - public void testGetBytesString() { - /* - - - // null value + @KnownFailure("last assertion fails: invalid conversion. Test passes on RI") + public void testGetBytesStringVarbinary() throws SQLException { + + Statement st = null; + Statement stQuery = null; + PreparedStatement stPrep = null; + ResultSet res = null; + + // setup try { - res.next(); - - for (String name: colNames) { - assertNull(res.getBytes(name)); + String testString = "HelloWorld"; + st = conn.createStatement(); + st.executeUpdate("create table testBinary (VARBINARY value);"); + stPrep = conn + .prepareStatement("insert into testBinary values (?);"); + stPrep.setBytes(1, testString.getBytes()); + stPrep.execute(); + + stQuery = conn.createStatement(); + res = stQuery.executeQuery("select value from testBinary"); + try { + assertTrue(res.next()); + byte[] output = res.getBytes("value"); + String helloTest = new String(output); + assertNotNull(helloTest); + assertEquals(testString, helloTest); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); } - } catch (SQLException e) { - fail("Unexpected exception: " + e.getMessage()); + } finally { + if (res != null) res.close(); + if (stPrep != null) stPrep.close(); + if (st != null) st.close(); + if (stQuery != null) stQuery.close(); } - try { - res.close(); - res.getBytes("TextVal"); - fail("Should get Exception"); - } catch (SQLException e) { - //ok + } + + /** + * Test method for {@link java.sql.ResultSet#getBytes(int)}. + * @throws SQLException + */ + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "BINARY value", + method = "getBytes", + args = {String.class} + ) + @KnownFailure("last assertion fails: invalid conversion. Test passes on RI") + public void testGetBytesStringBinary() throws SQLException { + + Statement st = null; + Statement stQuery = null; + PreparedStatement stPrep = null; + ResultSet res = null; + + + // setup + + String testString = "HelloWorld"; + st = conn.createStatement(); + st.executeUpdate("create table testBinary (BINARY value);"); + stPrep = conn.prepareStatement("insert into testBinary values (?);"); + stPrep.setBytes(1, testString.getBytes()); + stPrep.execute(); + try { + stQuery = conn.createStatement(); + res = stQuery.executeQuery("select value from testBinary"); + try { + assertTrue(res.next()); + byte[] output = res.getBytes("value"); + String helloTest = new String(output); + assertNotNull(helloTest); + assertEquals(testString, helloTest); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + } finally { + if (res != null) res.close(); + if (stPrep != null) stPrep.close(); + if (st != null) st.close(); + if (stQuery != null) stQuery.close(); } - */ } /** @@ -378,7 +515,7 @@ public class ResultSetGetterTests extends SQLTest { */ @TestTargetNew( level = TestLevel.SUFFICIENT, - notes = "PARTIAL_OKly supported: CONCUR_UPDATABLE not supported", + notes = "Not fully supported: CONCUR_UPDATABLE not supported", method = "getConcurrency", args = {} ) @@ -924,7 +1061,7 @@ public class ResultSetGetterTests extends SQLTest { * "LONGBLOB", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT", "BIGINT", * "BIGINT","URL","URL"); */ - List<String> types = Arrays.asList("VARCHAR", "INTEGER", "VARCHAR", + List<String> types = Arrays.asList("VARCHAR", "INTEGER", "INTEGER", "BIGINT", "SMALLINT", "SHORT", "INTEGER", "INTEGER", "FLOAT", "DOUBLE", "DOUBLE", "DECIMAL", "NUMERIC", "VARCHAR", "DATE", "TIME", "TIMESTAMP", "DATETIME", "BLOB", "BLOB", "BLOB", @@ -1298,8 +1435,8 @@ public class ResultSetGetterTests extends SQLTest { method = "getTime", args = {int.class} ) + @KnownFailure("getTime should return Time value for a TIMESTAMP type but returns null") public void testGetTimeInt() { - List<Time> times = new LinkedList<Time>(); // values "12:35:45", "2007-10-09 14:28:02.0", "1221-09-22 10:11:55" Calendar cal = new GregorianCalendar(); @@ -1312,7 +1449,19 @@ public class ResultSetGetterTests extends SQLTest { long millis = cal.getTime().getTime(); Time t1 = new java.sql.Time(millis); assertNotNull("t1", t1); - times.add(t1); + + + Calendar cal2 = new GregorianCalendar(); + cal2.set(Calendar.YEAR, 2007); + cal2.set(Calendar.MONTH, Calendar.OCTOBER); + cal2.set(Calendar.DATE, 9); + cal2.set(Calendar.HOUR_OF_DAY, 14); + cal2.set(Calendar.MINUTE, 28); + cal2.set(Calendar.SECOND, 02); + cal2.set(Calendar.MILLISECOND, 0); + + long millis2 = cal2.getTime().getTime(); + Time t2 = new java.sql.Time(millis2); int i = 16; @@ -1325,6 +1474,18 @@ public class ResultSetGetterTests extends SQLTest { } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } + // Compatibility Test: TIMESTAMP value + i = 17; + + try { + Time resTime = res.getTime(i); + assertNotNull("Pos " + i + " null", resTime); + assertEquals(t2.toString(), resTime.toString()); + assertEquals(t2.getTime(), resTime.getTime()); + assertEquals(t2, resTime); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } try { i = 16; @@ -1351,6 +1512,7 @@ public class ResultSetGetterTests extends SQLTest { method = "getTime", args = {int.class, java.util.Calendar.class} ) + @KnownFailure("getTime on TIMESTAMP value fails: returns null") public void testGetTimeIntCalendar() { List<Time> times = new LinkedList<Time>(); List<Calendar> cals = new LinkedList<Calendar>(); @@ -1366,6 +1528,20 @@ public class ResultSetGetterTests extends SQLTest { long millis = cal1.getTime().getTime(); Time t1 = new java.sql.Time(millis); + + Calendar cal2 = new GregorianCalendar(); + cal2.set(Calendar.YEAR, 2007); + cal2.set(Calendar.MONTH, Calendar.OCTOBER); + cal2.set(Calendar.DATE, 9); + cal2.set(Calendar.HOUR_OF_DAY, 14); + cal2.set(Calendar.MINUTE, 28); + cal2.set(Calendar.SECOND, 02); + cal2.set(Calendar.MILLISECOND, 0); + + long millis2 = cal2.getTime().getTime(); + Time t2 = new java.sql.Time(millis2); + + // TIME value int i = 16; @@ -1379,6 +1555,19 @@ public class ResultSetGetterTests extends SQLTest { fail("Unexpected exception: " + e.getMessage()); } + // TIMESTAMP value + i = 17; + + try { + Time timeRes = res.getTime(i,new GregorianCalendar()); + assertNotNull(timeRes); + assertEquals(t2.toString(), timeRes.toString()); + assertEquals(t2.getTime(), timeRes.getTime()); + assertEquals(t2, timeRes); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + try { res.next(); @@ -1407,7 +1596,7 @@ public class ResultSetGetterTests extends SQLTest { method = "getTime", args = {java.lang.String.class} ) -// @KnownFailure("Type Time not supported. test fails") + @KnownFailure("getTime should return a Time value for a TIMESTAMP type but returns null") public void testGetTimeString() { List<Time> times = new LinkedList<Time>(); @@ -1438,6 +1627,31 @@ public class ResultSetGetterTests extends SQLTest { } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } + + Calendar cal2 = new GregorianCalendar(); + cal2.set(Calendar.YEAR, 2007); + cal2.set(Calendar.MONTH, Calendar.OCTOBER); + cal2.set(Calendar.DATE, 9); + cal2.set(Calendar.HOUR_OF_DAY, 14); + cal2.set(Calendar.MINUTE, 28); + cal2.set(Calendar.SECOND, 02); + cal2.set(Calendar.MILLISECOND, 0); + + long millis2 = cal.getTime().getTime(); + Time t2 = new java.sql.Time(millis2); + + col = it.next(); + + try { + Time timeRes = res.getTime(col); + assertNotNull(timeRes); + assertEquals(t2.toString(), timeRes.toString()); + assertEquals(t2.getTime(), timeRes.getTime()); + assertEquals(t2, timeRes); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + try { res.next(); @@ -1460,11 +1674,11 @@ public class ResultSetGetterTests extends SQLTest { */ @TestTargetNew( level = TestLevel.COMPLETE, - notes = "type Time not supported. Test fails", + notes = "Testing getTime with TIME, TIMESTAMP value", method = "getTime", args = {java.lang.String.class, java.util.Calendar.class} ) -// @KnownFailure("type Time not supported. Test fails") + @KnownFailure("getTime on TIMESTAMP value fails: returns null") public void testGetTimeStringCalendar() { List<Time> times = new LinkedList<Time>(); @@ -1497,7 +1711,7 @@ public class ResultSetGetterTests extends SQLTest { long millis2 = cal2.getTime().getTime(); Time t2 = new java.sql.Time(millis2); -// ListIterator<Calendar> calIt = cals.listIterator(); + // TIME value String col = it.next(); try { @@ -1509,9 +1723,8 @@ public class ResultSetGetterTests extends SQLTest { } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } - + //TIMESTAMP value col = it.next(); - System.out.println("ResultSetGetterTests.testGetTimeStringCalendar() "+col); try { Time timeRes = res.getTime(col, new GregorianCalendar()); @@ -1568,7 +1781,7 @@ public class ResultSetGetterTests extends SQLTest { long millis = cal2.getTime().getTime(); Timestamp t2 = new Timestamp(millis); times.add(t2); - // + Calendar cal3 = new GregorianCalendar(); cal3.set(Calendar.YEAR, 1221); cal3.set(Calendar.MONTH, Calendar.SEPTEMBER); @@ -1581,26 +1794,27 @@ public class ResultSetGetterTests extends SQLTest { millis = cal3.getTime().getTime(); Timestamp t3 = new Timestamp(millis); times.add(t3); - -// cals.add(cal1); - cals.add(cal2); - cals.add(cal3); - - // ListIterator<Calendar> calIt = cals.listIterator(); - + // TIMESTAMP value int i = 17; - + try { - // String col = it.next(); Timestamp timeRes = res.getTimestamp(i); assertEquals(t2.toString(), timeRes.toString()); assertEquals(t2.getTime(), timeRes.getTime()); - // assertEquals(t, res.getTime(col)); + assertEquals(t2, timeRes); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + // DATE value + i = 18; + try { + Timestamp timeRes = res.getTimestamp(i); + assertEquals(t3.toString(), timeRes.toString()); + assertEquals(t3.getTime(), timeRes.getTime()); + assertEquals(t3, timeRes); } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } - - // calIt = cals.listIterator(); try { res.next(); @@ -1668,19 +1882,23 @@ public class ResultSetGetterTests extends SQLTest { int i = 17; try { - // String col = it.next(); - Timestamp timeRes = res.getTimestamp(i,cal2); + Timestamp timeRes = res.getTimestamp(i,new GregorianCalendar()); assertEquals(t2.toString(), timeRes.toString()); - timeRes = res.getTimestamp(i+1,cal3); + assertEquals(t2, timeRes); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + + i = 18; + + try { + Timestamp timeRes = res.getTimestamp(i,new GregorianCalendar()); assertEquals(t3.toString(), timeRes.toString()); - assertEquals(t3.getTime(), timeRes.getTime()); - // assertEquals(t, res.getTime(col)); + assertEquals(t3, timeRes); } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } - // calIt = cals.listIterator(); - try { res.next(); assertNull(res.getTime(17,cal2)); @@ -1739,25 +1957,30 @@ public class ResultSetGetterTests extends SQLTest { Timestamp t3 = new Timestamp(millis); times.add(t3); -// cals.add(cal1); -// cals.add(cal2); -// cals.add(cal3); -// -// ListIterator<Calendar> calIt = cals.listIterator(); + String col = it.next(); try { - Timestamp timeRes = res.getTimestamp(stringTimes.get(0)); + Timestamp timeRes = res.getTimestamp(col); + assertEquals(t2.toString(), timeRes.toString()); assertEquals(t2.toString(), timeRes.toString()); - timeRes = res.getTimestamp(stringTimes.get(1)); + assertEquals(t2.getTime(), timeRes.getTime()); + assertEquals(t2, timeRes); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + // DATE value + col = it.next(); + + try { + Timestamp timeRes = res.getTimestamp(col); + assertEquals(t3.toString(), timeRes.toString()); assertEquals(t3.toString(), timeRes.toString()); assertEquals(t3.getTime(), timeRes.getTime()); - // assertEquals(t, res.getTime(col)); + assertEquals(t3, timeRes); } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } - // calIt = cals.listIterator(); - try { res.next(); assertNull(res.getTime(stringTimes.get(0))); @@ -1818,10 +2041,17 @@ public class ResultSetGetterTests extends SQLTest { try { Timestamp timeRes = res.getTimestamp(stringTimes.get(0),cal2); assertEquals(t2.toString(), timeRes.toString()); - timeRes = res.getTimestamp(stringTimes.get(1),cal3); + assertEquals(t2.getTime(), timeRes.getTime()); + assertEquals(t2, timeRes); + } catch (SQLException e) { + fail("Unexpected exception: " + e.getMessage()); + } + // DATE value + try { + Timestamp timeRes = res.getTimestamp(stringTimes.get(1),cal3); assertEquals(t3.toString(), timeRes.toString()); assertEquals(t3.getTime(), timeRes.getTime()); - // assertEquals(t, res.getTime(col)); + assertEquals(t3, timeRes); } catch (SQLException e) { fail("Unexpected exception: " + e.getMessage()); } diff --git a/sql/src/test/java/tests/sql/SQLTest.java b/sql/src/test/java/tests/sql/SQLTest.java index 806a873..9d9051d 100755 --- a/sql/src/test/java/tests/sql/SQLTest.java +++ b/sql/src/test/java/tests/sql/SQLTest.java @@ -42,13 +42,13 @@ public class SQLTest extends TestCase { protected void getSQLiteConnection() { String tmp = System.getProperty("java.io.tmpdir"); assertEquals(tmp,System.getProperty("java.io.tmpdir")); - File ctsDir = new File(tmp); + File tmpDir = new File(tmp); try { - if (ctsDir.isDirectory()) { - dbFile = File.createTempFile("sqliteTest", ".db", ctsDir); + if (tmpDir.isDirectory()) { + dbFile = File.createTempFile("sqliteTest", ".db", tmpDir); dbFile.deleteOnExit(); } else { - System.err.println("ctsdir does not exist"); + System.err.println("java.io.tmpdir does not exist"); } Class.forName("SQLite.JDBCDriver").newInstance(); diff --git a/sql/src/test/java/tests/sql/StatementTest.java b/sql/src/test/java/tests/sql/StatementTest.java index 7568ac8..21560c2 100755 --- a/sql/src/test/java/tests/sql/StatementTest.java +++ b/sql/src/test/java/tests/sql/StatementTest.java @@ -281,6 +281,7 @@ public class StatementTest extends SQLTest { method = "execute", args = {java.lang.String.class} ) + @KnownFailure("Return value wrong for queries below.") public void testExecute() throws SQLException { String[] queries = { @@ -292,15 +293,15 @@ public class StatementTest extends SQLTest { "select animal_id, address from hutch where animal_id=1;", "create view address as select address from hutch where animal_id=2", "drop view address;", "drop table hutch;" }; - boolean[] results = {true, true, true, true, true, true, true, - true, true}; + boolean[] results = {false, false, false, false, false, true, false, + false, false}; for (int i = 0; i < queries.length; i++) { Statement st = null; try { st = conn.createStatement(); boolean res = st.execute(queries[i]); - assertEquals(results[i], res); + assertEquals("different result for statement no. "+i, results[i], res); } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { @@ -361,11 +362,14 @@ public class StatementTest extends SQLTest { try { st = conn.createStatement(); st.execute(queries[i], Statement.NO_GENERATED_KEYS); + fail("Exception expected: Not supported"); + /* ResultSet rs = st.getGeneratedKeys(); fail("Revise test implemenation for feature impl. has changed"); assertFalse(rs.next()); + */ } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + // ok } finally { try { st.close(); @@ -379,11 +383,14 @@ public class StatementTest extends SQLTest { try { st = conn.createStatement(); st.execute(queries[i], Statement.RETURN_GENERATED_KEYS); + fail("Exception expected: Not supported"); + /* ResultSet rs = st.getGeneratedKeys(); fail("Revise test implemenation for feature impl. has changed"); assertFalse(rs.next()); + */ } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok } finally { try { st.close(); @@ -418,7 +425,7 @@ public class StatementTest extends SQLTest { } try { - conn.close(); + st.close(); st.getConnection(); fail("Exception expected"); } catch (SQLException e) { @@ -432,8 +439,8 @@ public class StatementTest extends SQLTest { * @test java.sql.Statement#getFetchDirection() */ @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "SQLException test fails", + level = TestLevel.SUFFICIENT, + notes = "SQLException test fails. Not all Fetch directions supported.", method = "getFetchDirection", args = {} ) @@ -444,7 +451,21 @@ public class StatementTest extends SQLTest { st = conn.createStatement(); assertEquals(ResultSet.FETCH_UNKNOWN, st.getFetchDirection()); } catch (SQLException e) { - fail("SQLException is thrown" + e.getMessage()); + fail("SQLException is thrown " + e.getMessage()); + } finally { + try { + st.close(); + } catch (SQLException ee) { + } + } + + try { + st = conn.createStatement(); + st.setFetchDirection(ResultSet.FETCH_FORWARD); + assertEquals(ResultSet.FETCH_FORWARD, st.getFetchDirection()); + fail("Exception expected: not supported"); + } catch (SQLException e) { + // ok } finally { try { st.close(); @@ -475,11 +496,12 @@ public class StatementTest extends SQLTest { try { st = conn.createStatement(); st.setFetchDirection(ResultSet.FETCH_FORWARD); + st.executeQuery("select * from zoo;"); fail("Revise test implemenation for feature impl. has changed"); // assertEquals(ResultSet.FETCH_FORWARD, st.getFetchDirection()); } catch (SQLException e) { // fail("SQLException is thrown: " + e.getMessage()); - assertEquals("not supported", e.getMessage()); + //ok } finally { try { st.close(); @@ -531,6 +553,7 @@ public class StatementTest extends SQLTest { Statement st = null; try { st = conn.createStatement(); + st.execute("select * from zoo;"); assertEquals(1, st.getFetchSize()); } catch (SQLException e) { fail("SQLException is thrown"); @@ -542,6 +565,7 @@ public class StatementTest extends SQLTest { } try { + st.close(); st.getFetchSize(); fail("Exception expected"); } catch (SQLException e) { @@ -568,7 +592,7 @@ public class StatementTest extends SQLTest { try { st.setFetchSize(i); assertEquals(i, st.getFetchSize()); - fail("Revise test implemenation for feature impl. has changed"); + fail("Revise: test implemenation for feature impl. has changed"); } catch (SQLException sqle) { // fail("SQLException is thrown: " + sqle.toString()); assertEquals("not supported", sqle.getMessage()); @@ -653,7 +677,6 @@ public class StatementTest extends SQLTest { for (int i = 200; i < 500; i += 50) { try { st.setMaxFieldSize(i); - assertEquals(i, st.getMaxFieldSize()); fail("Revise test implemenation for feature impl. has changed"); } catch (SQLException sqle) { assertEquals("not supported", sqle.getMessage()); @@ -685,6 +708,7 @@ public class StatementTest extends SQLTest { Statement st = null; try { st = conn.createStatement(); + st.execute("select * from zoo;"); for (int i = 0; i < 300; i += 50) { try { st.setMaxRows(i); @@ -825,13 +849,16 @@ public class StatementTest extends SQLTest { st = conn.createStatement(); for (int i = 0; i < queries.length; i++) { st.execute(queries[i], (int[]) array.elementAt(i)); + fail("SQLException expected: not supported"); } + /* fail("Revise test implemenation for feature impl. has changed"); assertNotNull(st.getResultSet()); st.close(); assertNull(st.getResultSet()); + */ } catch (SQLException e) { - assertEquals("not supported",e.getMessage()); + // ok: not supported // fail("SQLException is thrown: " + e.getMessage()); } finally { try { @@ -867,15 +894,14 @@ public class StatementTest extends SQLTest { st = conn.createStatement(); for (int i = 0; i < queries.length; i++) { st.execute(queries[i], (String[]) array.elementAt(i)); + fail("Exception expected: not supported"); } fail("Revise test implemenation for feature impl. has changed"); assertNotNull(st.getResultSet()); st.close(); assertNull(st.getResultSet()); } catch (SQLException e) { - assertEquals("not supported",e.getMessage()); -// fail("SQLException is thrown: " + e.getMessage()); - } finally { + // ok: not supported try { st.close(); } catch (SQLException ee) { @@ -910,7 +936,7 @@ public class StatementTest extends SQLTest { "create view address as select address from hutch where animal_id=2;", "drop view address;", "drop table hutch;" }; - int[] result = { 1, 1, 1, 1, 1, 1, 1, 2 }; + int[] result = { 1, 1, 1, 1, 1, 1, 1, 1 }; Statement st = null; //Exception test @@ -954,8 +980,9 @@ public class StatementTest extends SQLTest { st = conn.createStatement(); st.addBatch("select * from zoo"); st.executeBatch(); + fail("Exception expected"); } catch (BatchUpdateException bue) { - fail("BatchUpdateException is thrown: " + bue.toString()); + // ok select returns a resultSet } catch (SQLException sqle) { fail("Unknown SQLException is thrown: " + sqle.getMessage()); } finally { @@ -966,6 +993,7 @@ public class StatementTest extends SQLTest { } //Exception test try { + st.close(); st.executeBatch(); fail("SQLException not thrown"); } catch (SQLException e) { @@ -1043,6 +1071,7 @@ public class StatementTest extends SQLTest { } /** + * @throws SQLException * @test java.sql.Statement#executeUpdate(String sql) */ @TestTargetNew( @@ -1051,8 +1080,10 @@ public class StatementTest extends SQLTest { method = "executeUpdate", args = {java.lang.String.class} ) - @KnownFailure("Returns wrong value for updates") - public void testExecuteUpdate_String() { + @KnownFailure("Spec is not precise enough: should be: number of rows affected."+ + " eg. to be consistent for deletes: 'delete from s1;' should be different from "+ + "'delete from s1 where c1 = 1;' ") + public void testExecuteUpdate_String() throws SQLException { String[] queries1 = { "update zoo set name='Masha', family='cat' where id=2;", @@ -1060,12 +1091,11 @@ public class StatementTest extends SQLTest { "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));", "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');", "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');", - "create view address as select address from hutch where animal_id=2", - "drop view address;", "drop table hutch;" }; + "create view address as select address from hutch where animal_id=2;", + "drop view address;", "drop table hutch;"}; + + String queries2 = "select * from zoo;"; - String[] queries2 = { "select * from zoo", - "select name, family from zoo where id = 1" }; - Statement st = null; try { st = conn.createStatement(); @@ -1078,16 +1108,12 @@ public class StatementTest extends SQLTest { } } - for (int i = 0; i < queries2.length; i++) { - try { - int count = st.executeUpdate(queries2[i]); - assertEquals(0, count); - // according to spec should return 0 for 0 manipulated rows - } catch (SQLException e) { - // expected - fail("SQLException is thrown: " + e.getMessage()); - } + try { + assertEquals(0, st.executeUpdate(queries2)); + } catch (SQLException e) { + fail("SQLException is thrown: " + e.getMessage()); } + } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); } finally { @@ -1095,7 +1121,36 @@ public class StatementTest extends SQLTest { st.close(); } catch (Exception ee) { } - } + } + + // test return value for specific numbers + + Statement stat = conn.createStatement(); + + // there are 0 rows created therefore 0 should be returned. + assertEquals(0 ,stat.executeUpdate("create table s1 (c1);")); + + assertEquals(1, stat.executeUpdate("insert into s1 values (0);")); + assertEquals(1, stat.executeUpdate("insert into s1 values (1);")); + assertEquals(1, stat.executeUpdate("insert into s1 values (2);")); + assertEquals(1,stat.executeUpdate("delete from s1 where c1 = 1;")); + assertEquals(2, stat.executeUpdate("update s1 set c1 = 5;")); + + // analogous to statemente before, delete all should return 2 + assertEquals(2,stat.executeUpdate("delete from s1;")); + + // there are no rows in table: 0 should be returned + assertEquals(0, stat.executeUpdate("drop table s1;")); + + stat.executeUpdate("create table s1 (c1);"); + stat.executeUpdate("insert into s1 values (0);"); + stat.executeUpdate("insert into s1 values (1);"); + stat.executeUpdate("insert into s1 values (2);"); + + // there are 3 rows in table: 3 should be returned + assertEquals(3, stat.executeUpdate("drop table s1;")); + + stat.close(); } /** @@ -1134,8 +1189,8 @@ public class StatementTest extends SQLTest { st = conn.createStatement(); for (int i = 0; i < queries1.length; i++) { st.executeUpdate(queries1[i], (int[]) array.elementAt(i)); + fail("Exception expected"); } - fail("Revise test implemenation for feature impl. has changed"); } catch (SQLException e) { assertEquals("not supported",e.getMessage()); // fail("SQLException is thrown: " + e.getMessage()); @@ -1153,7 +1208,7 @@ public class StatementTest extends SQLTest { * TODO executeUpdate(String sql, int autoGeneratedKeys) is not supported */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "not supported", method = "executeUpdate", args = {java.lang.String.class, int.class} @@ -1169,26 +1224,39 @@ public class StatementTest extends SQLTest { "create view address as select address from hutch where animal_id=2", "drop view address;", "drop table hutch;" }; - for (int i = 0; i < queries.length; i++) { Statement st = null; ResultSet rs = null; try { st = conn.createStatement(); - st.executeUpdate(queries[i], Statement.NO_GENERATED_KEYS); + st.executeUpdate(queries[1], Statement.NO_GENERATED_KEYS); rs = st.getGeneratedKeys(); - fail("Revise test implemenation for feature impl. has changed"); assertFalse(rs.next()); + fail("Exception expected: not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); -// fail("SQLException is thrown: " + e.getMessage()); + //ok } finally { try { rs.close(); st.close(); } catch (Exception ee) { } - } - } + } + + try { + st = conn.createStatement(); + st.executeUpdate(queries[1], Statement.RETURN_GENERATED_KEYS); + rs = st.getGeneratedKeys(); + assertTrue(rs.next()); + fail("Exception expected: not supported"); + } catch (SQLException e) { + //ok + } finally { + try { + rs.close(); + st.close(); + } catch (Exception ee) { + } + } } /** @@ -1230,8 +1298,8 @@ public class StatementTest extends SQLTest { st = conn.createStatement(); for (int i = 0; i < queries.length; i++) { st.executeUpdate(queries[i], (String[]) array.elementAt(i)); + fail("Revise test implemenation for feature impl. has changed"); } - fail("Revise test implemenation for feature impl. has changed"); } catch (SQLException e) { assertEquals("not supported", e.getMessage()); // fail("SQLException is thrown: " + e.getMessage()); @@ -1258,7 +1326,6 @@ public class StatementTest extends SQLTest { try { String query = "update zoo set name='Masha', family='cat' where id=2;"; st = conn.createStatement(); - assertEquals(0, st.getUpdateCount()); st.executeUpdate(query); assertEquals(1, st.getUpdateCount()); query = "update zoo set name='Masha', family='cat' where id=5;"; @@ -1287,7 +1354,7 @@ public class StatementTest extends SQLTest { * TODO getGeneratedKeys() is not supported */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "not supported", method = "getGeneratedKeys", args = {} @@ -1310,7 +1377,7 @@ public class StatementTest extends SQLTest { * TODO setCursorName() is not supported */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "not supported", method = "setCursorName", args = {java.lang.String.class} @@ -1333,7 +1400,7 @@ public class StatementTest extends SQLTest { * TODO setExcapeProcessing() is not supported */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "not supported", method = "setEscapeProcessing", args = {boolean.class} @@ -1449,19 +1516,19 @@ public class StatementTest extends SQLTest { * */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "not supported", method = "getResultSetHoldability", args = {} ) + @KnownFailure("Test for default value fails") public void testGetResultSetHoldability() { // test default value Statement st = null; try { st = conn.createStatement(); - st.getResultSetHoldability(); - assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, st + assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, st .getResultSetHoldability()); } catch (SQLException e) { assertEquals("not supported", e.getMessage()); @@ -1472,22 +1539,28 @@ public class StatementTest extends SQLTest { st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); + fail("Exception expected: not supported"); + /* st.getResultSetHoldability(); assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, st .getResultSetHoldability()); + */ } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + // ok: not supported } try { st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT); + fail("Exception expected: not supported"); + /* st.getResultSetHoldability(); assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, st .getResultSetHoldability()); + */ } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + // ok: not supported } } @@ -1496,12 +1569,12 @@ public class StatementTest extends SQLTest { * */ @TestTargetNew( - level = TestLevel.COMPLETE, + level = TestLevel.SUFFICIENT, notes = "Tests fail. returns only ResultSet.TYPE_SCROLL_INSENSITIVE. Either should throw an unsupported exception or behave according to spec.", method = "getResultSetConcurrency", args = {} ) - @KnownFailure("Not fully supported") + @KnownFailure("Not supported") public void testGetResultSetConcurrency() { Statement st = null; @@ -1514,26 +1587,28 @@ public class StatementTest extends SQLTest { } catch (SQLException e) { assertEquals("not supported", e.getMessage()); } + + // failing tests - try { st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); + ResultSet.CONCUR_UPDATABLE); st.getResultSetConcurrency(); - assertEquals(ResultSet.CONCUR_READ_ONLY, st.getResultSetConcurrency()); + assertEquals(ResultSet.CONCUR_UPDATABLE, st.getResultSetConcurrency()); + fail("Exception expected: not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); + //ok + } - // failing tests - + try { st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_UPDATABLE); + ResultSet.CONCUR_READ_ONLY); st.getResultSetConcurrency(); - assertEquals(ResultSet.CONCUR_UPDATABLE, st.getResultSetConcurrency()); + assertEquals(ResultSet.CONCUR_READ_ONLY, st.getResultSetConcurrency()); + fail("Exception expected: not supported"); } catch (SQLException e) { - assertEquals("not supported", e.getMessage()); - + //ok; } } @@ -1547,7 +1622,7 @@ public class StatementTest extends SQLTest { method = "getResultSet", args = {} ) - @KnownFailure("Does not return null on update count > 0") + @KnownFailure("Does not return null on update count > 0 (not a select statement) ") public void testGetResultSet() { Statement st = null; ResultSet res = null; @@ -1555,39 +1630,35 @@ public class StatementTest extends SQLTest { try { st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, - ResultSet.HOLD_CURSORS_OVER_COMMIT); + ResultSet.CLOSE_CURSORS_AT_COMMIT); + st.execute("create table test (c1);"); res = st.getResultSet(); assertNull(res); } catch (SQLException e) { - fail("SQLException is thrown"); - } - - try { - assertNull(st.getResultSet()); - } catch (SQLException e) { - fail("SQLException is thrown"); + fail("Unexpected Exception "+e); } try { + st = conn.createStatement(); String select = "select * from zoo where id == 4;"; String insert = "insert into zoo (id, name, family) values (4, 'Vorobuy', 'bear');"; st.execute(insert); st.execute(select); + assertEquals(-1, st.getUpdateCount()); res = st.getResultSet(); assertNotNull(res); res.next(); assertEquals(4,res.getInt(1)); assertEquals("Vorobuy",res.getString(2)); assertEquals("bear",res.getString(3)); -// assertEquals(0, st.getUpdateCount()); - +// assertEquals(0, st.getUpdateCount()); not supported assertFalse(res.next()); } catch (SQLException e) { fail("SQLException is thrown:"+e.getMessage()); } try { - assertEquals(0, st.getUpdateCount()); + st = conn.createStatement(); String insert = "insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');"; st .execute(insert); @@ -1651,21 +1722,13 @@ public class StatementTest extends SQLTest { * @test {@link java.sql.Statement#getMoreResults()} * */ - @TestTargets({ @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Test fails. It can never be that getMoreResults == true and updateCounts > 0, according to spec (see spec of getResultSet).Error seems to be related with malfunction of SQLite.Database.changes", + level = TestLevel.SUFFICIENT, + notes = "not fully supported", method = "getMoreResults", args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Test fails. It can never be that getMoreResults == true and updateCounts > 0, according to spec (see spec of getResultSet).Error seems to be related with malfunction of SQLite.Database.changes", - method = "getUpdateCount", - args = {} - ) - }) - @KnownFailure("Precondition fails. dependendancy with getUpdateCount") + ) + @KnownFailure("not supported") public void testGetMoreResults() { Statement st = null; ResultSet res1 = null; @@ -1673,46 +1736,18 @@ public class StatementTest extends SQLTest { String[] queries = { "insert into zoo values (3,'John','bird');", "update zoo set name='Masha', family='cat' where id=3;", - "update zoo set name='Masha', family='bear' where id=3;", - "select * from zoo;"}; - - int[] updates = {1, 1, 1, 0}; - try { + "update zoo set name='Masha', family='bear' where id=3;"}; + + try { st = conn.createStatement(); - for (int i = 0; i < queries.length; i++) { - st.addBatch(queries[i]); - } - int[] updateCounts = st.executeBatch(); - //Precondition - assertTrue(java.util.Arrays.equals(updateCounts, updates)); - - assertTrue((st.getMoreResults() == false) - && (st.getUpdateCount() == 1)); - res1 = st.getResultSet(); - assertNull(res1); - - assertTrue((st.getMoreResults() == false) - && (st.getUpdateCount() == 1)); - res2 = st.getResultSet(); - assertNull(res2); - - assertTrue((st.getMoreResults() == false) - && (st.getUpdateCount() == 1)); - res1 = st.getResultSet(); - assertNull(res1); - - assertTrue((st.getMoreResults() == true) - && (st.getUpdateCount() == 0)); - res1 = st.getResultSet(); - assertNotNull(res1); - - assertTrue((st.getMoreResults() == false) - && (st.getUpdateCount() == -1)); + st.execute(queries[0]); + assertFalse(st.getMoreResults()); + try { st.getResultSet(); + fail("Exception expected"); } catch (SQLException e) { - //error expected - assertEquals("statement already closed", e.getMessage()); + //ok } } catch (SQLException e) { fail("SQLException is thrown: " + e.getMessage()); @@ -1736,75 +1771,15 @@ public class StatementTest extends SQLTest { * */ @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "not supported", + level = TestLevel.NOT_FEASIBLE, + notes = "Callable Statements are not supported", method = "getMoreResults", args = {int.class} ) public void testGetMoreResultsInt() { - Statement st = null; - ResultSet res1 = null; - ResultSet res2 = null; - ResultSet notClosedResult = null; - ResultSet notClosedResult2 = null; - String[] queries = { - "insert into zoo values (3,'John','bird');", - "update zoo set name='Masha', family='cat' where id=3;", - "select * from zoo;", - "insert into zoo values (6,'Tweety','bird');", - "select * from zoo;"}; - - try { - st = conn.createStatement(); - for (int i = 0; i < queries.length; i++) { - st.addBatch(queries[i]); - } - int[] updateCounts = st.executeBatch(); - - //insert - assertTrue((st.getMoreResults(Statement.CLOSE_CURRENT_RESULT) == false) - && (st.getUpdateCount() == 1)); - res1 = st.getResultSet(); - assertNull(res1); - - - //update - assertTrue((st.getMoreResults(Statement.CLOSE_CURRENT_RESULT) == false) - && (st.getUpdateCount() == 1)); - res2 = st.getResultSet(); - assertNull(res2); - - //select - assertTrue((st.getMoreResults(Statement.KEEP_CURRENT_RESULT) == true) -// && (st.getUpdateCount() == 0) - ); - notClosedResult = st.getResultSet(); - assertNotNull(notClosedResult); - - //insert - assertTrue((st.getMoreResults(Statement.CLOSE_CURRENT_RESULT) == false) - && (st.getUpdateCount() == 1)); - res1 = st.getResultSet(); - assertNotNull(res1); - - //select - assertTrue((st.getMoreResults(Statement.KEEP_CURRENT_RESULT) == true) -// && (st.getUpdateCount() == 0) - ); - notClosedResult2 = st.getResultSet(); - assertNotNull(notClosedResult2); - assertFalse(notClosedResult.equals(notClosedResult2)); - - // end - assertTrue((st.getMoreResults() == false) - && (st.getUpdateCount() == -1)); - try { - st.getResultSet(); - } catch (SQLException e) { - //error expected - assertEquals("statement already closed", e.getMessage()); - } - + /* + } catch (BatchUpdateException e) { + fail("Unexpected Exception "+e.getMessage()); } catch (SQLException e) { assertEquals("not supported",e.getMessage()); } finally { @@ -1815,11 +1790,12 @@ public class StatementTest extends SQLTest { } try { - st.getMoreResults(Statement.CLOSE_CURRENT_RESULT); + st.getMoreResults(Integer.MAX_VALUE); fail("Exception expected"); } catch (SQLException e) { //ok } + */ } /** diff --git a/sql/src/test/java/tests/support/MockFunction.java b/sql/src/test/java/tests/support/MockFunction.java index 8f78895..de4e9f5 100644 --- a/sql/src/test/java/tests/support/MockFunction.java +++ b/sql/src/test/java/tests/support/MockFunction.java @@ -22,18 +22,25 @@ import SQLite.FunctionContext; public class MockFunction implements SQLite.Function{ private StringBuffer acc = new StringBuffer(); + public static boolean getAggValueCalled = false; + public static boolean functionCalled = false; + public static boolean stepCalled = false; + public static boolean lastStepCalled = false; public String getAggValue() { + getAggValueCalled = true; return acc.toString(); } public void function(FunctionContext fc, String args[]) { + functionCalled = true; if (args.length > 0) { fc.set_result(args[0].toLowerCase()); } } public void step(FunctionContext fc, String args[]) { + stepCalled = true; for (int i = 0; i < args.length; i++) { acc.append(args[i]); acc.append(" "); @@ -41,6 +48,7 @@ public class MockFunction implements SQLite.Function{ } public void last_step(FunctionContext fc) { + lastStepCalled = true; fc.set_result(acc.toString()); } }
\ No newline at end of file diff --git a/sql/src/test/java/tests/support/Support_SQL.java b/sql/src/test/java/tests/support/Support_SQL.java index 71dccc0..1f63f15 100644 --- a/sql/src/test/java/tests/support/Support_SQL.java +++ b/sql/src/test/java/tests/support/Support_SQL.java @@ -52,12 +52,12 @@ public class Support_SQL { .getResourceAsStream("/connection.properties")); String tmp = System.getProperty("java.io.tmpdir"); - File ctsDir = new File(tmp); - if (ctsDir.isDirectory()) { - dbFile = File.createTempFile("sqliteTest", ".db", ctsDir); + File tmpDir = new File(tmp); + if (tmpDir.isDirectory()) { + dbFile = File.createTempFile("sqliteTest", ".db", tmpDir); dbFile.deleteOnExit(); } else { - System.err.println("ctsdir does not exist"); + System.err.println("java.io.tmpdir does not exist"); } Class.forName("SQLite.JDBCDriver").newInstance(); diff --git a/sql/src/test/java/tests/support/ThreadPool.java b/sql/src/test/java/tests/support/ThreadPool.java index 37e87f7..6e82f25 100644 --- a/sql/src/test/java/tests/support/ThreadPool.java +++ b/sql/src/test/java/tests/support/ThreadPool.java @@ -104,7 +104,6 @@ public class ThreadPool extends ThreadGroup { } if (task == null) { - Logger.global.info("Task is null"); return; } |