AlertServiceTest.java 47.5 KB
Newer Older
Michael Chan's avatar
Michael Chan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Copyright (C) 2012 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 com.android.calendar.alerts;

import static android.app.Notification.PRIORITY_DEFAULT;
import static android.app.Notification.PRIORITY_HIGH;
import static android.app.Notification.PRIORITY_MIN;

23 24
import android.app.AlarmManager;
import android.app.PendingIntent;
Michael Chan's avatar
Michael Chan committed
25 26 27 28 29 30 31
import android.content.SharedPreferences;
import android.database.MatrixCursor;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.CalendarAlerts;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.Smoke;
Sara Ting's avatar
Sara Ting committed
32 33
import android.text.format.DateUtils;
import android.text.format.Time;
Michael Chan's avatar
Michael Chan committed
34 35

import com.android.calendar.GeneralPreferences;
36
import com.android.calendar.alerts.AlertService.NotificationInfo;
Michael Chan's avatar
Michael Chan committed
37 38
import com.android.calendar.alerts.AlertService.NotificationWrapper;

39 40
import junit.framework.Assert;

Michael Chan's avatar
Michael Chan committed
41 42 43 44 45 46 47 48 49
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

public class AlertServiceTest extends AndroidTestCase {

    class MockSharedPreferences implements SharedPreferences {

50
        private Boolean mVibrate;
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        private String mRingtone;
        private Boolean mPopup;

        // Strict mode will fail if a preference key is queried more than once.
        private boolean mStrict = false;

        MockSharedPreferences() {
            this(false);
        }

        MockSharedPreferences(boolean strict) {
            super();
            init();
            this.mStrict = strict;
        }

        void init() {
68
            mVibrate = true;
69 70 71
            mRingtone = "/some/cool/ringtone";
            mPopup = true;
        }
Michael Chan's avatar
Michael Chan committed
72 73 74

        @Override
        public boolean contains(String key) {
75
            if (GeneralPreferences.KEY_ALERTS_VIBRATE.equals(key)) {
Michael Chan's avatar
Michael Chan committed
76 77 78 79 80 81 82
                return true;
            }
            return false;
        }

        @Override
        public boolean getBoolean(String key, boolean defValue) {
83 84 85 86 87 88 89 90 91 92 93
            if (GeneralPreferences.KEY_ALERTS_VIBRATE.equals(key)) {
                if (mVibrate == null) {
                    Assert.fail(GeneralPreferences.KEY_ALERTS_VIBRATE
                            + " fetched more than once.");
                }
                boolean val = mVibrate;
                if (mStrict) {
                    mVibrate = null;
                }
                return val;
            }
Michael Chan's avatar
Michael Chan committed
94
            if (GeneralPreferences.KEY_ALERTS_POPUP.equals(key)) {
95 96 97 98 99 100 101 102
                if (mPopup == null) {
                    Assert.fail(GeneralPreferences.KEY_ALERTS_POPUP + " fetched more than once.");
                }
                boolean val = mPopup;
                if (mStrict) {
                    mPopup = null;
                }
                return val;
Michael Chan's avatar
Michael Chan committed
103 104 105 106 107 108 109
            }
            throw new IllegalArgumentException();
        }

        @Override
        public String getString(String key, String defValue) {
            if (GeneralPreferences.KEY_ALERTS_RINGTONE.equals(key)) {
110 111 112 113 114 115 116 117 118
                if (mRingtone == null) {
                    Assert.fail(GeneralPreferences.KEY_ALERTS_RINGTONE
                            + " fetched more than once.");
                }
                String val = mRingtone;
                if (mStrict) {
                    mRingtone = null;
                }
                return val;
Michael Chan's avatar
Michael Chan committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
            }
            throw new IllegalArgumentException();
        }

        @Override
        public Map<String, ?> getAll() {
            throw new IllegalArgumentException();
        }

        @Override
        public Set<String> getStringSet(String key, Set<String> defValues) {
            throw new IllegalArgumentException();
        }

        @Override
        public int getInt(String key, int defValue) {
            throw new IllegalArgumentException();
        }

        @Override
        public long getLong(String key, long defValue) {
            throw new IllegalArgumentException();
        }

        @Override
        public float getFloat(String key, float defValue) {
            throw new IllegalArgumentException();
        }

        @Override
        public Editor edit() {
            throw new IllegalArgumentException();
        }

        @Override
        public void registerOnSharedPreferenceChangeListener(
                OnSharedPreferenceChangeListener listener) {
            throw new IllegalArgumentException();
        }

        @Override
        public void unregisterOnSharedPreferenceChangeListener(
                OnSharedPreferenceChangeListener listener) {
            throw new IllegalArgumentException();
        }

    }

    // Created these constants so the test cases are shorter
    public static final int SCHEDULED = CalendarAlerts.STATE_SCHEDULED;
    public static final int FIRED = CalendarAlerts.STATE_FIRED;
    public static final int DISMISSED = CalendarAlerts.STATE_DISMISSED;

    public static final int ACCEPTED = Attendees.ATTENDEE_STATUS_ACCEPTED;
    public static final int DECLINED = Attendees.ATTENDEE_STATUS_DECLINED;
    public static final int INVITED = Attendees.ATTENDEE_STATUS_INVITED;
    public static final int TENTATIVE = Attendees.ATTENDEE_STATUS_TENTATIVE;

    class NotificationInstance {
        int mAlertId;
Sara Ting's avatar
Sara Ting committed
179
        int[] mAlertIdsInDigest;
Michael Chan's avatar
Michael Chan committed
180 181 182 183 184 185
        int mPriority;

        public NotificationInstance(int alertId, int priority) {
            mAlertId = alertId;
            mPriority = priority;
        }
Sara Ting's avatar
Sara Ting committed
186 187 188 189 190

