db-derby-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From krist...@apache.org
Subject svn commit: r1392375 - in /db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests: master/ suites/ tests/store/
Date Mon, 01 Oct 2012 15:05:48 GMT
Author: kristwaa
Date: Mon Oct  1 15:05:48 2012
New Revision: 1392375

URL: http://svn.apache.org/viewvc?rev=1392375&view=rev
Log:
DERBY-5934: Convert store.ReEncryptCrashRecovery

Converted old-style Java test to JUnit.
Changed the name of the test, since tests for database decryption are expected.

Patch file: derby-5934-1a-converted_to_junit.diff

Added:
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/CryptoCrashRecoveryTest.java
      - copied, changed from r1392364, db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/ReEncryptCrashRecovery.java
Removed:
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/master/ReEncryptCrashRecovery.out
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/ReEncryptCrashRecovery.java
Modified:
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall
    db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/_Suite.java

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall?rev=1392375&r1=1392374&r2=1392375&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall
(original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/suites/encryptionAll.runall
Mon Oct  1 15:05:48 2012
@@ -3,4 +3,3 @@ store/encryptDatabaseTest1.sql
 store/encryptDatabaseTest2.sql
 store/encryptDatabaseTest3.sql
 store/encryptionKey_jar.sql
-store/ReEncryptCrashRecovery.java

Copied: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/CryptoCrashRecoveryTest.java
(from r1392364, db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/ReEncryptCrashRecovery.java)
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/CryptoCrashRecoveryTest.java?p2=db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/CryptoCrashRecoveryTest.java&p1=db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/ReEncryptCrashRecovery.java&r1=1392364&r2=1392375&rev=1392375&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/ReEncryptCrashRecovery.java
(original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/CryptoCrashRecoveryTest.java
Mon Oct  1 15:05:48 2012
@@ -1,6 +1,6 @@
 /*
 
-   Derby - Class org.apache.derbyTesting.functionTests.store.ReEncryptCrashRecovery
+   Derby - Class org.apache.derbyTesting.functionTests.store.CryptoCrashRecoveryTest
 
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
@@ -20,675 +20,588 @@
  */
 
 package org.apache.derbyTesting.functionTests.tests.store;
+
+import java.io.File;
 import java.sql.Connection;
 import java.sql.Statement;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
-import org.apache.derby.tools.ij;
-import org.apache.derbyTesting.functionTests.util.TestUtil;
-import org.apache.derby.iapi.services.sanity.SanityManager;
+import javax.sql.DataSource;
 
-/*
- * This class tests crash/recovery scenarions during  (re) encryption of 
- * database. Debug flags are used to simulate crashes during the 
- * encrytpion of an un-encrypted database and re-encryption of an encrypted
- * database with new password/key. 
- *
- *  Unlike the other recovery tests which do a setup and recovery as different
- *  tests, Incase of re-encryption crash/recovery can be simulated in one 
- *  test itself because re-encryption is done at boot time. When debug flags are
- *  set database boot itself fails. To test the recovery, it is just a matter 
- *  of clearing up the debug flag and rebooting the database. 
- *  
- * In Non debug mode, this tests does not do anything.
- *
- * @version 1.0
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.derby.iapi.services.sanity.SanityManager;
+import org.apache.derbyTesting.junit.BaseJDBCTestCase;
+import org.apache.derbyTesting.junit.JDBC;
+import org.apache.derbyTesting.junit.JDBCDataSource;
+import org.apache.derbyTesting.junit.TestConfiguration;
+
+/**
+ * This class tests crash/recovery scenarios during cryptographic operations on
+ * the database.
+ * <p>
+ * Debug flags are used to simulate crashes during the encryption of an
+ * un-encrypted database and re-encryption of an encrypted database with new
+ * password/key.
+ * <p>
+ * Unlike the other recovery tests which do a setup and recovery as different
+ * tests, crash/recovery for cryptographic operations can be simulated in one
+ * test itself because the cryptographic operation is performed at boot time.
+ * When debug flags are set the database boot itself fails. To test the
+ * recovery, it is just a matter of clearing up the debug flag and rebooting
+ * the database.
+ * <p>
+ * In non-debug mode (compiled as "insane") this test does nothing.
  */
+public class CryptoCrashRecoveryTest
+    extends BaseJDBCTestCase {
 
-public class ReEncryptCrashRecovery
-{
+    private static boolean USE_ENC_PWD = true;
+    private static boolean USE_ENC_KEY = false;
 
-    // database name used to test re-encryption of an encrypted database 
-    // using a new boot password.
-    private static final String TEST_REENCRYPT_PWD_DATABASE = "wombat_pwd_ren" ;
-    // database name used to test encryption and un-encrypted database.
-    // using a boot password.
-    private static final String TEST_ENCRYPT_PWD_DATABASE = "wombat_pwd_en";
-
-
-    // database name used to test re-encryption of an encrypted database 
-    // using the external encryption key.
-    private static final String TEST_REENCRYPT_KEY_DATABASE = "wombat_key_ren" ;
-    // database name used to test encryption of un-encrypted database.
-    // using external encryption key.
-    private static final String TEST_ENCRYPT_KEY_DATABASE = "wombat_key_en";
-
-    // flags to indicate type of mechanism used to test the (re)encryption
-    private static final  int USING_KEY = 1;
-    private static final  int USING_PASSWORD = 2;
-
-    // flags to indicate the password/key to be used during recovery
-    // on reboot after a crash.
-    private static final int NONE = 1;
-    private static final int OLD  = 2;
-    private static final int NEW  = 3;
+    private static final int OP_ENCRYPT = 0;
+    private static final int OP_DECRYPT = 1;
+    private static final int OP_REENCRYPT = 2;
 
-    // test table name.
+    /** Table name used by the test. */
     private static final String TEST_TABLE_NAME = "emp";
 
     private static final String OLD_PASSWORD = "xyz1234abc";
     private static final String NEW_PASSWORD = "new1234xyz";
-    
+
     private static final String OLD_KEY = "6162636465666768";
     private static final String NEW_KEY = "5666768616263646";
-    
-    // the current database being tested.
-    private String currentTestDatabase ;
-    // the current encryption type being tested. 
-    private int encryptionType; 
-
-    // set the following to true, for this test 
-    // spit out more status messages.
-    private boolean verbose = false;
-
 
-	ReEncryptCrashRecovery() {
-        
+	public CryptoCrashRecoveryTest(String name) {
+        super(name);
 	}
 
-
-    /*
-	 * Test (re)encrytpion crash/recovery scenarios. 
-	 */
-	private void runTest() throws Exception {
-		logMessage("Begin  ReEncryptCrashRecovery Test");
-
+    public static Test suite() {
+        Test suite;
         if (SanityManager.DEBUG) {
-            if (verbose) 
-                logMessage("Start testing re-encryption with Password");
-            // test  crash recovery during re-encryption 
-            // using the password mechanism.
-            currentTestDatabase = TEST_REENCRYPT_PWD_DATABASE;
-            encryptionType = USING_PASSWORD;
-            runCrashRecoveryTestCases(true);
-
-        
-            if (verbose) 
-            logMessage("Start Testing encryption with Password");
-
-            // test crash recovery during databse encryption 
-            // using the password mechanism.
-            currentTestDatabase = TEST_ENCRYPT_PWD_DATABASE;
-            encryptionType = USING_PASSWORD;
-            // run crash recovery test cases. 
-            runCrashRecoveryTestCases(false);
-
-
-            if (verbose) {
-                logMessage("Start Testing Encryption with external Key");
-            }
-            // test crash recovery during database encryption 
-            // using the encryption key.
-        
-            currentTestDatabase = TEST_ENCRYPT_KEY_DATABASE;
-            encryptionType = USING_KEY;
-            runCrashRecoveryTestCases(false);
-
-            if (verbose) 
-                logMessage("Start Testing re-encryption with external Key");
-
-            // test crash recovery dureing re-encryption 
-            // using the encryption key.
-        
-            currentTestDatabase = TEST_REENCRYPT_KEY_DATABASE;
-            encryptionType = USING_KEY;
-            runCrashRecoveryTestCases(true);
-        }
-        logMessage("End ReEncryptCrashRecovery Test");
+            suite = TestConfiguration.embeddedSuite(
+                    CryptoCrashRecoveryTest.class);
+        } else {
+            suite = new TestSuite("disabled due to non-debug build");
+            println("test disabled due to non-debug build");
+        }
+        return suite;
+    }
+
+	public void testEncryptionWithBootPassword()
+            throws Exception {
+        String db = "wombat_pwd_en";
+        // Crash recovery during encryption using the password mechanism.
+        DataSource ds = JDBCDataSource.getDataSource(db);
+        runCrashRecoveryTestCases(ds, OP_ENCRYPT, USE_ENC_PWD);
+        assertDirectoryDeleted(new File("system", db));
+    }
+
+	public void testEncryptionWitEncryptionKey()
+            throws Exception {
+        String db = "wombat_key_en";
+        // Crash recovery during database encryption using the encryption key.
+        DataSource ds = JDBCDataSource.getDataSource(db);
+        runCrashRecoveryTestCases(ds, OP_ENCRYPT, USE_ENC_KEY);
+        assertDirectoryDeleted(new File("system", db));
+    }
+
+	public void testReEncryptionWithBootPassword()
+            throws Exception {
+        String db = "wombat_pwd_ren";
+        // Crash recovery during re-encryption using the password mechanism.
+        DataSource ds = JDBCDataSource.getDataSource(db);
+        runCrashRecoveryTestCases(ds, OP_REENCRYPT, USE_ENC_PWD);
+        assertDirectoryDeleted(new File("system", db));
+    }
+
+	public void testReEncryptionWithEncryptionKey()
+            throws Exception {
+        String db = "wombat_key_ren";
+        // Crash recovery during re-encryption using an encryption key.
+        DataSource ds = JDBCDataSource.getDataSource(db);
+        runCrashRecoveryTestCases(ds, OP_REENCRYPT, USE_ENC_KEY);
+        assertDirectoryDeleted(new File("system", db));
     }
 
-
     /**
-     * run crash recovery test scenarios using the debug flags.
-     * @param reEncrypt  <code> true </code> if testing re-encryption 
-     *                   <colde> false </code> otherwise.
-     */
-    private void runCrashRecoveryTestCases(boolean reEncrypt) 
-        throws SQLException
-    {
-        Connection conn;
-        if (reEncrypt) 
-            conn = createEncryptedDatabase();
-        else 
-            conn = createDatabase();
-
-        createTable(conn, TEST_TABLE_NAME);
-        //load some rows 
-        insert(conn, TEST_TABLE_NAME, 100);
-        conn.commit();
-        conn.close();
-		shutdown();
-
-        // following cases of (re) encryption should be rolled back. 
-        int passwordKey = (reEncrypt ? OLD : NONE );
+     * Runs crash recovery test scenarios for the given cryptographic operation
+     * using the debug flags.
+     *
+     * @param ds data source
+     * @param operation the cryptographic operation to perform
+     * @param useEncPwd whether to use encryption key or boot password (see
+     *      {@linkplain #USE_ENC_KEY} and {@linkplain #USE_ENC_PWD})
+     */
+    private void runCrashRecoveryTestCases(DataSource ds, int operation,
+                                           boolean useEncPwd)
+            throws SQLException {
+        verifyOperation(operation);
+        Connection con;
+        if (operation == OP_REENCRYPT) {
+            con = createEncryptedDatabase(ds, useEncPwd);
+        } else {
+            con = createDatabase(ds);
+        }
+
+        createTable(con, TEST_TABLE_NAME);
+        // Load some rows, used for verification later.
+        insert(con, TEST_TABLE_NAME, 100);
+        con.commit();
+        con.close();
+        JDBCDataSource.shutdownDatabase(ds);
+
+        // Following cases of (re-)encryption should be rolled back.
+        Boolean useNewCredential =
+                (operation == OP_REENCRYPT ? Boolean.FALSE : null);
 
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_BEFORE_COMMT);
+        crash(ds, operation, useEncPwd, TEST_REENCRYPT_CRASH_BEFORE_COMMT);
 
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_AFTER_COMMT);
-        crashInRecovery(passwordKey, 
+        crash(ds, operation, useEncPwd, TEST_REENCRYPT_CRASH_AFTER_COMMT);
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_LOGFILE_DELETE);
-        crashInRecovery(passwordKey, 
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_REVERTING_KEY);
-        crashInRecovery(passwordKey, 
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_BEFORE_RECOVERY_FINAL_CLEANUP);
 
-        
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_AFTER_COMMT);
-        crashInRecovery(passwordKey, 
+
+        crash(ds, operation, useEncPwd, TEST_REENCRYPT_CRASH_AFTER_COMMT);
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_LOGFILE_DELETE);
         // retry (re)encryption and crash.
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_AFTER_COMMT);
-
+        crash(ds, operation, useEncPwd, TEST_REENCRYPT_CRASH_AFTER_COMMT);
 
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY);
-        crashInRecovery(passwordKey, 
+        crash(ds, operation, useEncPwd,
+                TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY);
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_LOGFILE_DELETE);
-        crashInRecovery(passwordKey, 
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_REVERTING_KEY);
-        crashInRecovery(passwordKey, 
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_BEFORE_RECOVERY_FINAL_CLEANUP);
 
-
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY);
-        crashInRecovery(passwordKey, 
+        crash(ds, operation, useEncPwd,
+                TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY);
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_REVERTING_KEY);
-        // retry (re)encryption and crash.
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY);
-        crashInRecovery(passwordKey, 
+        // Retry (re-)encryption and crash.
+        crash(ds, operation, useEncPwd,
+                TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY);
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_BEFORE_RECOVERY_FINAL_CLEANUP);
 
+        // Rollowing cases of (re-)encryption should be successful, only
+        // cleanup is pending.
 
-        // following cases  (re) encryption should be successful, only 
-        // cleanup is pending. 
-
-        // crash after database is re-encrypted, but before cleanup. 
-        // (re)encryption is complete, database should be bootable 
-        // with a new password. 
-        passwordKey = (reEncrypt ? NEW : OLD);
-        crash(reEncrypt, TEST_REENCRYPT_CRASH_AFTER_CHECKPOINT);
-        crashInRecovery(passwordKey, 
+        // Crash after database is (re-)encrypted, but before cleanup.
+        // If re-encryption is complete, database should be bootable with the
+        // new password.
+        useNewCredential =
+                (operation == OP_REENCRYPT ? Boolean.TRUE : Boolean.FALSE);
+        crash(ds, operation, useEncPwd, TEST_REENCRYPT_CRASH_AFTER_CHECKPOINT);
+        crashInRecovery(ds, useEncPwd, useNewCredential,
                      TEST_REENCRYPT_CRASH_BEFORE_RECOVERY_FINAL_CLEANUP);
 
-        recover(passwordKey);
-        shutdown();
+        recover(ds, useEncPwd, useNewCredential);
+        JDBCDataSource.shutdownDatabase(ds);
     }
 
-
-    /*
-     * Attempt to (re)encrypt the database and force it to crash 
-     * at the given debug flag. 
-     */
-    private void crash(boolean reEncrypt, String debugFlag) 
-    {
-        if (verbose)
-            logMessage("Testing : " + debugFlag);
-        // set the debug flag to crash. 
+    /**
+     * Crashes the engine at the point specified by the debug flag while
+     * performing the requested operation.
+     *
+     * @param ds database
+     * @param operation cryptographic operation to perform
+     * @param useEncPwd whether to use boot password or encryption key
+     * @param debugFlag debug flag to enable to make the engine crash
+     */
+    private void crash(DataSource ds, int operation, boolean useEncPwd,
+                       String debugFlag) {
+        println("Testing crash at " + debugFlag);
+        // Set the debug flag to crash.
         setDebugFlag(debugFlag);
 
-        SQLException sqle = null;
-        Connection conn;
         try {
-            if (reEncrypt) 
-                conn = reEncryptDatabase();
-            else 
-                conn = encryptDatabase();
-                
-        }catch (SQLException se) {
-            // (re)encryption of the database should have failed,
-            // at the specified debug flag.
-            sqle = se;
+            if (operation == OP_REENCRYPT) {
+                reEncryptDatabase(ds, useEncPwd);
+            } else {
+                encryptDatabase(ds, useEncPwd);
+            }
+            fail("crypto operation didn't crash as expected");
+        } catch (SQLException sqle) {
+            // check that database boot failed at the set debug flag.
+            verifyBootException(sqle, debugFlag);
+        } finally {
+            clearDebugFlag(debugFlag);
         }
-
-        // check that database boot failed at the set debug flag.
-        verifyException(sqle, debugFlag);
-        // clear the debug flag.
-        clearDebugFlag(debugFlag);
     }
 
+    /**
+     * Crashes the engine in recovery of the given database at the point
+     * specified by the debug flag.
+     *
+     * @param ds database
+     * @param useEncPwd whether to use boot password or encryption key
+     * @param useNewCredential tri-state telling whether to use the old, the
+     *      new, or no credential when booting the database
+     * @param debugFlag debug flag to enable to make the engine crash
+     */
+    private void crashInRecovery(DataSource ds, boolean useEncPwd,
+                                 Boolean useNewCredential, String debugFlag)
+            throws SQLException {
+        println("Recovery crash at " + debugFlag);
 
-    /*
-     * Crash in recovery of the database at the given 
-     * debug flag.
-     */
-    private void crashInRecovery(int passwordKey, String debugFlag) 
-        throws SQLException 
-    {
-        if (verbose) 
-            logMessage("Testing : " + debugFlag);
-        
-        // set the debug flag to crash. 
+        // set the debug flag to crash.
         setDebugFlag(debugFlag);
-        SQLException sqle = null;
         try {
-            Connection conn = bootDatabase(passwordKey);
-        } catch (SQLException se) {
-            // recovery of the database 
-            // shold have failed at the specified
-            // debug flag.
-            sqle = se;
-        }
-        // check that database boot failed at the set debug flag.
-        verifyException(sqle, debugFlag);
-        // clear the debug flag.
-        clearDebugFlag(debugFlag);
-    }   
-    
-
+            bootDatabase(ds, useEncPwd, useNewCredential);
+            fail("database booted unexpectedly");
+        } catch (SQLException sqle) {
+            // check that database boot failed at the set debug flag.
+            verifyBootException(sqle, debugFlag);
+        } finally {
+            clearDebugFlag(debugFlag);
+        }
+    }
 
     /*
-     * Recover the database that failied during re-encryption and 
-     * perform some simple sanity check on the database. 
+     * Recover the database that failed during re-encryption and
+     * perform some simple sanity checks on the database.
      */
-    private void recover(int passwordKey) 
-        throws SQLException 
-    {
-        // starting recovery of database with failed Re-encrytpion
+    private void recover(DataSource ds, boolean useEncKey,
+                         Boolean useNewCredential)
+            throws SQLException {
+        // starting recovery of database with failed Re-encryption
         // in debug mode;
 
-        Connection conn = bootDatabase(passwordKey);
+        Connection con = bootDatabase(ds, useEncKey, useNewCredential);
 
-        // verify the contents of the db are ok. 
-        runConsistencyChecker(conn, TEST_TABLE_NAME);
-        // insert some rows, this might fail if anyhing is 
+        // Verify that the contents of the db are ok.
+        runConsistencyChecker(con, TEST_TABLE_NAME);
+        // Insert some rows, this might fail if anything is
         // wrong in the logging system setup.
-        insert(conn, TEST_TABLE_NAME, 100);
-        conn.commit();
-        conn.close();
-    }   
-    
-
-
-    /** *************************************************
-     * Crash/recovery test scenarios during 
-     * encryption of an un-encrypted database.
-     ****************************************************/
-    
-
-
-    // Debug flags that are to be set to simulate a crash 
-    // at different points during (re)encryption of the database. 
-    // these flags should match the flags in the engine code;
-    // these are redifined here to avoid pulling the engine code
-    // into the tests. 
-
-    
-    /*
-      Set to true if we want the re-encryption to crash just 
-      before the commit.
-	*/
-
-	public static final String TEST_REENCRYPT_CRASH_BEFORE_COMMT  = 
-        SanityManager.DEBUG ? "TEST_REENCRYPT_CRASH_BEFORE_COMMT" : null ;
-    public static final String TEST_REENCRYPT_CRASH_AFTER_COMMT  = 
-        SanityManager.DEBUG ? "TEST_REENCRYPT_CRASH_AFTER_COMMT" : null ;
-    public static final String TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY  = 
-        SanityManager.DEBUG ? "TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY" : null ;
-    public static final String TEST_REENCRYPT_CRASH_AFTER_CHECKPOINT  = 
-        SanityManager.DEBUG ? "TEST_REENCRYPT_CRASH_AFTER_CHECKPOINT" : null ;
-                                            
-    public static final String 
+        insert(con, TEST_TABLE_NAME, 100);
+        con.commit();
+        con.close();
+    }
+
+    // Debug flags are set to simulate a crash at different
+    // points during a cryptographic operation on the database.
+    // These flags should match the flags in the engine code, and they
+    // are redefined here to avoid pulling the engine code into the tests.
+
+	private static final String TEST_REENCRYPT_CRASH_BEFORE_COMMT =
+            "TEST_REENCRYPT_CRASH_BEFORE_COMMT";
+    private static final String TEST_REENCRYPT_CRASH_AFTER_COMMT =
+            "TEST_REENCRYPT_CRASH_AFTER_COMMT";
+    private static final String TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY =
+        "TEST_REENCRYPT_CRASH_AFTER_SWITCH_TO_NEWKEY";
+    private static final String TEST_REENCRYPT_CRASH_AFTER_CHECKPOINT =
+        "TEST_REENCRYPT_CRASH_AFTER_CHECKPOINT";
+    private static final String
         TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_LOGFILE_DELETE =
-        SanityManager.DEBUG ?
-        "TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_LOGFILE_DELETE" : null;
-    public static final String 
+            "TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_LOGFILE_DELETE";
+    private static final String
         TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_REVERTING_KEY =
-        SanityManager.DEBUG ?
-        "TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_REVERTING_KEY" : null;
-    public static final String 
+            "TEST_REENCRYPT_CRASH_AFTER_RECOVERY_UNDO_REVERTING_KEY";
+    private static final String
         TEST_REENCRYPT_CRASH_BEFORE_RECOVERY_FINAL_CLEANUP =
-        SanityManager.DEBUG ?
-        "TEST_REENCRYPT_CRASH_BEFORE_RECOVERY_FINAL_CLEANUP" : null;
-    
-    
-    void setDebugFlag(String debugFlag) {
+            "TEST_REENCRYPT_CRASH_BEFORE_RECOVERY_FINAL_CLEANUP";
+
+    private void setDebugFlag(String debugFlag) {
         if (SanityManager.DEBUG) {
             SanityManager.DEBUG_SET(debugFlag);
         }
     }
 
-    void clearDebugFlag(String debugFlag) {
+    private void clearDebugFlag(String debugFlag) {
         if (SanityManager.DEBUG) {
             SanityManager.DEBUG_CLEAR(debugFlag);
         }
     }
 
-    /*
-     * verify that database boot failed when a debug flag is set. 
-     */
-    private void verifyException(SQLException sqle, String debugFlag) 
-    {
-        boolean expectedExcepion = false ;
-        if (sqle != null) 
-        {
-            
-            if (sqle.getSQLState() != null && 
-                sqle.getSQLState().equals("XJ040")) 
-            {
-                // boot failed as expected with the  debug flag
-                // now check if it failed with specifed debug flags.
-                SQLException ne = sqle.getNextException();
-                if (ne != null) {
-                    String message = ne.getMessage();
-                    // check if debug flag exists in the message
-                    if (message.indexOf(debugFlag) != -1)
-                    {
-                        expectedExcepion = true;
-                    }
-                }
-            }
-
-            if (!expectedExcepion)
-                dumpSQLException(sqle);
-        } 
-        else 
-        {
-            if (SanityManager.DEBUG) 
-            {
-                logMessage("Did not crash at " + debugFlag);
+    /**
+     * Verifies that database boot failed because of the right reasons.
+     *
+     * @param sqle the exception thrown when
+     * @param debugFlag the debug flag that was set before booting
+     * @throws junit.framework.AssertionFailedError if the boot failure is
+     *      deemed invalid
+     */
+    private void verifyBootException(SQLException sqle, String debugFlag) {
+        assertSQLState("XJ040", sqle);
+        // Boot failed as expected triggered by a debug flag.
+        // Now check if it failed because of the expected debug flag.
+        SQLException ne = sqle.getNextException();
+        while (ne != null) {
+            String message = ne.getMessage();
+            // Check if debug flag exists in the message.
+            if (message.indexOf(debugFlag) != -1) {
+                return;
             }
+            ne = ne.getNextException();
         }
+        fail("real error or wrong debug flag triggered crash", sqle);
     }
 
-
-    /* 
-     * create the tables that are used by this test.
-     * @param  conn  connection to the database.
-     * @param  tableName  Name of the table to create.
+    /**
+     * Creates the table that is used by this test.
+     *
+     * @param con connection to the database
+     * @param tableName  name of the table to create
      * @exception SQLException if any database exception occurs.
      */
-    void createTable(Connection conn, 
-                     String tableName) throws SQLException {
-
-			Statement s = conn.createStatement();
-			s.executeUpdate("CREATE TABLE " + tableName + 
-							"(id INT," +
-							"name CHAR(200))");
-			s.executeUpdate("create index " + tableName + "_id_idx on " + 
-							tableName + "(id)");
-			s.close();
+    private void createTable(Connection con, String tableName)
+            throws SQLException {
+        Statement s = con.createStatement();
+        s.executeUpdate("CREATE TABLE " + tableName +
+                        "(id INT," +
+                        "name VARCHAR(200))");
+        s.executeUpdate("create index " + tableName + "_id_idx on " +
+                        tableName + "(id)");
+        s.close();
     }
 
-
     /**
-	 * Run some consistency checks.
-     * @param  conn  connection to the database.
-	 * @param  tableName  consistency checks are performed on this table.
-     * @exception SQLException if any database exception occurs.
+	 * Runs some consistency checks on the specified table.
+     *
+     * @param con connection to the database
+	 * @param tableName target table
+     * @exception SQLException if any database exception occurs
 	 */
-	void runConsistencyChecker(Connection conn, 
-                               String tableName) throws SQLException {
-		Statement stmt = conn.createStatement();
+	private void runConsistencyChecker(Connection con, String tableName)
+            throws SQLException {
+		Statement stmt = con.createStatement();
 		stmt.execute("values SYSCS_UTIL.SYSCS_CHECK_TABLE('APP',  'EMP')");
-        // check the data in the EMP table.
-        select(conn, tableName);
+        // Check the data in the EMP table.
+        verifyContents(con, tableName);
 	}
 
-    		
     /**
-     * Insert some rows into the specified table.
-     * @param  conn  connection to the database.
-     * @param  tableName  name of the table that rows are inserted.
-     * @param  rowCount   Number of rows to Insert.
-     * @exception SQLException if any database exception occurs.
-     */
-    void insert(Connection conn, 
-                String tableName, 
-                int rowCount) throws SQLException 
-    {
-
-        PreparedStatement ps = conn.prepareStatement("INSERT INTO " + 
-                                                     tableName + 
-                                                     " VALUES(?,?)");
-        int startId = findMax(conn, tableName);
-        for (int i = startId; i < rowCount; i++) {
-			
+     * Inserts rows into the specified table.
+     *
+     * @param con connection to the database
+     * @param tableName target table
+     * @param rowCount number of rows to insert
+     * @exception SQLException if any database exception occurs
+     */
+    private void insert(Connection con, String tableName, int rowCount)
+            throws SQLException {
+        PreparedStatement ps = con.prepareStatement(
+                "INSERT INTO " + tableName + " VALUES(?,?)");
+        int startId = findMaxId(con, tableName);
+        int endId = rowCount + startId;
+        for (int i = startId; i < endId; i++) {
             ps.setInt(1, i); // ID
             ps.setString(2 , "skywalker" + i);
             ps.executeUpdate();
         }
         ps.close();
-        conn.commit();
+        con.commit();
     }
 
     /**
-    * find a max value on the give table. 
-    * @param  conn  connection to the database.
-    * @param  tableName  name of the table.
-    * @exception SQLException if any database exception occurs.
-    */
-    private int findMax(Connection conn, 
-                        String tableName) throws SQLException 
-    {
-        Statement s = conn.createStatement();
-        ResultSet rs = s.executeQuery("SELECT max(ID) from " +  
-										  tableName);
-        rs.next();
+     * Returns the highest id in the given table.
+     *
+     * @param con connection to the database.
+     * @param tableName name of the table
+     * @return The highest id.
+     * @exception SQLException if any database exception occurs.
+     */
+    private int findMaxId(Connection con, String tableName)
+            throws SQLException {
+        Statement s = con.createStatement();
+        ResultSet rs = s.executeQuery("SELECT max(ID) from " + tableName);
+        assertTrue(rs.next());
         int max = rs.getInt(1);
         rs.close();
         s.close();
         return max;
     }
 
-
-    /*
-     * read  the rows in the table. 
-     * @param  conn  connection to the database.
-     * @param  tableName  select operation is perfomed on this table.
-     * @exception SQLException if any database exception occurs.
-     */
-    void select(Connection conn , 
-                String tableName) throws SQLException 
-    {
-		
-        Statement s = conn.createStatement();
-        ResultSet rs = s.executeQuery("SELECT ID, name from " +  
-										  tableName + " order by id" );
+    /**
+     * Verifies the rows in the given table.
+     *
+     * @param con connection to the database
+     * @param tableName table to select from
+     * @exception SQLException if any database exception occurs
+     */
+    private void verifyContents(Connection con, String tableName)
+            throws SQLException {
+        Statement s = con.createStatement();
+        ResultSet rs = s.executeQuery(
+                "SELECT ID, name from " +  tableName + " order by id");
         int count = 0;
         int id = 0;
-        while(rs.next())
-        {
+        while (rs.next()) {
             int tid = rs.getInt(1);
             String name = rs.getString(2);
-            if(name.equals("skywalker" + id) && tid!= id)
-            {
-                logMessage("DATA IN THE TABLE IS NOT AS EXPECTED");
-                logMessage("Got :ID=" +  tid + " Name=:" + name);
-                logMessage("Expected: ID=" + id + "Name=" + "skywalker" + id );
-            }
-
+            assertEquals("skywalker" + id, name);
+            assertEquals(id, tid);
             id++;
             count++;
         }
-            
+
         rs.close();
         s.close();
-        conn.commit();
+        con.commit();
     }
 
-
-
-    /*
-     * create an encrypted database.
-     */
-    private Connection createEncryptedDatabase() throws SQLException
-    {
-        String connAttrs = "";
-        if (encryptionType == USING_PASSWORD) 
-        {
+    /**
+     * Creates an encrypted database.
+     *
+     * @param ds database
+     * @param useEncPwd whether to use boot password or encryption key
+     */
+    private Connection createEncryptedDatabase(DataSource ds, boolean useEncPwd)
+            throws SQLException {
+        String connAttrs = "dataEncryption=true;";
+        if (useEncPwd) {
             // create encrypted database.
-            connAttrs = "create=true;dataEncryption=true;bootPassword=" +
-                OLD_PASSWORD;
-        }
-
-        if (encryptionType == USING_KEY) 
-        {
+            connAttrs += "bootPassword=" + OLD_PASSWORD;
+        } else {
             // create an encrypted  database.
-            connAttrs = "create=true;dataEncryption=true;encryptionKey=" +
-                OLD_KEY;
+            connAttrs += "encryptionKey=" + OLD_KEY;
+        }
+        JDBCDataSource.setBeanProperty(ds, "createDatabase", "create");
+        JDBCDataSource.setBeanProperty(ds, "connectionAttributes", connAttrs);
+        try {
+            return ds.getConnection();
+        } finally {
+            JDBCDataSource.clearStringBeanProperty(ds, "createDatabase");
+            JDBCDataSource.clearStringBeanProperty(ds, "connectionAttributes");
         }
-        
-        return TestUtil.getConnection(currentTestDatabase, connAttrs); 
     }
 
-
-    /*
-     * create an un-encrypted database.
-     */
-    private Connection createDatabase() throws SQLException
-    {
-        return TestUtil.getConnection(currentTestDatabase,  
-                                      "create=true" );
+    /**
+     * Creates an un-encrypted database.
+     *
+     * @param ds database
+     */
+    private Connection createDatabase(DataSource ds)
+            throws SQLException {
+        JDBCDataSource.setBeanProperty(ds, "createDatabase", "create");
+        try {
+            Connection con = ds.getConnection();
+            JDBC.assertNoWarnings(con.getWarnings());
+            return con;
+        } finally {
+            JDBCDataSource.clearStringBeanProperty(ds, "createDatabase");
+        }
     }
 
-
     /**
-     * Re-encrypt the database. 
-     * @exception SQLException if any database exception occurs.
-     */
-    private Connection  reEncryptDatabase() throws SQLException
-    {
-        String connAttrs = "";
-        if (encryptionType == USING_PASSWORD) 
-        {
-            // re-encrypt the database.
-            connAttrs = "bootPassword=" + OLD_PASSWORD + 
+     * Re-encrypts the database.
+     *
+     * @param ds database
+     * @param useEncPwd whether to use boot password or encryption key
+     * @throws SQLException if any database exception occurs
+     */
+    private Connection reEncryptDatabase(DataSource ds, boolean useEncPwd)
+            throws SQLException {
+        String connAttrs;
+        if (useEncPwd) {
+            connAttrs = "bootPassword=" + OLD_PASSWORD +
                 ";newBootPassword=" + NEW_PASSWORD;
-        }
-
-        if (encryptionType == USING_KEY) 
-        {
-            // re-encrypt the database.
-            connAttrs = "encryptionKey=" + OLD_KEY + 
+        } else {
+            connAttrs = "encryptionKey=" + OLD_KEY +
                 ";newEncryptionKey=" + NEW_KEY;
         }
-        
-        if (verbose)
-            logMessage("re-encrypting " + currentTestDatabase + 
-                       " with " + connAttrs);
 
-        return TestUtil.getConnection(currentTestDatabase, connAttrs); 
+        JDBCDataSource.setBeanProperty(ds, "connectionAttributes", connAttrs);
+        println("re-encrypting " + db(ds) + " with " + connAttrs);
+        // Re-encrypt the database.
+        try {
+            return ds.getConnection();
+        } finally {
+            JDBCDataSource.clearStringBeanProperty(ds, "connectionAttributes");
+        }
     }
 
-    
     /**
-     * Encrypt an un-encrypted atabase. 
+     * Encrypts an un-encrypted database.
+     *
+     * @param ds database
+     * @param useEncPwd whether to use boot password or encryption key
      * @exception SQLException if any database exception occurs.
      */
-    private Connection encryptDatabase() 
-        throws SQLException
-    {
-        String connAttrs = "";
-        if (encryptionType == USING_PASSWORD) 
-        {
-            //encrypt an existing database.
-            connAttrs = "dataEncryption=true;bootPassword=" + OLD_PASSWORD;
-        }
-        if (encryptionType == USING_KEY) 
-        {
-            //encrypt an existing database.
-            connAttrs = "dataEncryption=true;encryptionKey=" + OLD_KEY;
+    private Connection encryptDatabase(DataSource ds, boolean useEncPwd)
+        throws SQLException {
+        String connAttrs = "dataEncryption=true;";
+        if (useEncPwd) {
+            connAttrs += "bootPassword=" + OLD_PASSWORD;
+        } else {
+            connAttrs += "encryptionKey=" + OLD_KEY;
         }
 
-        if (verbose)
-            logMessage("encrypting " + currentTestDatabase + 
-                       " with " + connAttrs);
-        return TestUtil.getConnection(currentTestDatabase, connAttrs); 
+        JDBCDataSource.setBeanProperty(ds, "connectionAttributes", connAttrs);
+        println("encrypting " + db(ds) + " with " + connAttrs);
+        //Encrypt the existing database.
+        try {
+            return ds.getConnection();
+        } finally {
+            JDBCDataSource.clearStringBeanProperty(ds, "connectionAttributes");
+        }
     }
-    
 
     /**
-     * Boot the database. 
-     * @param passwordKey the password/key to use.  
+     * Boots the database.
+     *
+     * @param ds database
+     * @param useEncPwd whether to use boot password or encryption key
+     * @param useNewCredential tri-state telling whether to use the old, the
+     *      new, or no credential when booting the database
      * @exception SQLException if any database exception occurs.
      */
-    Connection bootDatabase(int passwordKey)
-        throws SQLException 
-    {
-
+    private Connection bootDatabase(DataSource ds,
+                                    boolean useEncPwd, Boolean useNewCredential)
+            throws SQLException {
         String connAttrs = "";
-        if (encryptionType == USING_PASSWORD) 
-        {
-            if (passwordKey == NEW)
+        if (useEncPwd) {
+            if (Boolean.TRUE.equals(useNewCredential)) {
                 connAttrs = "bootPassword=" + NEW_PASSWORD;
-            else if (passwordKey == OLD)
+            } else if (Boolean.FALSE.equals(useNewCredential)) {
                 connAttrs = "bootPassword=" + OLD_PASSWORD;
-        }
-
-        
-        if (encryptionType == USING_KEY) 
-        {
-            if (passwordKey == NEW)
+            }
+        } else {
+            if (Boolean.TRUE.equals(useNewCredential)) {
                 connAttrs = "encryptionKey=" + NEW_KEY;
-            else if (passwordKey == OLD)
+            } else if (Boolean.FALSE.equals(useNewCredential)) {
                 connAttrs = "encryptionKey=" + OLD_KEY;
+            }
         }
 
-        if (verbose)
-            logMessage("booting " + currentTestDatabase + 
-                   " with " + connAttrs);
-        return TestUtil.getConnection(currentTestDatabase, connAttrs); 
+        JDBCDataSource.setBeanProperty(ds, "connectionAttributes", connAttrs);
+        println("booting " + db(ds) +
+                (connAttrs.length() > 0 ? " with " + connAttrs : ""));
+        try {
+            return ds.getConnection();
+        } finally {
+            JDBCDataSource.clearStringBeanProperty(ds, "connectionAttributes");
+        }
     }
 
-
-
-    /**
-	 * Shutdown the datbase
-	 */
-	void shutdown() {
-
-        if (verbose)
-            logMessage("Shutdown " + currentTestDatabase);
-		try{
-			//shutdown
-			TestUtil.getConnection(currentTestDatabase, "shutdown=true");
-		}catch(SQLException se){
-			if (se.getSQLState() == null || !(se.getSQLState().equals("08006")))
-            {
-                // database was not shutdown properly
-				dumpSQLException(se);
-            }
+    /** Verifies if the operation constant is a known operation. */
+    private static void verifyOperation(int operation) {
+        switch (operation) {
+            case OP_ENCRYPT:
+            //case OP_DECRYPT:
+            case OP_REENCRYPT:
+                return;
+            default:
+                fail("unknown operation constant: " + operation);
         }
-        
-
     }
 
-    /**
-     * dump the SQLException to the standard output.
-	 */
-	private void dumpSQLException(SQLException sqle) {
-		
-		org.apache.derby.tools.JDBCDisplayUtil.	ShowSQLException(System.out, sqle);
-		sqle.printStackTrace(System.out);
-	}
-
-
-    void logMessage(String str)
-    {
-        System.out.println(str);
-    }
-	
-	
-	public static void main(String[] argv) throws Throwable {
-		
-        ReEncryptCrashRecovery test = new ReEncryptCrashRecovery();
+    /** Extracts the database name from the data source. */
+    private static String db(DataSource ds) {
         try {
-            test.runTest();
+            return (String)JDBCDataSource.getBeanProperty(ds, "databaseName");
+        } catch (Exception e) {
+            return "<unknown/error>";
         }
-        catch (SQLException sqle) {
-			org.apache.derby.tools.JDBCDisplayUtil.ShowSQLException(
-                System.out, sqle);
-			sqle.printStackTrace(System.out);
-		}
     }
 }

Modified: db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/_Suite.java
URL: http://svn.apache.org/viewvc/db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/_Suite.java?rev=1392375&r1=1392374&r2=1392375&view=diff
==============================================================================
--- db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/_Suite.java
(original)
+++ db/derby/code/trunk/java/testing/org/apache/derbyTesting/functionTests/tests/store/_Suite.java
Mon Oct  1 15:05:48 2012
@@ -98,6 +98,7 @@ public class _Suite extends BaseTestCase
             suite.addTest(EncryptionKeyDESTest.suite());
             suite.addTest(EncryptionAESTest.suite());
             suite.addTest(EncryptDatabaseTest.suite());
+            suite.addTest(CryptoCrashRecoveryTest.suite());
         }
 
         return suite;



Mime
View raw message