Fix CalendarProvider2Test

1. Add authority into ProviderInfo
2. Add more features we needed in IsolatedContext
3. testInsertOriginalTimezoneInExtProperties is removed as we dun have this extended property anymore
4. Fix bug in instance search due to wrong order of selection args
5. Fix bug that dirty is not marked to 1 when attendee of event is deleted

Bug: 20715117

Change-Id: I494348742491eedf99355b44378d75e637b1e3c7
diff --git a/src/com/android/providers/calendar/CalendarProvider2.java b/src/com/android/providers/calendar/CalendarProvider2.java
index 5002177..73a2275 100644
--- a/src/com/android/providers/calendar/CalendarProvider2.java
+++ b/src/com/android/providers/calendar/CalendarProvider2.java
@@ -179,14 +179,6 @@
     private CalendarDatabaseHelper mDbHelper;
     private CalendarInstancesHelper mInstancesHelper;
 
-    // The extended property name for storing an Event original Timezone.
-    // Due to an issue in Calendar Server restricting the length of the name we
-    // had to strip it down
-    // TODO - Better name would be:
-    // "com.android.providers.calendar.CalendarSyncAdapter#originalTimezone"
-    protected static final String EXT_PROP_ORIGINAL_TIMEZONE =
-        "CalendarSyncAdapter#originalTimezone";
-
     private static final String SQL_SELECT_EVENTSRAWTIMES = "SELECT " +
             CalendarContract.EventsRawTimes.EVENT_ID + ", " +
             CalendarContract.EventsRawTimes.DTSTART_2445 + ", " +