        public NotificationInstance(int[] alertIdsInDigest, int priority) {
            mAlertIdsInDigest = alertIdsInDigest;
            mPriority = priority;
        }
Michael Chan's avatar
Michael Chan committed
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    }

    class Alert {
        long mEventId;
        int mAlertStatus;
        int mResponseStatus;
        int mAllDay;
        long mBegin;
        long mEnd;
        int mMinute;
        long mAlarmTime;

        public Alert(long eventId, int alertStatus, int responseStatus, int allDay, long begin,
                long end, int minute, long alarmTime) {
            mEventId = eventId;
            mAlertStatus = alertStatus;
            mResponseStatus = responseStatus;
            mAllDay = allDay;
            mBegin = begin;
            mEnd = end;
            mMinute = minute;
            mAlarmTime = alarmTime;
        }

    }

    class AlertsTable {

        ArrayList<Alert> mAlerts = new ArrayList<Alert>();

        int addAlertRow(long eventId, int alertStatus, int responseStatus, int allDay, long begin,
Sara Ting's avatar
Sara Ting committed
222 223 224
                long end, long alarmTime) {
            Alert a = new Alert(eventId, alertStatus, responseStatus, allDay, begin, end,
                    5 /* minute */, alarmTime);
Michael Chan's avatar
Michael Chan committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
            int id = mAlerts.size();
            mAlerts.add(a);
            return id;
        }

        public MatrixCursor getAlertCursor() {
            MatrixCursor alertCursor = new MatrixCursor(AlertService.ALERT_PROJECTION);

            int i = 0;
            for (Alert a : mAlerts) {
                Object[] ca = {
                        i++,
                        a.mEventId,
                        a.mAlertStatus,
                        "Title" + a.mEventId + " " + a.mMinute,
                        "Loc" + a.mEventId,
                        a.mResponseStatus,
                        a.mAllDay,
                        a.mAlarmTime > 0 ? a.mAlarmTime : a.mBegin - a.mMinute * 60 * 1000,
                        a.mMinute,
                        a.mBegin,
                        a.mEnd,
                        "Desc: " + a.mAlarmTime
                };
                alertCursor.addRow(ca);
            }
            return alertCursor;
        }

    }

256
    class NotificationTestManager extends NotificationMgr {
Michael Chan's avatar
Michael Chan committed
257
        // Expected notifications
258 259 260
        NotificationInstance[] mExpectedNotifications;
        NotificationWrapper[] mActualNotifications;
        boolean[] mCancelled;
Michael Chan's avatar
Michael Chan committed
261 262 263 264

