aboutsummaryrefslogtreecommitdiff
path: root/tests/unit/src/com/android/car/calendar/common/EventsLiveDataTest.java
blob: 81b881d21df7ed14d9f371674a5528b612a6bd6c (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
/*
 * Copyright 2020 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.car.calendar.common;

import static com.google.common.truth.Truth.assertThat;

import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import static java.time.temporal.ChronoUnit.HOURS;

import android.Manifest;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.os.SystemClock;
import android.provider.CalendarContract;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;

import androidx.lifecycle.Observer;
import androidx.test.annotation.UiThreadTest;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.GrantPermissionRule;

import com.google.common.collect.ImmutableList;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RunWith(AndroidJUnit4.class)
public class EventsLiveDataTest {
    private static final ZoneId BERLIN_ZONE_ID = ZoneId.of("Europe/Berlin");
    private static final ZonedDateTime CURRENT_DATE_TIME =
            LocalDateTime.of(2019, 12, 10, 10, 10, 10, 500500).atZone(BERLIN_ZONE_ID);
    private static final Dialer.NumberAndAccess EVENT_NUMBER_PIN =
            new Dialer.NumberAndAccess("the number", "the pin");
    private static final String EVENT_TITLE = "the title";
    private static final boolean EVENT_ALL_DAY = false;
    private static final String EVENT_LOCATION = "the location";
    private static final String EVENT_DESCRIPTION = "the description";
    private static final String CALENDAR_NAME = "the calendar name";
    private static final int CALENDAR_COLOR = 0xCAFEBABE;
    private static final int EVENT_ATTENDEE_STATUS =
            CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED;

    @Rule
    public final GrantPermissionRule permissionRule =
            GrantPermissionRule.grant(Manifest.permission.READ_CALENDAR);

    private EventsLiveData mEventsLiveData;
    private TestContentProvider mTestContentProvider;
    private TestHandler mTestHandler;
    private TestClock mTestClock;

    @Before
    public void setUp() {
        mTestClock = new TestClock(BERLIN_ZONE_ID);
        mTestClock.setTime(CURRENT_DATE_TIME);
        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

        // Create a fake result for the calendar content provider.
        MockContentResolver mockContentResolver = new MockContentResolver(context);

        mTestContentProvider = new TestContentProvider(context);
        mockContentResolver.addProvider(CalendarContract.AUTHORITY, mTestContentProvider);

        EventDescriptions mockEventDescriptions = mock(EventDescriptions.class);
        when(mockEventDescriptions.extractNumberAndPins(any()))
                .thenReturn(ImmutableList.of(EVENT_NUMBER_PIN));

        EventLocations mockEventLocations = mock(EventLocations.class);
        when(mockEventLocations.isValidLocation(anyString())).thenReturn(true);
        mTestHandler = TestHandler.create();
        mEventsLiveData =
                new EventsLiveData(
                        mTestClock,
                        mTestHandler,
                        mockContentResolver,
                        mockEventDescriptions,
                        mockEventLocations);
    }

    @After
    public void tearDown() {
        if (mTestHandler != null) {
            mTestHandler.stop();
        }
    }

    @Test
    public void noObserver_noQueryMade() {
        // No query should be made because there are no observers.
        assertThat(mTestContentProvider.mTestEventCursor).isNull();
    }

    @Test
    @UiThreadTest
    public void addObserver_queryMade() throws InterruptedException {
        // Observing triggers content to be read.
        mEventsLiveData.observeForever((unused) -> { /* Do nothing */ });

        // Wait for the data to be read on the background thread.
        mTestContentProvider.awaitCalendarQuery();

        assertThat(mTestContentProvider.mTestEventCursor).isNotNull();
    }

    @Test
    @UiThreadTest
    public void addObserver_contentObserved() throws InterruptedException {
        // Observing triggers content to be read.
        mEventsLiveData.observeForever((unused) -> { /* Do nothing */ });

        // Wait for the data to be read on the background thread.
        mTestContentProvider.awaitCalendarQuery();

        awaitAndAssertDone(mTestContentProvider.mTestEventCursor.mRegisterContentObserverLatch);
    }

    @Test
    public void removeObserver_contentNotObserved() throws InterruptedException {
        // Observing triggers content to be read.
        Observer<ImmutableList<Event>> observer = (unused) -> { /* Do nothing */ };
        runOnMain(() -> mEventsLiveData.observeForever(observer));

        // Wait for the data to be read on the background thread.
        mTestContentProvider.awaitCalendarQuery();

        awaitAndAssertDone(mTestContentProvider.mTestEventCursor.mRegisterContentObserverLatch);
        runOnMain(() -> mEventsLiveData.removeObserver(observer));
        awaitAndAssertDone(mTestContentProvider.mTestEventCursor.mUnregisterContentObserverLatch);
    }

    @Test
    public void addObserver_oneEventResult() throws InterruptedException {
        mTestContentProvider.addRow(buildTestRowWithDuration(CURRENT_DATE_TIME, 1));

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);

        // Must add observer on main thread.
        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        ImmutableList<Event> events = mEventsLiveData.getValue();
        assertThat(events).isNotNull();
        assertThat(events).hasSize(1);
        Event event = events.get(0);

        long eventStartMillis = addHoursAndTruncate(CURRENT_DATE_TIME, 0);
        long eventEndMillis = addHoursAndTruncate(CURRENT_DATE_TIME, 1);

        assertThat(event.getTitle()).isEqualTo(EVENT_TITLE);
        assertThat(event.getCalendarDetails().getColor()).isEqualTo(CALENDAR_COLOR);
        assertThat(event.getLocation()).isEqualTo(EVENT_LOCATION);
        assertThat(event.getStartInstant().toEpochMilli()).isEqualTo(eventStartMillis);
        assertThat(event.getEndInstant().toEpochMilli()).isEqualTo(eventEndMillis);
        assertThat(event.getStatus()).isEqualTo(Event.Status.ACCEPTED);
        assertThat(event.getNumberAndAccess()).isEqualTo(EVENT_NUMBER_PIN);
    }

    @Test
    public void notifyDataChange_dataNotChanged_onChangedNotCalled() throws InterruptedException {
        mTestContentProvider.addRow(buildTestRow());

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch initializeCountdownLatch = new CountDownLatch(2);

        // Expect the same init callbacks as above but with an extra when the data is updated.
        CountDownLatch changeCountdownLatch = new CountDownLatch(3);

        // Must add observer on main thread.
        runOnMain(
                () ->
                        mEventsLiveData.observeForever(
                                // Count down both latches when data is changed.
                                (value) -> {
                                    initializeCountdownLatch.countDown();
                                    changeCountdownLatch.countDown();
                                }));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(initializeCountdownLatch);

        // Signal that the content has changed but do not update the data.
        mTestContentProvider.mTestEventCursor.signalDataChanged();

        // Wait for the changed data to be read on the background thread.
        awaitAndAssertNotDone(changeCountdownLatch);
    }

    @Test
    public void notifyDataChange_dataChanged_onChangedCalled() throws InterruptedException {
        mTestContentProvider.addRow(buildTestRow());

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch initializeCountdownLatch = new CountDownLatch(2);

        // Expect the same init callbacks as above but with an extra when the data is updated.
        CountDownLatch changeCountdownLatch = new CountDownLatch(3);

        // Must add observer on main thread.
        runOnMain(
                () ->
                        mEventsLiveData.observeForever(
                                // Count down both latches when data is changed.
                                (value) -> {
                                    initializeCountdownLatch.countDown();
                                    changeCountdownLatch.countDown();
                                }));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(initializeCountdownLatch);

        // Change the data and signal that the content has changed.
        mTestContentProvider.addRow(buildTestRowWithTitle("Another event"));
        mTestContentProvider.mTestEventCursor.signalDataChanged();

        // Wait for the changed data to be read on the background thread.
        awaitAndAssertDone(changeCountdownLatch);
    }

    @Test
    public void addObserver_updateScheduled() throws InterruptedException {
        mTestHandler.setExpectedMessageCount(2);

        // Must add observer on main thread.
        runOnMain(() -> mEventsLiveData.observeForever((unused) -> {/* Do nothing */ }));

        mTestHandler.awaitExpectedMessages();

        // Show that a message was scheduled for the future.
        assertThat(mTestHandler.mLastUptimeMillis).isAtLeast(SystemClock.uptimeMillis());
    }

    @Test
    public void noCalendars_valueNull() throws InterruptedException {
        mTestContentProvider.mAddFakeCalendar = false;
        mTestContentProvider.addRow(buildTestRow());

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);
        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        assertThat(mEventsLiveData.getValue()).isNull();
    }

    @Test
    @UiThreadTest
    public void noCalendars_contentObserved() throws InterruptedException {
        mTestContentProvider.mAddFakeCalendar = false;
        mEventsLiveData.observeForever((unused) -> { /* Do nothing */ });
        mTestContentProvider.awaitCalendarQuery();
        awaitAndAssertDone(mTestContentProvider.mTestEventCursor.mRegisterContentObserverLatch);
    }

    @Test
    public void multiDayEvent_createsMultipleEvents() throws InterruptedException {
        // Replace the default event with one that lasts 24 hours.
        mTestContentProvider.addRow(buildTestRowWithDuration(CURRENT_DATE_TIME, 24));

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);

        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        // Expect an event for the 2 parts of the split event instance.
        assertThat(mEventsLiveData.getValue()).hasSize(2);
    }

    @Test
    public void multiDayEvent_keepsOriginalTimes() throws InterruptedException {
        // Replace the default event with one that lasts 24 hours.
        int hours = 48;
        mTestContentProvider.addRow(buildTestRowWithDuration(CURRENT_DATE_TIME, hours));

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);

        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        Event middlePartEvent = mEventsLiveData.getValue().get(1);

        // The start and end times should remain the original times.
        ZonedDateTime expectedStartTime = CURRENT_DATE_TIME.truncatedTo(HOURS);
        assertThat(middlePartEvent.getStartInstant()).isEqualTo(expectedStartTime.toInstant());
        ZonedDateTime expectedEndTime = expectedStartTime.plus(hours, HOURS);
        assertThat(middlePartEvent.getEndInstant()).isEqualTo(expectedEndTime.toInstant());
    }

    @Test
    public void multipleEvents_resultsSortedStart() throws InterruptedException {
        // Replace the default event with two that are out of time order.
        ZonedDateTime twoHoursAfterCurrentTime = CURRENT_DATE_TIME.plus(Duration.ofHours(2));
        mTestContentProvider.addRow(buildTestRowWithDuration(twoHoursAfterCurrentTime, 1));
        mTestContentProvider.addRow(buildTestRowWithDuration(CURRENT_DATE_TIME, 1));

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);

        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        ImmutableList<Event> events = mEventsLiveData.getValue();

        assertThat(events.get(0).getStartInstant().toEpochMilli())
                .isEqualTo(addHoursAndTruncate(CURRENT_DATE_TIME, 0));
        assertThat(events.get(1).getStartInstant().toEpochMilli())
                .isEqualTo(addHoursAndTruncate(CURRENT_DATE_TIME, 2));
    }

    @Test
    public void multipleEvents_resultsSortedTitle() throws InterruptedException {
        // Replace the default event with two that are out of time order.
        mTestContentProvider.addRow(buildTestRowWithTitle("Title B"));
        mTestContentProvider.addRow(buildTestRowWithTitle("Title A"));
        mTestContentProvider.addRow(buildTestRowWithTitle("Title C"));

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);

        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        ImmutableList<Event> events = mEventsLiveData.getValue();

        assertThat(events.get(0).getTitle()).isEqualTo("Title A");
        assertThat(events.get(1).getTitle()).isEqualTo("Title B");
        assertThat(events.get(2).getTitle()).isEqualTo("Title C");
    }

    @Test
    public void allDayEvent_timesSetToLocal() throws InterruptedException {
        // All-day events always start at UTC midnight.
        ZonedDateTime utcMidnightStart =
                CURRENT_DATE_TIME.withZoneSameLocal(ZoneId.of("UTC")).truncatedTo(ChronoUnit.DAYS);
        mTestContentProvider.addRow(buildTestRowAllDay(utcMidnightStart));

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);

        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        ImmutableList<Event> events = mEventsLiveData.getValue();

        Instant localMidnightStart = CURRENT_DATE_TIME.truncatedTo(ChronoUnit.DAYS).toInstant();
        assertThat(events.get(0).getStartInstant()).isEqualTo(localMidnightStart);
    }

    @Test
    public void allDayEvent_queryCoversLocalDayStart() throws InterruptedException {
        // All-day events always start at UTC midnight.
        ZonedDateTime utcMidnightStart =
                CURRENT_DATE_TIME.withZoneSameLocal(ZoneId.of("UTC")).truncatedTo(ChronoUnit.DAYS);
        mTestContentProvider.addRow(buildTestRowAllDay(utcMidnightStart));

        // Set the time to 23:XX in the BERLIN_ZONE_ID which will be after the event end time.
        mTestClock.setTime(CURRENT_DATE_TIME.with(ChronoField.HOUR_OF_DAY, 23));

        // Expect onChanged to be called for when we start to observe and when the data is read.
        CountDownLatch latch = new CountDownLatch(2);

        runOnMain(() -> mEventsLiveData.observeForever((value) -> latch.countDown()));

        // Wait for the data to be read on the background thread.
        awaitAndAssertDone(latch);

        // Show that the event is included even though its end time is before the current time.
        assertThat(mEventsLiveData.getValue()).isNotEmpty();
    }

    private void runOnMain(Runnable runnable) {
        InstrumentationRegistry.getInstrumentation().runOnMainSync(runnable);
    }

    private static void awaitAndAssertDone(CountDownLatch latch) throws InterruptedException {
        assertThat(latch.await(2, TimeUnit.SECONDS)).isTrue();
    }

    private static void awaitAndAssertNotDone(CountDownLatch latch) throws InterruptedException {
        assertThat(latch.await(2, TimeUnit.SECONDS)).isFalse();
    }

    private static class TestContentProvider extends MockContentProvider {
        TestEventCursor mTestEventCursor;
        boolean mAddFakeCalendar = true;
        List<Object[]> mEventRows = new ArrayList<>();
        CountDownLatch mCalendarQueryLatch = new CountDownLatch(1);

        TestContentProvider(Context context) {
            super(context);
        }

        private void addRow(Object[] row) {
            mEventRows.add(row);
        }

        @Override
        public Cursor query(
                Uri uri,
                String[] projection,
                Bundle queryArgs,
                CancellationSignal cancellationSignal) {
            if (uri.toString().startsWith(CalendarContract.Instances.CONTENT_URI.toString())) {
                mTestEventCursor = new TestEventCursor(uri);
                for (Object[] row : mEventRows) {
                    mTestEventCursor.addRow(row);
                }
                return mTestEventCursor;
            } else if (uri.equals(CalendarContract.Calendars.CONTENT_URI)) {
                MatrixCursor calendarsCursor = new MatrixCursor(new String[] {" Test name"});
                if (mAddFakeCalendar) {
                    calendarsCursor.addRow(new String[] {"Test value"});
                }
                mCalendarQueryLatch.countDown();
                return calendarsCursor;
            }
            throw new IllegalStateException("Unexpected query uri " + uri);
        }

        void awaitCalendarQuery() throws InterruptedException {
            awaitAndAssertDone(mCalendarQueryLatch);
        }

        static class TestEventCursor extends MatrixCursor {
            final Uri mUri;
            CountDownLatch mRegisterContentObserverLatch = new CountDownLatch(1);
            CountDownLatch mUnregisterContentObserverLatch = new CountDownLatch(1);

            TestEventCursor(Uri uri) {
                super(
                        new String[] {
                            CalendarContract.Instances.TITLE,
                            CalendarContract.Instances.ALL_DAY,
                            CalendarContract.Instances.BEGIN,
                            CalendarContract.Instances.END,
                            CalendarContract.Instances.DESCRIPTION,
                            CalendarContract.Instances.EVENT_LOCATION,
                            CalendarContract.Instances.SELF_ATTENDEE_STATUS,
                            CalendarContract.Instances.CALENDAR_COLOR,
                            CalendarContract.Instances.CALENDAR_DISPLAY_NAME,
                        });
                mUri = uri;
            }

            @Override
            public void registerContentObserver(ContentObserver observer) {
                super.registerContentObserver(observer);
                mRegisterContentObserverLatch.countDown();
            }

            @Override
            public void unregisterContentObserver(ContentObserver observer) {
                super.unregisterContentObserver(observer);
                mUnregisterContentObserverLatch.countDown();
            }

            void signalDataChanged() {
                super.onChange(true);
            }
        }
    }

    private static class TestHandler extends Handler {
        final HandlerThread mThread;
        long mLastUptimeMillis;
        CountDownLatch mCountDownLatch;

        static TestHandler create() {
            HandlerThread thread =
                    new HandlerThread(
                            EventsLiveDataTest.class.getSimpleName(),
                            Process.THREAD_PRIORITY_FOREGROUND);
            thread.start();
            return new TestHandler(thread);
        }

        TestHandler(HandlerThread thread) {
            super(thread.getLooper());
            mThread = thread;
        }

        void stop() {
            mThread.quit();
        }

        void setExpectedMessageCount(int expectedMessageCount) {
            mCountDownLatch = new CountDownLatch(expectedMessageCount);
        }

        void awaitExpectedMessages() throws InterruptedException {
            awaitAndAssertDone(mCountDownLatch);
        }

        @Override
        public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
            mLastUptimeMillis = uptimeMillis;
            if (mCountDownLatch != null) {
                mCountDownLatch.countDown();
            }
            return super.sendMessageAtTime(msg, uptimeMillis);
        }
    }

    // Similar to {@link android.os.SimpleClock} but without @hide and with mutable millis.
    static class TestClock extends Clock {
        private final ZoneId mZone;
        private long mTimeMs;

        TestClock(ZoneId zone) {
            mZone = zone;
        }

        void setTime(ZonedDateTime time) {
            mTimeMs = time.toInstant().toEpochMilli();
        }

        @Override
        public ZoneId getZone() {
            return mZone;
        }

        @Override
        public Clock withZone(ZoneId zone) {
            return new TestClock(zone) {
                @Override
                public long millis() {
                    return TestClock.this.millis();
                }
            };
        }

        @Override
        public long millis() {
            return mTimeMs;
        }

        @Override
        public Instant instant() {
            return Instant.ofEpochMilli(millis());
        }
    }

    static long addHoursAndTruncate(ZonedDateTime dateTime, int hours) {
        return dateTime.truncatedTo(HOURS)
                .plus(Duration.ofHours(hours))
                .toInstant()
                .toEpochMilli();
    }

    static Object[] buildTestRowWithDuration(ZonedDateTime startDateTime, int eventDurationHours) {
        return buildTestRowWithDuration(
                startDateTime, eventDurationHours, EVENT_TITLE, EVENT_ALL_DAY);
    }

    static Object[] buildTestRowAllDay(ZonedDateTime startDateTime) {
        return buildTestRowWithDuration(startDateTime, 24, EVENT_TITLE, true);
    }

    static Object[] buildTestRowWithTitle(String title) {
        return buildTestRowWithDuration(CURRENT_DATE_TIME, 1, title, EVENT_ALL_DAY);
    }

    static Object[] buildTestRow() {
        return buildTestRowWithDuration(CURRENT_DATE_TIME, 1, EVENT_TITLE, EVENT_ALL_DAY);
    }

    static Object[] buildTestRowWithDuration(
            ZonedDateTime currentDateTime, int eventDurationHours, String title, boolean allDay) {
        return new Object[] {
            title,
            allDay ? 1 : 0,
            addHoursAndTruncate(currentDateTime, 0),
            addHoursAndTruncate(currentDateTime, eventDurationHours),
            EVENT_DESCRIPTION,
            EVENT_LOCATION,
            EVENT_ATTENDEE_STATUS,
            CALENDAR_COLOR,
            CALENDAR_NAME
        };
    }
}