summaryrefslogtreecommitdiffstats
path: root/tests/src/com/android/calendar/alerts/AlertServiceTest.java
blob: ef472866e6b8d5bcd302f7d84b3fa93df441018f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
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
179
180
181
182
183
184
185
186
187
188
189
190
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
222
223
224
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
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
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
724
725
726
727
728
729
730
731
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
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
1058
/*
 * 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;

import android.app.AlarmManager;
import android.app.PendingIntent;
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;
import android.text.format.DateUtils;
import android.text.format.Time;

import com.android.calendar.GeneralPreferences;
import com.android.calendar.alerts.AlertService.NotificationInfo;
import com.android.calendar.alerts.AlertService.NotificationWrapper;

import junit.framework.Assert;

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 {

        /* "always", "silent", depends on ringer mode */
        private String mVibrateWhen;
        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() {
            mVibrateWhen = "always";
            mRingtone = "/some/cool/ringtone";
            mPopup = true;
        }

        @Override
        public boolean contains(String key) {
            if (GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN.equals(key)) {
                return true;
            }
            return false;
        }

        @Override
        public boolean getBoolean(String key, boolean defValue) {
            if (GeneralPreferences.KEY_ALERTS_POPUP.equals(key)) {
                if (mPopup == null) {
                    Assert.fail(GeneralPreferences.KEY_ALERTS_POPUP + " fetched more than once.");
                }
                boolean val = mPopup;
                if (mStrict) {
                    mPopup = null;
                }
                return val;
            }
            throw new IllegalArgumentException();
        }

        @Override
        public String getString(String key, String defValue) {
            if (GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN.equals(key)) {
                if (mVibrateWhen == null) {
                    Assert.fail(GeneralPreferences.KEY_ALERTS_VIBRATE_WHEN
                            + " fetched more than once.");
                }
                String val = mVibrateWhen;
                if (mStrict) {
                    mVibrateWhen = null;
                }
                return val;
            }
            if (GeneralPreferences.KEY_ALERTS_RINGTONE.equals(key)) {
                if (mRingtone == null) {
                    Assert.fail(GeneralPreferences.KEY_ALERTS_RINGTONE
                            + " fetched more than once.");
                }
                String val = mRingtone;
                if (mStrict) {
                    mRingtone = null;
                }
                return val;
            }
            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;
        int[] mAlertIdsInDigest;
        int mPriority;

        public NotificationInstance(int alertId, int priority) {
            mAlertId = alertId;
            mPriority = priority;
        }

        public NotificationInstance(int[] alertIdsInDigest, int priority) {
            mAlertIdsInDigest = alertIdsInDigest;
            mPriority = priority;
        }
    }

    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,
                long end, long alarmTime) {
            Alert a = new Alert(eventId, alertStatus, responseStatus, allDay, begin, end,
                    5 /* minute */, alarmTime);
            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;
        }

    }

    class NotificationTestManager extends NotificationMgr {
        // Expected notifications
        NotificationInstance[] mExpectedNotifications;
        NotificationWrapper[] mActualNotifications;
        boolean[] mCancelled;

        // CalendarAlerts table
        private ArrayList<Alert> mAlerts;

        public NotificationTestManager(ArrayList<Alert> alerts, int maxNotifications) {
            assertEquals(0, AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
            mAlerts = alerts;
            mExpectedNotifications = new NotificationInstance[maxNotifications + 1];
            mActualNotifications = new NotificationWrapper[mExpectedNotifications.length];
            mCancelled = new boolean[mExpectedNotifications.length];
        }

        public void expectTestNotification(int notificationId, int alertId, int highPriority) {
            mExpectedNotifications[notificationId] = new NotificationInstance(alertId,
                    highPriority);
        }

        public void expectTestNotification(int notificationId, int[] alertIds, int priority) {
            mExpectedNotifications[notificationId] = new NotificationInstance(alertIds, priority);
        }

        private <T> boolean nullContents(T[] array) {
            for (T item : array) {
                if (item != null) {
                    return false;
                }
            }
            return true;
        }

        public void validateNotificationsAndReset() {
            if (nullContents(mExpectedNotifications)) {
                return;
            }

            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]);
                } else {
                    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);
                        }
                    }
                }
            }

            Arrays.fill(mCancelled, false);
            Arrays.fill(mExpectedNotifications, null);
            Arrays.fill(mActualNotifications, null);
        }

        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");
            }
            return s.toString();
        }

        ///////////////////////////////
        // NotificationMgr methods
        @Override
        public void cancel(int id) {
            assertTrue("id out of bound: " + id, 0 <= id);
            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]);
        }

        public void notify(int id, NotificationWrapper nw) {
            assertTrue("id out of bound: " + id, 0 <= id);
            assertTrue("id out of bound: " + id, id < mExpectedNotifications.length);
            assertNull("id already used: " + id, mActualNotifications[id]);
            mActualNotifications[id] = nw;
        }
    }

    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);
            }
        }
    }

    // TODO
    // Catch updates of new state, notify time, and received time
    // Test ringer, vibrate,
    // Test intents, action email

    @Smoke
    @SmallTest
    public void testGenerateAlerts_none() {
        MockSharedPreferences prefs = new MockSharedPreferences();
        AlertsTable at = new AlertsTable();
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts,
                AlertService.MAX_NOTIFICATIONS);

        // Test no alert
        long currentTime = 1000000;
        AlertService.generateAlerts(mContext, ntm, new MockAlarmManager(), prefs,
                at.getAlertCursor(), currentTime, AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();
    }

    @Smoke
    @SmallTest
    public void testGenerateAlerts_single() {
        MockSharedPreferences prefs = new MockSharedPreferences();
        MockAlarmManager alarmMgr = new MockAlarmManager();
        AlertsTable at = new AlertsTable();
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts,
                AlertService.MAX_NOTIFICATIONS);

        int id = at.addAlertRow(100, SCHEDULED, ACCEPTED, 0 /* all day */, 1300000, 2300000, 0);

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

        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(), currentTime,
                AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset(); // This wipes out notification
                                             // tests added so far

        // Test half way into an event
        currentTime = 2300000;
        ntm.expectTestNotification(AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID, id, PRIORITY_MIN);

        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(), currentTime,
                AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();

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

        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(), currentTime,
                AlertService.MAX_NOTIFICATIONS);
        ntm.validateNotificationsAndReset();
    }

    @SmallTest
    public void testGenerateAlerts_multiple() {
        int maxNotifications = 10;
        MockSharedPreferences prefs = new MockSharedPreferences();
        MockAlarmManager alarmMgr = new MockAlarmManager();
        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);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
        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);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
        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);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
        ntm.validateNotificationsAndReset();
    }

    @SmallTest
    public void testGenerateAlerts_maxAlerts() {
        MockSharedPreferences prefs = new MockSharedPreferences();
        MockAlarmManager alarmMgr = new MockAlarmManager();
        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);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
        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);
        AlertService.generateAlerts(mContext, ntm, alarmMgr, prefs, at.getAlertCursor(),
                currentTime, maxNotifications);
        ntm.validateNotificationsAndReset();
    }

    /**
     * Test that the SharedPreferences are only fetched once for each setting.
     */
    @SmallTest
    public void testGenerateAlerts_sharedPreferences() {
        MockSharedPreferences prefs = new MockSharedPreferences(true /* strict mode */);
        AlertsTable at = new AlertsTable();
        NotificationTestManager ntm = new NotificationTestManager(at.mAlerts,
                AlertService.MAX_NOTIFICATIONS);

        // 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.
        at.addAlertRow(3, SCHEDULED, ACCEPTED, 0, createTimeInMillis(9, 0),
                createTimeInMillis(10, 0), 0);
        at.addAlertRow(2, SCHEDULED, ACCEPTED, 0, createTimeInMillis(8, 0),
                createTimeInMillis(9, 0), 0);
        at.addAlertRow(1, SCHEDULED, ACCEPTED, 0, createTimeInMillis(7, 0),
                createTimeInMillis(8, 0), 0);

        // 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);
    }

    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);

        // 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();

        // 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);
        ntm.validateNotificationsAndReset();
    }

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

    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);
    }

    @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);
    }
}