        // CalendarAlerts table
        private ArrayList<Alert> mAlerts;

Sara Ting's avatar
Sara Ting committed
265
        public NotificationTestManager(ArrayList<Alert> alerts, int maxNotifications) {
Michael Chan's avatar
Michael Chan committed
266 267
            assertEquals(0, AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
            mAlerts = alerts;
268 269 270
            mExpectedNotifications = new NotificationInstance[maxNotifications + 1];
            mActualNotifications = new NotificationWrapper[mExpectedNotifications.length];
            mCancelled = new boolean[mExpectedNotifications.length];
Michael Chan's avatar
Michael Chan committed
271 272 273
        }

        public void expectTestNotification(int notificationId, int alertId, int highPriority) {
274 275
            mExpectedNotifications[notificationId] = new NotificationInstance(alertId,
                    highPriority);
Michael Chan's avatar
Michael Chan committed
276 277
        }

Sara Ting's avatar
Sara Ting committed
278
        public void expectTestNotification(int notificationId, int[] alertIds, int priority) {
279 280 281 282 283 284 285 286 287 288
            mExpectedNotifications[notificationId] = new NotificationInstance(alertIds, priority);
        }

        private <T> boolean nullContents(T[] array) {
            for (T item : array) {
                if (item != null) {
                    return false;
                }
            }
            return true;
Sara Ting's avatar
Sara Ting committed
289 290
        }

291 292 293 294
        public void validateNotificationsAndReset() {
            if (nullContents(mExpectedNotifications)) {
                return;
            }
Sara Ting's avatar
Sara Ting committed
295

296 297 298 299 300 301 302 303
            String debugStr = printActualNotifications();
            for (int id = 0; id < mActualNotifications.length; id++) {
                NotificationInstance expected = mExpectedNotifications[id];
                NotificationWrapper actual = mActualNotifications[id];
                if (expected == null) {
                    assertNull("Received unexpected notificationId " + id + debugStr, actual);
                    assertTrue("NotificationId " + id + " should have been cancelled." + debugStr,
                            mCancelled[id]);
Sara Ting's avatar
Sara Ting committed
304
                } else {
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
                    assertNotNull("Expected notificationId " + id + " but it was not posted."
                            + debugStr, actual);
                    assertFalse("NotificationId " + id + " should not have been cancelled."
                            + debugStr, mCancelled[id]);
                    assertEquals("Priority not as expected for notification " + id + debugStr,
                            expected.mPriority, actual.mNotification.priority);
                    if (expected.mAlertIdsInDigest == null) {
                        Alert a = mAlerts.get(expected.mAlertId);
                        assertEquals("Event ID not expected for notification " + id + debugStr,
                                a.mEventId, actual.mEventId);
                        assertEquals("Begin time not expected for notification " + id + debugStr,
                                a.mBegin, actual.mBegin);
                        assertEquals("End time not expected for notification " + id + debugStr,
                                a.mEnd, actual.mEnd);
                    } else {
                        // Notification should be a digest.
                        assertNotNull("Posted notification not a digest as expected." + debugStr,
                                actual.mNw);
                        assertEquals("Number of notifications in digest not as expected."
                                + debugStr, expected.mAlertIdsInDigest.length, actual.mNw.size());
                        for (int i = 0; i < actual.mNw.size(); i++) {
                            Alert a = mAlerts.get(expected.mAlertIdsInDigest[i]);
                            assertEquals("Digest item " + i + ": Event ID not as expected"
                                    + debugStr, a.mEventId, actual.mNw.get(i).mEventId);
                            assertEquals("Digest item " + i + ": Begin time in digest not expected"
                                    + debugStr, a.mBegin, actual.mNw.get(i).mBegin);
                            assertEquals("Digest item " + i + ": End time in digest not expected"
                                    + debugStr, a.mEnd, actual.mNw.get(i).mEnd);
                        }
Sara Ting's avatar
Sara Ting committed
334 335
                    }
                }
336 337 338 339 340
            }

            Arrays.fill(mCancelled, false);
            Arrays.fill(mExpectedNotifications, null);
            Arrays.fill(mActualNotifications, null);
Michael Chan's avatar
Michael Chan committed
341 342
        }

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        private String printActualNotifications() {
            StringBuilder s = new StringBuilder();
            s.append("\n\nNotifications actually posted:\n");
            for (int i = mActualNotifications.length - 1; i >= 0; i--) {
                NotificationWrapper actual = mActualNotifications[i];
                if (actual == null) {
                    continue;
                }
                s.append("Notification " + i + " -- ");
                s.append("priority:" + actual.mNotification.priority);
                if (actual.mNw == null) {
                    s.append(", eventId:" +  actual.mEventId);
                } else {
                    s.append(", eventIds:{");
                    for (int digestIndex = 0; digestIndex < actual.mNw.size(); digestIndex++) {
                        s.append(actual.mNw.get(digestIndex).mEventId + ",");
                    }
                    s.append("}");
                }
                s.append("\n");
Michael Chan's avatar
Michael Chan committed
363
            }
364
            return s.toString();
Michael Chan's avatar
Michael Chan committed
365 366 367 368 369 370 371
        }

        ///////////////////////////////
        // NotificationMgr methods
        @Override
        public void cancel(int id) {
            assertTrue("id out of bound: " + id, 0 <= id);
372 373 374 375 376
            assertTrue("id out of bound: " + id, id < mCancelled.length);
            assertNull("id already used", mActualNotifications[id]);
            assertFalse("id already used", mCancelled[id]);
            mCancelled[id] = true;
            assertNull("Unexpected cancel for id " + id, mExpectedNotifications[id]);
Michael Chan's avatar
Michael Chan committed
377 378
        }

379
        @Override
Michael Chan's avatar
Michael Chan committed
380 381
        public void notify(int id, NotificationWrapper nw) {
            assertTrue("id out of bound: " + id, 0 <= id);
382 383 384
            assertTrue("id out of bound: " + id, id < mExpectedNotifications.length);
            assertNull("id already used: " + id, mActualNotifications[id]);
            mActualNotifications[id] = nw;
Michael Chan's avatar
Michael Chan committed
385 386 387
        }
    }

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    private class MockAlarmManager implements AlarmManagerInterface {
        private int expectedAlarmType = -1;
        private long expectedAlarmTime = -1;

        public void expectAlarmTime(int type, long millis) {
            this.expectedAlarmType = type;
            this.expectedAlarmTime = millis;
        }

        @Override
        public void set(int actualAlarmType, long actualAlarmTime, PendingIntent operation) {
            assertNotNull(operation);
            if (expectedAlarmType != -1) {
                assertEquals("Alarm type not expected.", expectedAlarmType, actualAlarmType);
                assertEquals("Alarm time not expected. Expected:" + DateUtils.formatDateTime(
                        mContext, expectedAlarmTime, DateUtils.FORMAT_SHOW_TIME) + ", actual:"
                        + DateUtils.formatDateTime(mContext, actualAlarmTime,
                        DateUtils.FORMAT_SHOW_TIME), expectedAlarmTime, actualAlarmTime);
            }
        }
    }

Michael Chan's avatar
Michael Chan committed
410 411 412 413 414 415 416
    // TODO
    // Catch updates of new state, notify time, and received time
    // Test ringer, vibrate,
    // Test intents, action email

    @Smoke
    @SmallTest
417
    public void testGenerateAlerts_none() {
Michael Chan's avatar
Michael Chan committed
418 419
        MockSharedPreferences prefs = new MockSharedPreferences();
        AlertsTable at = new AlertsTable();
Sara Ting's avatar
Sara Ting committed
420 421
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts,
                AlertService.MAX_NOTIFICATIONS);
Michael Chan's avatar
Michael Chan committed
422 423 424

        // Test no alert
        long currentTime = 1000000;
425 426
        AlertService.generateAlerts(mContext, ntm, new MockAlarmManager(), prefs,
                at.getAlertCursor(), currentTime, AlertService.MAX_NOTIFICATIONS);
Michael Chan's avatar
Michael Chan committed
427 428 429 430 431
        ntm.validateNotificationsAndReset();
    }

    @Smoke
    @SmallTest
432
    public void testGenerateAlerts_single() {
Michael Chan's avatar
Michael Chan committed
433
        MockSharedPreferences prefs = new MockSharedPreferences();
434
        MockAlarmManager alarmMgr = new MockAlarmManager();
Michael Chan's avatar
Michael Chan committed
435
        AlertsTable at = new AlertsTable();
Sara Ting's avatar
Sara Ting committed
436 437
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts,
                AlertService.MAX_NOTIFICATIONS);
Michael Chan's avatar
Michael Chan committed
438

Sara Ting's avatar
Sara Ting committed
439
        int id = at.addAlertRow(100, SCHEDULED, ACCEPTED, 0 /* all day */, 1300000, 2300000, 0);
Michael Chan's avatar
Michael Chan committed
440 441 442 443 444

