Last active
June 26, 2021 13:59
-
-
Save richardleggett/8318730eccb3cdc6316d to your computer and use it in GitHub Desktop.
Using SQLCipher with ProviderTestCase2 Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package my.app.test; | |
import android.content.ContentResolver; | |
import android.content.Context; | |
import android.content.SyncInfo; | |
import android.os.Environment; | |
import android.test.ProviderTestCase2; | |
import android.util.Log; | |
import net.sqlcipher.database.SQLiteDatabase; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.nio.channels.FileChannel; | |
/** | |
* Base class for any test cases that use the MyContentProvider. Automatically uses a | |
* MockContentResolver to avoid modifying the regular database. | |
*/ | |
abstract public class BaseMyContentProviderTestCase extends ProviderTestCase2<MyContentProvider> { | |
private static final String TAG = BaseMyContentProviderTestCase.class.getSimpleName(); | |
/** | |
* Default constructor as required | |
*/ | |
public BaseMyContentProviderTestCase() { | |
super(MyContentProvider.class, MyContentProvider.AUTHORITY); | |
} | |
@Override | |
protected void setUp() throws Exception { | |
super.setUp(); | |
// initialize SQLCipher with correct Context and file path for these tests | |
SQLiteDatabase.loadLibs(getMockContext(), | |
getMockContext().getDatabasePath(MyDatabaseHelper.DB_NAME).getParentFile()); | |
// make sure SyncAdapter doesn't try to run | |
ContentResolver.cancelSync(SyncAdapter.getAccount(getMockContext()), | |
MyContentProvider.AUTHORITY); | |
// wait here until SyncAdapter finishes (or we will get a ReadOnlyDatabaseException after | |
// due to the :sync process accessing at the same time) | |
boolean isSyncing; | |
do { | |
isSyncing = false; | |
for (SyncInfo syncInfo : ContentResolver.getCurrentSyncs()) { | |
if(syncInfo.authority.equals(MyContentProvider.AUTHORITY)) { | |
isSyncing = true; | |
break; | |
} | |
} | |
Thread.sleep(10); | |
} while(isSyncing); | |
} | |
@Override | |
protected void tearDown() throws Exception { | |
super.tearDown(); | |
getMockContext().getDatabasePath(MyDatabaseHelper.DB_NAME).delete(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One issue to tackle, the above stops an ongoing SyncAdapter and waits for it to finish before running the next test. Debugging shows it is running on start due to the setSyncAutomatically() in the Application setup. But technically it could also start again during the test (e.g. due to network "tickle") as it's a different process. Need to permanently disable automatic syncing once it's been set without side effects.