summaryrefslogtreecommitdiff
path: root/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ongoingcall/OngoingCallControllerTest.kt
blob: d26db4c69ecefb8c7b9110ac4bb7b4ed950a3237 (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
/*
 * Copyright (C) 2021 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.systemui.statusbar.phone.ongoingcall

import android.app.ActivityManager
import android.app.IActivityManager
import android.app.IUidObserver
import android.app.Notification
import android.app.PendingIntent
import android.app.Person
import android.content.Intent
import android.service.notification.NotificationListenerService.REASON_USER_STOPPED
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.test.filters.SmallTest
import com.android.internal.logging.testing.UiEventLoggerFake
import com.android.systemui.R
import com.android.systemui.SysuiTestCase
import com.android.systemui.plugins.ActivityStarter
import com.android.systemui.statusbar.FeatureFlags
import com.android.systemui.statusbar.notification.collection.NotificationEntry
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder
import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection
import com.android.systemui.statusbar.notification.collection.notifcollection.NotifCollectionListener
import com.android.systemui.util.concurrency.FakeExecutor
import com.android.systemui.util.mockito.any
import com.android.systemui.util.time.FakeSystemClock
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.anyBoolean
import org.mockito.ArgumentMatchers.nullable
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.reset
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations

private const val CALL_UID = 900

// A process state that represents the process being visible to the user.
private const val PROC_STATE_VISIBLE = ActivityManager.PROCESS_STATE_TOP

// A process state that represents the process being invisible to the user.
private const val PROC_STATE_INVISIBLE = ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE

@SmallTest
@RunWith(AndroidTestingRunner::class)
@TestableLooper.RunWithLooper
class OngoingCallControllerTest : SysuiTestCase() {

    private val clock = FakeSystemClock()
    private val mainExecutor = FakeExecutor(clock)
    private val uiEventLoggerFake = UiEventLoggerFake()

    private lateinit var controller: OngoingCallController
    private lateinit var notifCollectionListener: NotifCollectionListener

    @Mock private lateinit var mockOngoingCallListener: OngoingCallListener
    @Mock private lateinit var mockActivityStarter: ActivityStarter
    @Mock private lateinit var mockIActivityManager: IActivityManager

    private lateinit var chipView: View

    @Before
    fun setUp() {
        allowTestableLooperAsMainThread()
        TestableLooper.get(this).runWithLooper {
            chipView = LayoutInflater.from(mContext).inflate(R.layout.ongoing_call_chip, null)
        }

        MockitoAnnotations.initMocks(this)
        val featureFlags = mock(FeatureFlags::class.java)
        `when`(featureFlags.isOngoingCallStatusBarChipEnabled).thenReturn(true)
        val notificationCollection = mock(CommonNotifCollection::class.java)

        controller = OngoingCallController(
                notificationCollection,
                featureFlags,
                clock,
                mockActivityStarter,
                mainExecutor,
                mockIActivityManager,
                OngoingCallLogger(uiEventLoggerFake))
        controller.init()
        controller.addCallback(mockOngoingCallListener)
        controller.setChipView(chipView)

        val collectionListenerCaptor = ArgumentCaptor.forClass(NotifCollectionListener::class.java)
        verify(notificationCollection).addCollectionListener(collectionListenerCaptor.capture())
        notifCollectionListener = collectionListenerCaptor.value!!

        `when`(mockIActivityManager.getUidProcessState(eq(CALL_UID), nullable(String::class.java)))
                .thenReturn(PROC_STATE_INVISIBLE)
    }

    @After
    fun tearDown() {
        controller.tearDownChipView()
    }

    @Test
    fun onEntryUpdated_isOngoingCallNotif_listenerNotified() {
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())

        verify(mockOngoingCallListener).onOngoingCallStateChanged(anyBoolean())
    }

    @Test
    fun onEntryUpdated_notOngoingCallNotif_listenerNotNotified() {
        notifCollectionListener.onEntryUpdated(createNotCallNotifEntry())

        verify(mockOngoingCallListener, never()).onOngoingCallStateChanged(anyBoolean())
    }

    @Test
    fun onEntryUpdated_ongoingCallNotifThenScreeningCallNotif_listenerNotifiedTwice() {
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())
        notifCollectionListener.onEntryUpdated(createScreeningCallNotifEntry())

        verify(mockOngoingCallListener, times(2))
                .onOngoingCallStateChanged(anyBoolean())
    }

    /** Regression test for b/191472854. */
    @Test
    fun onEntryUpdated_notifHasNullContentIntent_noCrash() {
        notifCollectionListener.onEntryUpdated(
                createCallNotifEntry(ongoingCallStyle, nullContentIntent = true))
    }

    /** Regression test for b/192379214. */
    @Test
    fun onEntryUpdated_notificationWhenIsZero_timeHidden() {
        val notification = NotificationEntryBuilder(createOngoingCallNotifEntry())
        notification.modifyNotification(context).setWhen(0)

        notifCollectionListener.onEntryUpdated(notification.build())
        chipView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )

        assertThat(chipView.findViewById<View>(R.id.ongoing_call_chip_time)?.measuredWidth)
                .isEqualTo(0)
    }

    @Test
    fun onEntryUpdated_notificationWhenIsValid_timeShown() {
        val notification = NotificationEntryBuilder(createOngoingCallNotifEntry())
        notification.modifyNotification(context).setWhen(clock.currentTimeMillis())

        notifCollectionListener.onEntryUpdated(notification.build())
        chipView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )

        assertThat(chipView.findViewById<View>(R.id.ongoing_call_chip_time)?.measuredWidth)
                .isGreaterThan(0)
    }

    /** Regression test for b/194731244. */
    @Test
    fun onEntryUpdated_calledManyTimes_uidObserverUnregisteredManyTimes() {
        val numCalls = 4

        for (i in 0 until numCalls) {
            // Re-create the notification each time so that it's considered a different object and
            // observers will get re-registered (and hopefully unregistered).
            notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())
        }

        // There should be 1 observer still registered, so we should unregister n-1 times.
        verify(mockIActivityManager, times(numCalls - 1)).unregisterUidObserver(any())
    }

    /**
     * If a call notification is never added before #onEntryRemoved is called, then the listener
     * should never be notified.
     */
    @Test
    fun onEntryRemoved_callNotifNeverAddedBeforehand_listenerNotNotified() {
        notifCollectionListener.onEntryRemoved(createOngoingCallNotifEntry(), REASON_USER_STOPPED)

        verify(mockOngoingCallListener, never()).onOngoingCallStateChanged(anyBoolean())
    }

    @Test
    fun onEntryRemoved_callNotifAddedThenRemoved_listenerNotified() {
        val ongoingCallNotifEntry = createOngoingCallNotifEntry()
        notifCollectionListener.onEntryAdded(ongoingCallNotifEntry)
        reset(mockOngoingCallListener)

        notifCollectionListener.onEntryRemoved(ongoingCallNotifEntry, REASON_USER_STOPPED)

        verify(mockOngoingCallListener).onOngoingCallStateChanged(anyBoolean())
    }

    /** Regression test for b/188491504. */
    @Test
    fun onEntryRemoved_removedNotifHasSameKeyAsAddedNotif_listenerNotified() {
        val ongoingCallNotifEntry = createOngoingCallNotifEntry()
        notifCollectionListener.onEntryAdded(ongoingCallNotifEntry)
        reset(mockOngoingCallListener)

        // Create another notification based on the ongoing call one, but remove the features that
        // made it a call notification.
        val removedEntryBuilder = NotificationEntryBuilder(ongoingCallNotifEntry)
        removedEntryBuilder.modifyNotification(context).style = null

        notifCollectionListener.onEntryRemoved(removedEntryBuilder.build(), REASON_USER_STOPPED)

        verify(mockOngoingCallListener).onOngoingCallStateChanged(anyBoolean())
    }


    @Test
    fun onEntryRemoved_notifKeyDoesNotMatchOngoingCallNotif_listenerNotNotified() {
        notifCollectionListener.onEntryAdded(createOngoingCallNotifEntry())
        reset(mockOngoingCallListener)

        notifCollectionListener.onEntryRemoved(createNotCallNotifEntry(), REASON_USER_STOPPED)

        verify(mockOngoingCallListener, never()).onOngoingCallStateChanged(anyBoolean())
    }

    @Test
    fun hasOngoingCall_noOngoingCallNotifSent_returnsFalse() {
        assertThat(controller.hasOngoingCall()).isFalse()
    }

    @Test
    fun hasOngoingCall_unrelatedNotifSent_returnsFalse() {
        notifCollectionListener.onEntryUpdated(createNotCallNotifEntry())

        assertThat(controller.hasOngoingCall()).isFalse()
    }

    @Test
    fun hasOngoingCall_screeningCallNotifSent_returnsFalse() {
        notifCollectionListener.onEntryUpdated(createScreeningCallNotifEntry())

        assertThat(controller.hasOngoingCall()).isFalse()
    }

    @Test
    fun hasOngoingCall_ongoingCallNotifSentAndCallAppNotVisible_returnsTrue() {
        `when`(mockIActivityManager.getUidProcessState(eq(CALL_UID), nullable(String::class.java)))
                .thenReturn(PROC_STATE_INVISIBLE)

        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())

        assertThat(controller.hasOngoingCall()).isTrue()
    }

    @Test
    fun hasOngoingCall_ongoingCallNotifSentButCallAppVisible_returnsFalse() {
        `when`(mockIActivityManager.getUidProcessState(eq(CALL_UID), nullable(String::class.java)))
                .thenReturn(PROC_STATE_VISIBLE)

        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())

        assertThat(controller.hasOngoingCall()).isFalse()
    }

    @Test
    fun hasOngoingCall_ongoingCallNotifSentButInvalidChipView_returnsFalse() {
        val invalidChipView = LinearLayout(context)
        controller.setChipView(invalidChipView)

        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())

        assertThat(controller.hasOngoingCall()).isFalse()
    }

    @Test
    fun hasOngoingCall_ongoingCallNotifSentThenRemoved_returnsFalse() {
        val ongoingCallNotifEntry = createOngoingCallNotifEntry()

        notifCollectionListener.onEntryUpdated(ongoingCallNotifEntry)
        notifCollectionListener.onEntryRemoved(ongoingCallNotifEntry, REASON_USER_STOPPED)

        assertThat(controller.hasOngoingCall()).isFalse()
    }

    @Test
    fun hasOngoingCall_ongoingCallNotifSentThenScreeningCallNotifSent_returnsFalse() {
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())
        notifCollectionListener.onEntryUpdated(createScreeningCallNotifEntry())

        assertThat(controller.hasOngoingCall()).isFalse()
    }

    @Test
    fun hasOngoingCall_ongoingCallNotifSentThenUnrelatedNotifSent_returnsTrue() {
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())
        notifCollectionListener.onEntryUpdated(createNotCallNotifEntry())

        assertThat(controller.hasOngoingCall()).isTrue()
    }

    /**
     * This test fakes a theme change during an ongoing call.
     *
     * When a theme change happens, [CollapsedStatusBarFragment] and its views get re-created, so
     * [OngoingCallController.setChipView] gets called with a new view. If there's an active ongoing
     * call when the theme changes, the new view needs to be updated with the call information.
     */
    @Test
    fun setChipView_whenHasOngoingCallIsTrue_listenerNotifiedWithNewView() {
        // Start an ongoing call.
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())
        reset(mockOngoingCallListener)

        lateinit var newChipView: View
        TestableLooper.get(this).runWithLooper {
            newChipView = LayoutInflater.from(mContext).inflate(R.layout.ongoing_call_chip, null)
        }

        // Change the chip view associated with the controller.
        controller.setChipView(newChipView)

        verify(mockOngoingCallListener).onOngoingCallStateChanged(anyBoolean())
    }

    @Test
    fun callProcessChangesToVisible_listenerNotified() {
        // Start the call while the process is invisible.
        `when`(mockIActivityManager.getUidProcessState(eq(CALL_UID), nullable(String::class.java)))
                .thenReturn(PROC_STATE_INVISIBLE)
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())
        reset(mockOngoingCallListener)

        val captor = ArgumentCaptor.forClass(IUidObserver.Stub::class.java)
        verify(mockIActivityManager).registerUidObserver(
                captor.capture(), any(), any(), nullable(String::class.java))
        val uidObserver = captor.value

        // Update the process to visible.
        uidObserver.onUidStateChanged(CALL_UID, PROC_STATE_VISIBLE, 0, 0)
        mainExecutor.advanceClockToLast()
        mainExecutor.runAllReady();

        verify(mockOngoingCallListener).onOngoingCallStateChanged(anyBoolean())
    }

    @Test
    fun callProcessChangesToInvisible_listenerNotified() {
        // Start the call while the process is visible.
        `when`(mockIActivityManager.getUidProcessState(eq(CALL_UID), nullable(String::class.java)))
                .thenReturn(PROC_STATE_VISIBLE)
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())
        reset(mockOngoingCallListener)

        val captor = ArgumentCaptor.forClass(IUidObserver.Stub::class.java)
        verify(mockIActivityManager).registerUidObserver(
                captor.capture(), any(), any(), nullable(String::class.java))
        val uidObserver = captor.value

        // Update the process to invisible.
        uidObserver.onUidStateChanged(CALL_UID, PROC_STATE_INVISIBLE, 0, 0)
        mainExecutor.advanceClockToLast()
        mainExecutor.runAllReady();

        verify(mockOngoingCallListener).onOngoingCallStateChanged(anyBoolean())
    }

    @Test
    fun chipClicked_clickEventLogged() {
        notifCollectionListener.onEntryUpdated(createOngoingCallNotifEntry())

        chipView.performClick()

        assertThat(uiEventLoggerFake.numLogs()).isEqualTo(1)
        assertThat(uiEventLoggerFake.eventId(0))
                .isEqualTo(OngoingCallLogger.OngoingCallEvents.ONGOING_CALL_CLICKED.id)
    }

    @Test
    fun notifyChipVisibilityChanged_visibleEventLogged() {
        controller.notifyChipVisibilityChanged(true)

        assertThat(uiEventLoggerFake.numLogs()).isEqualTo(1)
        assertThat(uiEventLoggerFake.eventId(0))
                .isEqualTo(OngoingCallLogger.OngoingCallEvents.ONGOING_CALL_VISIBLE.id)
    }
    // Other tests for notifyChipVisibilityChanged are in [OngoingCallLogger], since
    // [OngoingCallController.notifyChipVisibilityChanged] just delegates to that class.

    private fun createOngoingCallNotifEntry() = createCallNotifEntry(ongoingCallStyle)

    private fun createScreeningCallNotifEntry() = createCallNotifEntry(screeningCallStyle)

    private fun createCallNotifEntry(
        callStyle: Notification.CallStyle,
        nullContentIntent: Boolean = false
    ): NotificationEntry {
        val notificationEntryBuilder = NotificationEntryBuilder()
        notificationEntryBuilder.modifyNotification(context).style = callStyle
        notificationEntryBuilder.setUid(CALL_UID)

        if (nullContentIntent) {
            notificationEntryBuilder.modifyNotification(context).setContentIntent(null)
        } else {
            val contentIntent = mock(PendingIntent::class.java)
            `when`(contentIntent.intent).thenReturn(mock(Intent::class.java))
            notificationEntryBuilder.modifyNotification(context).setContentIntent(contentIntent)
        }

        return notificationEntryBuilder.build()
    }

    private fun createNotCallNotifEntry() = NotificationEntryBuilder().build()
}

private val person = Person.Builder().setName("name").build()
private val hangUpIntent = mock(PendingIntent::class.java)

private val ongoingCallStyle = Notification.CallStyle.forOngoingCall(person, hangUpIntent)
private val screeningCallStyle = Notification.CallStyle.forScreeningCall(
        person, hangUpIntent, /* answerIntent= */ mock(PendingIntent::class.java))