        // Test one up coming alert
        long currentTime = 1000000;
        ntm.expectTestNotification(1, id, PRIORITY_HIGH);

445
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(), currentTime,
Sara Ting's avatar
Sara Ting committed
446
                AlertService.MAX_NOTIFICATIONS);
Michael Chan's avatar
Michael Chan committed
447 448 449 450 451
        ntm.validateNotificationsAndReset(); // This wipes out notification
                                             // tests added so far

        // Test half way into an event
        currentTime = 2300000;
452
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, id, PRIORITY_MIN);
Michael Chan's avatar
Michael Chan committed
453

454
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(), currentTime,
Sara Ting's avatar
Sara Ting committed
455
                AlertService.MAX_NOTIFICATIONS);
Michael Chan's avatar
Michael Chan committed
456 457 458 459 460 461
        ntm.validateNotificationsAndReset();

        // Test event ended
        currentTime = 4300000;
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, id, PRIORITY_MIN);

462
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(), currentTime,
Sara Ting's avatar
Sara Ting committed
463 464 465 466 467
                AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();
    }

    @SmallTest
468
    public void testGenerateAlerts_multiple() {
Sara Ting's avatar
Sara Ting committed
469 470
        int maxNotifications = 10;
        MockSharedPreferences prefs = new MockSharedPreferences();
471
        MockAlarmManager alarmMgr = new MockAlarmManager();
Sara Ting's avatar
Sara Ting committed
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
        AlertsTable at = new AlertsTable();
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts, maxNotifications);

        // Current time - 5:00
        long currentTime = createTimeInMillis(5, 0);

        // Set up future alerts.  The real query implementation sorts by descending start
        // time so simulate that here with our order of adds to AlertsTable.
        int id9 = at.addAlertRow(9, SCHEDULED, ACCEPTED, 0, createTimeInMillis(9, 0),
                createTimeInMillis(10, 0), 0);
        int id8 = at.addAlertRow(8, SCHEDULED, ACCEPTED, 0, createTimeInMillis(8, 0),
                createTimeInMillis(9, 0), 0);
        int id7 = at.addAlertRow(7, SCHEDULED, ACCEPTED, 0, createTimeInMillis(7, 0),
                createTimeInMillis(8, 0), 0);

        // Set up concurrent alerts (that started recently).
        int id6 = at.addAlertRow(6, SCHEDULED, ACCEPTED, 0, createTimeInMillis(5, 0),
                createTimeInMillis(5, 40), 0);
        int id5 = at.addAlertRow(5, SCHEDULED, ACCEPTED, 0, createTimeInMillis(4, 55),
                createTimeInMillis(7, 30), 0);
        int id4 = at.addAlertRow(4, SCHEDULED, ACCEPTED, 0, createTimeInMillis(4, 50),
                createTimeInMillis(4, 50), 0);

        // Set up past alerts.
        int id3 = at.addAlertRow(3, SCHEDULED, ACCEPTED, 0, createTimeInMillis(3, 0),
                createTimeInMillis(4, 0), 0);
        int id2 = at.addAlertRow(2, SCHEDULED, ACCEPTED, 0, createTimeInMillis(2, 0),
                createTimeInMillis(3, 0), 0);
        int id1 = at.addAlertRow(1, SCHEDULED, ACCEPTED, 0, createTimeInMillis(1, 0),
                createTimeInMillis(2, 0), 0);

        // Check posted notifications.  The order listed here is the order simulates the
        // order in the real notification bar (last one posted appears on top), so these
        // should be lowest start time on top.
        ntm.expectTestNotification(6, id4, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(5, id5, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(4, id6, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(3, id7, PRIORITY_HIGH); // future
        ntm.expectTestNotification(2, id8, PRIORITY_HIGH); // future
        ntm.expectTestNotification(1, id9, PRIORITY_HIGH); // future
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID,
                new int[] {id3, id2, id1}, PRIORITY_MIN);
514 515
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
Sara Ting's avatar
Sara Ting committed
516 517 518 519 520 521 522 523 524 525 526
        ntm.validateNotificationsAndReset();

        // Increase time by 15 minutes to check that some concurrent events dropped
        // to the low priority bucket.
        currentTime = createTimeInMillis(5, 15);
        ntm.expectTestNotification(4, id5, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(3, id7, PRIORITY_HIGH); // future
        ntm.expectTestNotification(2, id8, PRIORITY_HIGH); // future
        ntm.expectTestNotification(1, id9, PRIORITY_HIGH); // future
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID,
                new int[] {id6, id4, id3, id2, id1}, PRIORITY_MIN);
527 528
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
Sara Ting's avatar
Sara Ting committed
529 530 531 532 533 534 535
        ntm.validateNotificationsAndReset();

        // Increase time so some of the previously future ones change state.
        currentTime = createTimeInMillis(8, 15);
        ntm.expectTestNotification(1, id9, PRIORITY_HIGH); // future
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID,
                new int[] {id8, id7, id6, id5, id4, id3, id2, id1}, PRIORITY_MIN);
536 537
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
Michael Chan's avatar
Michael Chan committed
538 539
        ntm.validateNotificationsAndReset();
    }
540

Sara Ting's avatar
Sara Ting committed
541
    @SmallTest
