1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/mobile/android/tests/background/junit3/src/helpers/DBHelpers.java Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,84 @@ 1.4 +/* Any copyright is dedicated to the Public Domain. 1.5 + http://creativecommons.org/publicdomain/zero/1.0/ */ 1.6 + 1.7 +package org.mozilla.gecko.background.helpers; 1.8 + 1.9 +import android.database.Cursor; 1.10 +import android.database.sqlite.SQLiteDatabase; 1.11 +import junit.framework.Assert; 1.12 + 1.13 +public class DBHelpers { 1.14 + 1.15 + /* 1.16 + * Works for strings and int-ish values. 1.17 + */ 1.18 + public static void assertCursorContains(Object[][] expected, Cursor actual) { 1.19 + Assert.assertEquals(expected.length, actual.getCount()); 1.20 + int i = 0, j = 0; 1.21 + Object[] row; 1.22 + 1.23 + do { 1.24 + row = expected[i]; 1.25 + for (j = 0; j < row.length; ++j) { 1.26 + Object atIndex = row[j]; 1.27 + if (atIndex == null) { 1.28 + continue; 1.29 + } 1.30 + if (atIndex instanceof String) { 1.31 + Assert.assertEquals(atIndex, actual.getString(j)); 1.32 + } else { 1.33 + Assert.assertEquals(atIndex, actual.getInt(j)); 1.34 + } 1.35 + } 1.36 + ++i; 1.37 + } while (actual.moveToPosition(i)); 1.38 + } 1.39 + 1.40 + public static int getRowCount(SQLiteDatabase db, String table) { 1.41 + return getRowCount(db, table, null, null); 1.42 + } 1.43 + 1.44 + public static int getRowCount(SQLiteDatabase db, String table, String selection, String[] selectionArgs) { 1.45 + final Cursor c = db.query(table, null, selection, selectionArgs, null, null, null); 1.46 + try { 1.47 + return c.getCount(); 1.48 + } finally { 1.49 + c.close(); 1.50 + } 1.51 + } 1.52 + 1.53 + /** 1.54 + * Returns an ID that is non-existent in the given sqlite table. Assumes that a column named 1.55 + * "id" exists. 1.56 + */ 1.57 + public static int getNonExistentID(SQLiteDatabase db, String table) { 1.58 + // XXX: We should use selectionArgs to concatenate table, but sqlite throws a syntax error on 1.59 + // "?" because it wants to ensure id is a valid column in table. 1.60 + final Cursor c = db.rawQuery("SELECT MAX(id) + 1 FROM " + table, null); 1.61 + try { 1.62 + if (!c.moveToNext()) { 1.63 + return 0; 1.64 + } 1.65 + return c.getInt(0); 1.66 + } finally { 1.67 + c.close(); 1.68 + } 1.69 + } 1.70 + 1.71 + /** 1.72 + * Returns an ID that exists in the given sqlite table. Assumes that a column named * "id" 1.73 + * exists. 1.74 + */ 1.75 + public static long getExistentID(SQLiteDatabase db, String table) { 1.76 + final Cursor c = db.query(table, new String[] {"id"}, null, null, null, null, null, "1"); 1.77 + try { 1.78 + if (!c.moveToNext()) { 1.79 + throw new IllegalStateException("Given table does not contain any entries."); 1.80 + } 1.81 + return c.getInt(0); 1.82 + } finally { 1.83 + c.close(); 1.84 + } 1.85 + } 1.86 + 1.87 +}