@@ -1088,7 +1080,6 @@
             long rangeEnd, String[] projection, String selection, String[] selectionArgs,
             String sort, boolean searchByDay, boolean forceExpansion,
             String instancesTimezone, boolean isHomeTimezone) {
-
         mDb = mDbHelper.getWritableDatabase();
         qb.setTables(INSTANCE_QUERY_TABLES);
         qb.setProjectionMap(sInstancesProjectionMap);
@@ -1116,8 +1107,6 @@
         if (selectionArgs == null) {
             selectionArgs = newSelectionArgs;
         } else {
-            // The appendWhere pieces get added first, so put the
-            // newSelectionArgs first.
             selectionArgs = combine(newSelectionArgs, selectionArgs);
         }
         return qb.query(mDb, projection, selection, selectionArgs, null /* groupBy */,
@@ -1237,15 +1226,12 @@
     }
 
     @VisibleForTesting
-    String[] constructSearchArgs(String[] tokens, long rangeBegin, long rangeEnd) {
+    String[] constructSearchArgs(String[] tokens) {
         int numCols = SEARCH_COLUMNS.length;
-        int numArgs = tokens.length * numCols + 2;
-        // the additional two elements here are for begin/end time
+        int numArgs = tokens.length * numCols;
         String[] selectionArgs = new String[numArgs];
-        selectionArgs[0] =  String.valueOf(rangeEnd);
-        selectionArgs[1] =  String.valueOf(rangeBegin);
         for (int j = 0; j < tokens.length; j++) {
-            int start = 2 + numCols * j;
+            int start = numCols * j;
             for (int i = start; i < start + numCols; i++) {
                 selectionArgs[i] = "%" + tokens[j] + "%";
             }
@@ -1262,13 +1248,13 @@
         qb.setProjectionMap(sInstancesProjectionMap);
 
         String[] tokens = tokenizeSearchQuery(query);
-        String[] newSelectionArgs = constructSearchArgs(tokens, rangeBegin, rangeEnd);
+        String[] searchArgs = constructSearchArgs(tokens);
+        String[] timeRange = new String[] {String.valueOf(rangeEnd), String.valueOf(rangeBegin)};
         if (selectionArgs == null) {
-            selectionArgs = newSelectionArgs;
+            selectionArgs = combine(timeRange, searchArgs);
         } else {
-            // The appendWhere pieces get added first, so put the
-            // newSelectionArgs first.
-            selectionArgs = combine(newSelectionArgs, selectionArgs);
+            // where clause comes first, so put selectionArgs before searchArgs.
+            selectionArgs = combine(timeRange, selectionArgs, searchArgs);
         }
         // we pass this in as a HAVING instead of a WHERE so the filtering
         // happens after the grouping
@@ -1304,7 +1290,6 @@
             );
             qb.appendWhere(SQL_WHERE_INSTANCES_BETWEEN);
         }
-
         return qb.query(mDb, projection, selection, selectionArgs,
                 Tables.INSTANCES + "." + Instances._ID /* groupBy */,
                 searchWhere /* having */, sort);
@@ -2189,8 +2174,8 @@
                 }
                 if (updatedValues.containsKey(Events.ORIGINAL_SYNC_ID)
                         && !updatedValues.containsKey(Events.ORIGINAL_ID)) {
-                    long originalId = getOriginalId(updatedValues
-                            .getAsString(Events.ORIGINAL_SYNC_ID),
+                    long originalId = getOriginalId(updatedValues.getAsString(
+                                    Events.ORIGINAL_SYNC_ID),
                             updatedValues.getAsString(Events.CALENDAR_ID));
                     if (originalId != -1) {
                         updatedValues.put(Events.ORIGINAL_ID, originalId);
@@ -3343,13 +3328,13 @@
                 // event that we just duplicated on the previous iteration.
                 if (eventId != prevEventId) {
                     mDbHelper.duplicateEvent(eventId);
-                    prevEventId = eventId;
                 }
                 mDb.delete(table, SQL_WHERE_ID, new String[]{String.valueOf(id)});
                 if (eventId != prevEventId) {
                     mDb.update(Tables.EVENTS, dirtyValues, SQL_WHERE_ID,
                             new String[] { String.valueOf(eventId)} );
                 }
+                prevEventId = eventId;
                 count++;
             }
         } finally {
diff --git a/tests/src/com/android/providers/calendar/CalendarProvider2Test.java b/tests/src/com/android/providers/calendar/CalendarProvider2Test.java
index 5f2ebf4..98c4b6a 100644
--- a/tests/src/com/android/providers/calendar/CalendarProvider2Test.java
+++ b/tests/src/com/android/providers/calendar/CalendarProvider2Test.java
@@ -23,6 +23,8 @@
 import android.content.ContentValues;
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.pm.ProviderInfo;
 import android.content.res.Resources;
 import android.database.Cursor;
 import android.database.MatrixCursor;
@@ -146,6 +148,11 @@
         public boolean stopService(Intent service) {
             return false;
         }
+
+        @Override
+        public PackageManager getPackageManager() {
+            return getContext().getPackageManager();
+        }
     }
 
     /**
@@ -945,10 +952,21 @@
                 new MockContext2(), // The context that most methods are delegated to
                 getContext(), // The context that file methods are delegated to
                 filenamePrefix);
-        mContext = new IsolatedContext(mResolver, targetContextWrapper);
+        mContext = new IsolatedContext(mResolver, targetContextWrapper) {
+            @Override
+            public Object getSystemService(String name) {
+                // for accessing wakelock.
+                if (Context.POWER_SERVICE.equals(name)) {
+                    return getContext().getSystemService(name);
+                }
+                return super.getSystemService(name);
+            }
+        };
 
         mProvider = new CalendarProvider2ForTesting();
-        mProvider.attachInfo(mContext, null);
+        ProviderInfo info = new ProviderInfo();
+        info.authority = CalendarContract.AUTHORITY;
+        mProvider.attachInfoForTesting(mContext, info);
 
         mResolver.addProvider(CalendarContract.AUTHORITY, mProvider);
         mResolver.addProvider("subscribedfeeds", new MockProvider("subscribedfeeds"));
@@ -1339,7 +1357,7 @@
                 .appendQueryParameter(Calendars.ACCOUNT_NAME, account)
                 .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build();
     }
-    
+
     public void testInsertUpdateDeleteColor() throws Exception {
         // Calendar Color
         long colorType = Colors.TYPE_CALENDAR;
@@ -1735,26 +1753,20 @@
 
     @SmallTest @Smoke
     public void testConstructSearchArgs() {
-        long rangeBegin = 0;
-        long rangeEnd = 10;
-
         String[] tokens = new String[] {"red"};
-        String[] expected = new String[] {"10", "0", "%red%", "%red%",
+        String[] expected = new String[] {"%red%", "%red%",
                 "%red%", "%red%", "%red%" };
-        assertArrayEquals(expected, mProvider.constructSearchArgs(tokens,
-                rangeBegin, rangeEnd));
+        assertArrayEquals(expected, mProvider.constructSearchArgs(tokens));
 
         tokens = new String[] {"red", "blue"};
-        expected = new String[] { "10", "0", "%red%", "%red%", "%red%",
+        expected = new String[] { "%red%", "%red%", "%red%",
                 "%red%", "%red%", "%blue%", "%blue%",
                 "%blue%", "%blue%","%blue%"};
-        assertArrayEquals(expected, mProvider.constructSearchArgs(tokens,
-                rangeBegin, rangeEnd));
+        assertArrayEquals(expected, mProvider.constructSearchArgs(tokens));
 
         tokens = new String[] {};
-        expected = new String[] {"10", "0" };
-        assertArrayEquals(expected, mProvider.constructSearchArgs(tokens,
-                rangeBegin, rangeEnd));
+        expected = new String[] {};
+        assertArrayEquals(expected, mProvider.constructSearchArgs(tokens));
     }
 
     public void testInstanceSearchQuery() throws Exception {
@@ -1950,7 +1962,7 @@
 
         assertEquals(0, deletes);
     }
-    
+
     public void testCalendarAlerts() throws Exception {
         // This projection is from AlertActivity; want to make sure it works.
         String[] projection = new String[] {
@@ -1967,11 +1979,17 @@
                 CalendarContract.CalendarAlerts.STATE,            // 10
                 CalendarContract.CalendarAlerts.ALARM_TIME,       // 11
         };
-        testInsertNormalEvents(); // To initialize
 
-        Uri alertUri = CalendarContract.CalendarAlerts.insert(mResolver, 1 /* eventId */,
+        mCalendarId = insertCal("CalendarTestAttendees", DEFAULT_TIMEZONE);
+        String calendarIdString = Integer.toString(mCalendarId);
+        checkEvents(0, mDb, calendarIdString);
+        Uri eventUri = insertEvent(mCalendarId, findEvent("normal0"));
+        checkEvents(1, mDb, calendarIdString);
+        long eventId = ContentUris.parseId(eventUri);
+
+        Uri alertUri = CalendarContract.CalendarAlerts.insert(mResolver, eventId /* eventId */,
                 2 /* begin */, 3 /* end */, 4 /* alarmTime */, 5 /* minutes */);
-        CalendarContract.CalendarAlerts.insert(mResolver, 1 /* eventId */,
+        CalendarContract.CalendarAlerts.insert(mResolver, eventId /* eventId */,
                 2 /* begin */, 7 /* end */, 8 /* alarmTime */, 9 /* minutes */);
 
         // Regular query
@@ -2279,7 +2297,7 @@
                             DEFAULT_ACCOUNT, DEFAULT_ACCOUNT_TYPE), extended);
             testAndClearDirty(eventId, syncAdapter ? 0 : 1);
             testQueryCount(CalendarContract.ExtendedProperties.CONTENT_URI,
-                    "event_id=" + eventId, 2);
+                    "event_id=" + eventId, 1);
         } else {
             // Confirm that inserting as app fails.
             try {
@@ -2324,7 +2342,7 @@
                     null /* where */, null /* selectionArgs */));
             testAndClearDirty(eventId, syncAdapter ? 0 : 1);
             testQueryCount(CalendarContract.ExtendedProperties.CONTENT_URI,
-                    "event_id=" + eventId, 2);
+                    "event_id=" + eventId, 1);
         }
 
         // Now test deletes