542
    public void testGenerateAlerts_maxAlerts() {
Sara Ting's avatar
Sara Ting committed
543
        MockSharedPreferences prefs = new MockSharedPreferences();
544
        MockAlarmManager alarmMgr = new MockAlarmManager();
Sara Ting's avatar
Sara Ting committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
        AlertsTable at = new AlertsTable();

        // Current time - 5:00
        long currentTime = createTimeInMillis(5, 0);

        // Set up future alerts.  The real query implementation sorts by descending start
        // time so simulate that here with our order of adds to AlertsTable.
        int id9 = at.addAlertRow(9, SCHEDULED, ACCEPTED, 0, createTimeInMillis(9, 0),
                createTimeInMillis(10, 0), 0);
        int id8 = at.addAlertRow(8, SCHEDULED, ACCEPTED, 0, createTimeInMillis(8, 0),
                createTimeInMillis(9, 0), 0);
        int id7 = at.addAlertRow(7, SCHEDULED, ACCEPTED, 0, createTimeInMillis(7, 0),
                createTimeInMillis(8, 0), 0);

        // Set up concurrent alerts (that started recently).
        int id6 = at.addAlertRow(6, SCHEDULED, ACCEPTED, 0, createTimeInMillis(5, 0),
                createTimeInMillis(5, 40), 0);
        int id5 = at.addAlertRow(5, SCHEDULED, ACCEPTED, 0, createTimeInMillis(4, 55),
                createTimeInMillis(7, 30), 0);
        int id4 = at.addAlertRow(4, SCHEDULED, ACCEPTED, 0, createTimeInMillis(4, 50),
                createTimeInMillis(4, 50), 0);

        // Set up past alerts.
        int id3 = at.addAlertRow(3, SCHEDULED, ACCEPTED, 0, createTimeInMillis(3, 0),
                createTimeInMillis(4, 0), 0);
        int id2 = at.addAlertRow(2, SCHEDULED, ACCEPTED, 0, createTimeInMillis(2, 0),
                createTimeInMillis(3, 0), 0);
        int id1 = at.addAlertRow(1, SCHEDULED, ACCEPTED, 0, createTimeInMillis(1, 0),
                createTimeInMillis(2, 0), 0);

        // Test when # alerts = max.
        int maxNotifications = 6;
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts, maxNotifications);
        ntm.expectTestNotification(6, id4, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(5, id5, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(4, id6, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(3, id7, PRIORITY_HIGH); // future
        ntm.expectTestNotification(2, id8, PRIORITY_HIGH); // future
        ntm.expectTestNotification(1, id9, PRIORITY_HIGH); // future
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID,
                new int[] {id3, id2, id1}, PRIORITY_MIN);
586 587
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
Sara Ting's avatar
Sara Ting committed
588 589 590 591 592 593 594 595 596 597 598
        ntm.validateNotificationsAndReset();

        // Test when # alerts > max.
        maxNotifications = 4;
        ntm = new NotificationTestManager(at.mAlerts, maxNotifications);
        ntm.expectTestNotification(4, id4, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(3, id5, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(2, id6, PRIORITY_HIGH); // concurrent
        ntm.expectTestNotification(1, id7, PRIORITY_HIGH); // future
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID,
                new int[] {id9, id8, id3, id2, id1}, PRIORITY_MIN);
599 600
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
Sara Ting's avatar
Sara Ting committed
601 602
        ntm.validateNotificationsAndReset();
    }
603

604 605 606 607
    /**
     * Test that the SharedPreferences are only fetched once for each setting.
     */
    @SmallTest
608
    public void testGenerateAlerts_sharedPreferences() {
609 610
        MockSharedPreferences prefs = new MockSharedPreferences(true /* strict mode */);
        AlertsTable at = new AlertsTable();
611 612
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts,
                AlertService.MAX_NOTIFICATIONS);
613 614 615 616 617 618

        // Current time - 5:00
        long currentTime = createTimeInMillis(5, 0);

        // Set up future alerts.  The real query implementation sorts by descending start
        // time so simulate that here with our order of adds to AlertsTable.
619
        at.addAlertRow(3, SCHEDULED, ACCEPTED, 0, createTimeInMillis(9, 0),
620
                createTimeInMillis(10, 0), 0);
621
        at.addAlertRow(2, SCHEDULED, ACCEPTED, 0, createTimeInMillis(8, 0),
622
                createTimeInMillis(9, 0), 0);
623
        at.addAlertRow(1, SCHEDULED, ACCEPTED, 0, createTimeInMillis(7, 0),
624 625
                createTimeInMillis(8, 0), 0);

626 627 628 629 630
        // If this does not result in a failure (MockSharedPreferences fails for duplicate
        // queries), then test passes.
        AlertService.generateAlerts(mContext, ntm, new MockAlarmManager(), prefs,
                at.getAlertCursor(), currentTime, AlertService.MAX_NOTIFICATIONS);
    }
631

632 633 634 635 636 637
    public void testGenerateAlerts_refreshTime() {
        AlertsTable at = new AlertsTable();
        MockSharedPreferences prefs = new MockSharedPreferences();
        MockAlarmManager alarmMgr = new MockAlarmManager();
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts,
                AlertService.MAX_NOTIFICATIONS);
638

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        // Since AlertService.processQuery uses DateUtils.isToday instead of checking against
        // the passed in currentTime (not worth allocating the extra Time objects to do so), use
        // today's date for this test.
        Time now = new Time();
        now.setToNow();
        int day = now.monthDay;
        int month = now.month;
        int year = now.year;
        Time yesterday = new Time();
        yesterday.set(System.currentTimeMillis() - DateUtils.DAY_IN_MILLIS);
        Time tomorrow = new Time();
        tomorrow.set(System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS);
        long allDayStart = createTimeInMillis(0, 0, 0, day, month, year, Time.TIMEZONE_UTC);

        /* today 10am - 10:30am */
        int id4 = at.addAlertRow(4, SCHEDULED, ACCEPTED, 0,
                createTimeInMillis(0, 0, 10, day, month, year, Time.getCurrentTimezone()),
                createTimeInMillis(0, 30, 10, day, month, year, Time.getCurrentTimezone()), 0);
        /* today 6am - 6am (0 duration event) */
        int id3 = at.addAlertRow(3, SCHEDULED, ACCEPTED, 0,
                createTimeInMillis(0, 0, 6, day, month, year, Time.getCurrentTimezone()),
                createTimeInMillis(0, 0, 6, day, month, year, Time.getCurrentTimezone()), 0);
        /* today allDay */
        int id2 = at.addAlertRow(2, SCHEDULED, ACCEPTED, 1, allDayStart,
                allDayStart + DateUtils.HOUR_IN_MILLIS * 24, 0);
        /* yesterday 11pm - today 7am (multiday event) */
        int id1 = at.addAlertRow(1, SCHEDULED, ACCEPTED, 0,
                createTimeInMillis(0, 0, 23, yesterday.monthDay, yesterday.month, yesterday.year,
                        Time.getCurrentTimezone()),
                createTimeInMillis(0, 0, 7, day, month, year, Time.getCurrentTimezone()), 0);

        // Test at midnight - next refresh should be 15 min later (15 min into the all
        // day event).
        long currentTime = createTimeInMillis(0, 0, 0, day, month, year, Time.getCurrentTimezone());
        alarmMgr.expectAlarmTime(AlarmManager.RTC, currentTime + 15 * DateUtils.MINUTE_IN_MILLIS);
        ntm.expectTestNotification(4, id1, PRIORITY_HIGH);
        ntm.expectTestNotification(3, id2, PRIORITY_HIGH);
        ntm.expectTestNotification(2, id3, PRIORITY_HIGH);
        ntm.expectTestNotification(1, id4, PRIORITY_HIGH);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();
681

682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
        // Test at 12:30am - next refresh should be 30 min later (1/4 into event 'id1').
        currentTime = createTimeInMillis(0, 30, 0, day, month, year, Time.getCurrentTimezone());
        alarmMgr.expectAlarmTime(AlarmManager.RTC, currentTime + 30 * DateUtils.MINUTE_IN_MILLIS);
        ntm.expectTestNotification(3, id1, PRIORITY_HIGH);
        ntm.expectTestNotification(2, id3, PRIORITY_HIGH);
        ntm.expectTestNotification(1, id4, PRIORITY_HIGH);
        ntm.expectTestNotification(4, id2, PRIORITY_DEFAULT);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();

        // Test at 5:55am - next refresh should be 20 min later (15 min after 'id3').
        currentTime = createTimeInMillis(0, 55, 5, day, month, year, Time.getCurrentTimezone());
        alarmMgr.expectAlarmTime(AlarmManager.RTC, currentTime + 20 * DateUtils.MINUTE_IN_MILLIS);
        ntm.expectTestNotification(2, id3, PRIORITY_HIGH);
        ntm.expectTestNotification(1, id4, PRIORITY_HIGH);
        ntm.expectTestNotification(3, id2, PRIORITY_DEFAULT);
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, id1, PRIORITY_MIN);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();

        // Test at 10:14am - next refresh should be 1 min later (15 min into event 'id4').
        currentTime = createTimeInMillis(0, 14, 10, day, month, year, Time.getCurrentTimezone());
        alarmMgr.expectAlarmTime(AlarmManager.RTC, currentTime + 1 * DateUtils.MINUTE_IN_MILLIS);
        ntm.expectTestNotification(1, id4, PRIORITY_HIGH);
        ntm.expectTestNotification(2, id2, PRIORITY_DEFAULT);
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, new int[] {id3, id1},
                PRIORITY_MIN);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();

        // Test at 10:15am - next refresh should be tomorrow midnight (end of all day event 'id2').
        currentTime = createTimeInMillis(0, 15, 10, day, month, year, Time.getCurrentTimezone());
        alarmMgr.expectAlarmTime(AlarmManager.RTC, createTimeInMillis(0, 0, 23, tomorrow.monthDay,
                tomorrow.month, tomorrow.year, Time.getCurrentTimezone()));
        ntm.expectTestNotification(1, id2, PRIORITY_DEFAULT);
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID,
                new int[] {id4, id3, id1}, PRIORITY_MIN);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, AlertService.MAX_NOTIFICATIONS);
724 725 726
        ntm.validateNotificationsAndReset();
    }

727 728 729 730 731
    private NotificationInfo createNotificationInfo(long eventId) {
        return new NotificationInfo("eventName", "location", "description", 100L, 200L, eventId,
                false, false);
    }

Sara Ting's avatar
Sara Ting committed
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    private static long createTimeInMillis(int hour, int minute) {
        return createTimeInMillis(0 /* second */, minute, hour, 1 /* day */, 1 /* month */,
                2012 /* year */, Time.getCurrentTimezone());
    }

    private static long createTimeInMillis(int second, int minute, int hour, int monthDay,
            int month, int year, String timezone) {
        Time t = new Time(timezone);
        t.set(second, minute, hour, monthDay, month, year);
        t.normalize(false);
        return t.toMillis(false);
    }

    @SmallTest
    public void testProcessQuery_skipDeclinedDismissed() {
        int declinedEventId = 1;
        int dismissedEventId = 2;
        int acceptedEventId = 3;
        long acceptedStartTime = createTimeInMillis(10, 0);
        long acceptedEndTime = createTimeInMillis(10, 30);

        AlertsTable at = new AlertsTable();
        at.addAlertRow(declinedEventId, SCHEDULED, DECLINED, 0, createTimeInMillis(9, 0),
                createTimeInMillis(10, 0), 0);
        at.addAlertRow(dismissedEventId, SCHEDULED, DISMISSED, 0, createTimeInMillis(9, 30),
                createTimeInMillis(11, 0), 0);
        at.addAlertRow(acceptedEventId, SCHEDULED, ACCEPTED, 1, acceptedStartTime, acceptedEndTime,
                0);

        ArrayList<NotificationInfo> highPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> mediumPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> lowPriority = new ArrayList<NotificationInfo>();
        long currentTime = createTimeInMillis(5, 0);
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);

        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, highPriority.size());
        assertEquals(acceptedEventId, highPriority.get(0).eventId);
        assertEquals(acceptedStartTime, highPriority.get(0).startMillis);
        assertEquals(acceptedEndTime, highPriority.get(0).endMillis);
        assertTrue(highPriority.get(0).allDay);
    }

    @SmallTest
    public void testProcessQuery_newAlert() {
        int scheduledAlertEventId = 1;
        int firedAlertEventId = 2;

        AlertsTable at = new AlertsTable();
        at.addAlertRow(scheduledAlertEventId, SCHEDULED, ACCEPTED, 0, createTimeInMillis(9, 0),
                createTimeInMillis(10, 0), 0);
        at.addAlertRow(firedAlertEventId, FIRED, ACCEPTED, 0, createTimeInMillis(10, 0),
                createTimeInMillis(10, 30), 0);

        ArrayList<NotificationInfo> highPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> mediumPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> lowPriority = new ArrayList<NotificationInfo>();
        long currentTime = createTimeInMillis(5, 0);
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);

        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(2, highPriority.size());
        assertEquals(scheduledAlertEventId, highPriority.get(0).eventId);
        assertTrue("newAlert should be ON for scheduled alerts", highPriority.get(0).newAlert);
        assertEquals(firedAlertEventId, highPriority.get(1).eventId);
        assertFalse("newAlert should be OFF for fired alerts", highPriority.get(1).newAlert);
    }

    @SmallTest
    public void testProcessQuery_recurringEvent() {
        int eventId = 1;
        long earlierStartTime = createTimeInMillis(10, 0);
        long laterStartTime = createTimeInMillis(11, 0);

        ArrayList<NotificationInfo> highPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> mediumPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> lowPriority = new ArrayList<NotificationInfo>();

        AlertsTable at = new AlertsTable();
        at.addAlertRow(eventId, SCHEDULED, ACCEPTED, 0, laterStartTime,
                laterStartTime + DateUtils.HOUR_IN_MILLIS, 0);
        at.addAlertRow(eventId, FIRED, ACCEPTED, 0, earlierStartTime,
                earlierStartTime + DateUtils.HOUR_IN_MILLIS, 0);

        // Both events in the future: the earliest one should be chosen.
        long currentTime = earlierStartTime - DateUtils.DAY_IN_MILLIS * 5;
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, highPriority.size());
        assertEquals("Recurring event with earlier start time expected", earlierStartTime,
                highPriority.get(0).startMillis);

        // Increment time just past the earlier event: the earlier one should be chosen.
        highPriority.clear();
        currentTime = earlierStartTime + DateUtils.MINUTE_IN_MILLIS * 10;
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, highPriority.size());
        assertEquals("Recurring event with earlier start time expected", earlierStartTime,
                highPriority.get(0).startMillis);

        // Increment time to 15 min past the earlier event: the later one should be chosen.
        highPriority.clear();
        currentTime = earlierStartTime + DateUtils.MINUTE_IN_MILLIS * 15;
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, highPriority.size());
        assertEquals("Recurring event with later start time expected", laterStartTime,
                highPriority.get(0).startMillis);

        // Both events in the past: the later one should be chosen (in the low priority bucket).
        highPriority.clear();
        currentTime = laterStartTime + DateUtils.DAY_IN_MILLIS * 5;
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, highPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, lowPriority.size());
        assertEquals("Recurring event with later start time expected", laterStartTime,
                lowPriority.get(0).startMillis);
    }

    @SmallTest
    public void testProcessQuery_recurringAllDayEvent() {
        int eventId = 1;
        long day1 = createTimeInMillis(0, 0, 0, 1, 5, 2012, Time.TIMEZONE_UTC);
        long day2 = createTimeInMillis(0, 0, 0, 2, 5, 2012, Time.TIMEZONE_UTC);

        ArrayList<NotificationInfo> highPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> mediumPriority = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> lowPriority = new ArrayList<NotificationInfo>();

        AlertsTable at = new AlertsTable();
        at.addAlertRow(eventId, SCHEDULED, ACCEPTED, 1, day2, day2 + DateUtils.HOUR_IN_MILLIS * 24,
                0);
        at.addAlertRow(eventId, SCHEDULED, ACCEPTED, 1, day1, day1 + DateUtils.HOUR_IN_MILLIS * 24,
                0);

        // Both events in the future: the earliest one should be chosen.
        long currentTime = day1 - DateUtils.DAY_IN_MILLIS * 3;
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, highPriority.size());
        assertEquals("Recurring event with earlier start time expected", day1,
                highPriority.get(0).startMillis);

        // Increment time just past the earlier event (to 12:10am).  The earlier one should
        // be chosen.
        highPriority.clear();
        currentTime = createTimeInMillis(0, 10, 0, 1, 5, 2012, Time.getCurrentTimezone());
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, highPriority.size());
        assertEquals("Recurring event with earlier start time expected", day1,
                highPriority.get(0).startMillis);

        // Increment time to 15 min past the earlier event: the later one should be chosen.
        highPriority.clear();
        currentTime = createTimeInMillis(0, 15, 0, 1, 5, 2012, Time.getCurrentTimezone());
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, lowPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, highPriority.size());
        assertEquals("Recurring event with earlier start time expected", day2,
                highPriority.get(0).startMillis);

        // Both events in the past: the later one should be chosen (in the low priority bucket).
        highPriority.clear();
        currentTime = day2 + DateUtils.DAY_IN_MILLIS * 1;
        AlertService.processQuery(at.getAlertCursor(), mContext, currentTime, highPriority,
                mediumPriority, lowPriority);
        assertEquals(0, highPriority.size());
        assertEquals(0, mediumPriority.size());
        assertEquals(1, lowPriority.size());
        assertEquals("Recurring event with later start time expected", day2,
                lowPriority.get(0).startMillis);
    }

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    @SmallTest
    public void testRedistributeBuckets_withinLimits() throws Exception {
        int maxNotifications = 3;
        ArrayList<NotificationInfo> threeItemList = new ArrayList<NotificationInfo>();
        threeItemList.add(createNotificationInfo(5));
        threeItemList.add(createNotificationInfo(4));
        threeItemList.add(createNotificationInfo(3));

        // Test when max notifications at high priority.
        ArrayList<NotificationInfo> high = threeItemList;
        ArrayList<NotificationInfo> medium = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> low = new ArrayList<NotificationInfo>();
        AlertService.redistributeBuckets(high, medium, low, maxNotifications);
        assertEquals(3, high.size());
        assertEquals(0, medium.size());
        assertEquals(0, low.size());

        // Test when max notifications at medium priority.
        high = new ArrayList<NotificationInfo>();
        medium = threeItemList;
        low = new ArrayList<NotificationInfo>();
        AlertService.redistributeBuckets(high, medium, low, maxNotifications);
        assertEquals(0, high.size());
        assertEquals(3, medium.size());
        assertEquals(0, low.size());

        // Test when max notifications at high and medium priority
        high = new ArrayList<NotificationInfo>(threeItemList);
        medium = new ArrayList<NotificationInfo>();
        medium.add(high.remove(1));
        low = new ArrayList<NotificationInfo>();
        AlertService.redistributeBuckets(high, medium, low, maxNotifications);
        assertEquals(2, high.size());
        assertEquals(1, medium.size());
        assertEquals(0, low.size());
    }

    @SmallTest
    public void testRedistributeBuckets_tooManyHighPriority() throws Exception {
        ArrayList<NotificationInfo> high = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> medium = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> low = new ArrayList<NotificationInfo>();
        high.add(createNotificationInfo(5));
        high.add(createNotificationInfo(4));
        high.add(createNotificationInfo(3));
        high.add(createNotificationInfo(2));
        high.add(createNotificationInfo(1));

        // Invoke the method under test.
        int maxNotifications = 3;
        AlertService.redistributeBuckets(high, medium, low, maxNotifications);

        // Verify some high priority were kicked out.
        assertEquals(3, high.size());
        assertEquals(3, high.get(0).eventId);
        assertEquals(2, high.get(1).eventId);
        assertEquals(1, high.get(2).eventId);

        // Verify medium priority untouched.
        assertEquals(0, medium.size());

        // Verify the extras went to low priority.
        assertEquals(2, low.size());
        assertEquals(5, low.get(0).eventId);
        assertEquals(4, low.get(1).eventId);
    }

    @SmallTest
    public void testRedistributeBuckets_tooManyMediumPriority() throws Exception {
        ArrayList<NotificationInfo> high = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> medium = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> low = new ArrayList<NotificationInfo>();
        high.add(createNotificationInfo(5));
        high.add(createNotificationInfo(4));
        medium.add(createNotificationInfo(3));
        medium.add(createNotificationInfo(2));
        medium.add(createNotificationInfo(1));

        // Invoke the method under test.
        int maxNotifications = 3;
        AlertService.redistributeBuckets(high, medium, low, maxNotifications);

        // Verify high priority untouched.
        assertEquals(2, high.size());
        assertEquals(5, high.get(0).eventId);
        assertEquals(4, high.get(1).eventId);

        // Verify some medium priority were kicked out (the ones near the end of the
        // list).
        assertEquals(1, medium.size());
        assertEquals(3, medium.get(0).eventId);

        // Verify the extras went to low priority.
        assertEquals(2, low.size());
        assertEquals(2, low.get(0).eventId);
        assertEquals(1, low.get(1).eventId);
    }

    @SmallTest
    public void testRedistributeBuckets_tooManyHighMediumPriority() throws Exception {
        ArrayList<NotificationInfo> high = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> medium = new ArrayList<NotificationInfo>();
        ArrayList<NotificationInfo> low = new ArrayList<NotificationInfo>();
        high.add(createNotificationInfo(8));
        high.add(createNotificationInfo(7));
        high.add(createNotificationInfo(6));
        high.add(createNotificationInfo(5));
        high.add(createNotificationInfo(4));
        medium.add(createNotificationInfo(3));
        medium.add(createNotificationInfo(2));
        medium.add(createNotificationInfo(1));

        // Invoke the method under test.
        int maxNotifications = 3;
        AlertService.redistributeBuckets(high, medium, low, maxNotifications);

        // Verify high priority.
        assertEquals(3, high.size());
        assertEquals(6, high.get(0).eventId);
        assertEquals(5, high.get(1).eventId);
        assertEquals(4, high.get(2).eventId);

        // Verify some medium priority.
        assertEquals(0, medium.size());

        // Verify low priority.
        assertEquals(5, low.size());
        assertEquals(8, low.get(0).eventId);
        assertEquals(7, low.get(1).eventId);
        assertEquals(3, low.get(2).eventId);
        assertEquals(2, low.get(3).eventId);
        assertEquals(1, low.get(4).eventId);
    }
Michael Chan's avatar
Michael Chan committed
1058
}