@@ -2356,7 +2374,8 @@
                     null /* where */, null /* selectionArgs */));
 
             testAndClearDirty(eventId, syncAdapter ? 0 : 1);
-            testQueryCount(CalendarContract.ExtendedProperties.CONTENT_URI, "event_id=" + eventId, 1);
+            testQueryCount(CalendarContract.ExtendedProperties.CONTENT_URI, "event_id=" + eventId,
+                    0);
         }
     }
 
@@ -2815,8 +2834,8 @@
     public static final Uri PROPERTIES_CONTENT_URI =
             Uri.parse("content://" + CalendarContract.AUTHORITY + "/properties");
 
-    public static final int COLUMN_KEY_INDEX = 1;
-    public static final int COLUMN_VALUE_INDEX = 0;
+    public static final int COLUMN_KEY_INDEX = 0;
+    public static final int COLUMN_VALUE_INDEX = 1;
 
     public void testGetProviderProperties() throws CalendarCache.CacheException {
         CalendarDatabaseHelper helper = (CalendarDatabaseHelper) getProvider().getDatabaseHelper();
@@ -2928,51 +2947,6 @@
         assertEquals(1, result);
     }
 
-    public void testInsertOriginalTimezoneInExtProperties() throws Exception {
-        int calId = insertCal("Calendar0", DEFAULT_TIMEZONE);
-
-
-        EventInfo[] events = { new EventInfo("normal0",
-                                        "2008-05-01T00:00:00",
-                                        "2008-05-02T00:00:00",
-                                        false,
-                                        DEFAULT_TIMEZONE) };
-
-        Uri eventUri = insertEvent(calId, events[0]);
-        assertNotNull(eventUri);
-
-        long eventId = ContentUris.parseId(eventUri);
-        assertTrue(eventId > -1);
-
-        // check the inserted event
-        checkEvent(1, events[0].mTitle, events[0].mDtstart, events[0].mDtend, events[0].mAllDay);
-
-        // Should have 1 calendars and 1 event
-        testQueryCount(CalendarContract.Calendars.CONTENT_URI, null /* where */, 1);
-        testQueryCount(CalendarContract.Events.CONTENT_URI, null /* where */, 1);
-
-        // Verify that the original timezone is correct
-        Cursor cursor = mResolver.query(CalendarContract.ExtendedProperties.CONTENT_URI,
-                null/* projection */,
-                "event_id=" + eventId,
-                null /* selectionArgs */,
-                null /* sortOrder */);
-        try {
-            // Should have 1 extended property for the original timezone
-            assertEquals(1, cursor.getCount());
-
-            if (cursor.moveToFirst()) {
-                long id = cursor.getLong(1);
-                assertEquals(id, eventId);
-
-                assertEquals(CalendarProvider2.EXT_PROP_ORIGINAL_TIMEZONE, cursor.getString(2));
-                assertEquals(DEFAULT_TIMEZONE, cursor.getString(3));
-            }
-        } finally {
-            cursor.close();
-        }
-    }
-
     /**
      * Verifies that the number of defined calendars meets expectations.
      *