summaryrefslogtreecommitdiff
path: root/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/interruption/KeyguardNotificationVisibilityProviderTest.java
blob: 3a85972aa470a3b49bb11ba0cff2e634d59eb08d (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
/*
 * Copyright (C) 2022 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.notification.interruption;

import static android.app.Notification.VISIBILITY_PUBLIC;
import static android.app.Notification.VISIBILITY_SECRET;
import static android.app.NotificationManager.IMPORTANCE_HIGH;
import static android.app.NotificationManager.IMPORTANCE_LOW;
import static android.app.NotificationManager.IMPORTANCE_MIN;

import static com.android.systemui.statusbar.StatusBarState.KEYGUARD;
import static com.android.systemui.statusbar.StatusBarState.SHADE;
import static com.android.systemui.statusbar.notification.collection.EntryUtilKt.modifyEntry;
import static com.android.systemui.util.mockito.KotlinMockitoHelpersKt.argThat;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.UserHandle;
import android.provider.Settings;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;

import androidx.test.filters.SmallTest;

import com.android.keyguard.KeyguardUpdateMonitor;
import com.android.keyguard.KeyguardUpdateMonitorCallback;
import com.android.systemui.CoreStartable;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.broadcast.BroadcastDispatcher;
import com.android.systemui.dagger.SysUISingleton;
import com.android.systemui.dagger.qualifiers.Main;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.statusbar.NotificationLockscreenUserManager;
import com.android.systemui.statusbar.RankingBuilder;
import com.android.systemui.statusbar.SysuiStatusBarStateController;
import com.android.systemui.statusbar.notification.collection.GroupEntry;
import com.android.systemui.statusbar.notification.collection.GroupEntryBuilder;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.collection.provider.HighPriorityProvider;
import com.android.systemui.statusbar.policy.KeyguardStateController;
import com.android.systemui.util.settings.FakeSettings;
import com.android.systemui.util.settings.GlobalSettings;
import com.android.systemui.util.settings.SecureSettings;
import com.android.systemui.utils.os.FakeHandler;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Map;
import java.util.function.Consumer;

import dagger.BindsInstance;
import dagger.Component;

@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
public class KeyguardNotificationVisibilityProviderTest  extends SysuiTestCase {
    private static final int NOTIF_USER_ID = 0;
    private static final int CURR_USER_ID = 1;

    @Mock private KeyguardStateController mKeyguardStateController;
    @Mock private NotificationLockscreenUserManager mLockscreenUserManager;
    @Mock private KeyguardUpdateMonitor mKeyguardUpdateMonitor;
    @Mock private HighPriorityProvider mHighPriorityProvider;
    @Mock private SysuiStatusBarStateController mStatusBarStateController;
    @Mock private BroadcastDispatcher mBroadcastDispatcher;
    private final FakeSettings mFakeSettings = new FakeSettings();

    private KeyguardNotificationVisibilityProvider mKeyguardNotificationVisibilityProvider;
    private NotificationEntry mEntry;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        TestComponent component =
                DaggerKeyguardNotificationVisibilityProviderTest_TestComponent
                        .factory()
                        .create(
                                mContext,
                                new FakeHandler(TestableLooper.get(this).getLooper()),
                                mKeyguardStateController,
                                mLockscreenUserManager,
                                mKeyguardUpdateMonitor,
                                mHighPriorityProvider,
                                mStatusBarStateController,
                                mBroadcastDispatcher,
                                mFakeSettings,
                                mFakeSettings);
        mKeyguardNotificationVisibilityProvider = component.getProvider();
        for (CoreStartable startable : component.getCoreStartables().values()) {
            startable.start();
        }
        mEntry = new NotificationEntryBuilder()
                .setUser(new UserHandle(NOTIF_USER_ID))
                .build();
    }

    @Test
    public void notifyListeners_onUnlockedChanged() {
        ArgumentCaptor<KeyguardStateController.Callback> callbackCaptor =
                ArgumentCaptor.forClass(KeyguardStateController.Callback.class);
        verify(mKeyguardStateController).addCallback(callbackCaptor.capture());
        KeyguardStateController.Callback callback = callbackCaptor.getValue();

        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        callback.onUnlockedChanged();

        verify(listener).accept(anyString());
    }

    @Test
    public void notifyListeners_onKeyguardShowingChanged() {
        ArgumentCaptor<KeyguardStateController.Callback> callbackCaptor =
                ArgumentCaptor.forClass(KeyguardStateController.Callback.class);
        verify(mKeyguardStateController).addCallback(callbackCaptor.capture());
        KeyguardStateController.Callback callback = callbackCaptor.getValue();

        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        callback.onKeyguardShowingChanged();

        verify(listener).accept(anyString());
    }

    @Test
    public void notifyListeners_onStrongAuthStateChanged() {
        ArgumentCaptor<KeyguardUpdateMonitorCallback> callbackCaptor =
                ArgumentCaptor.forClass(KeyguardUpdateMonitorCallback.class);
        verify(mKeyguardUpdateMonitor).registerCallback(callbackCaptor.capture());
        KeyguardUpdateMonitorCallback callback = callbackCaptor.getValue();

        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        callback.onStrongAuthStateChanged(0);

        verify(listener).accept(anyString());
    }

    @Test
    public void notifyListeners_onStatusBarStateChanged() {
        ArgumentCaptor<StatusBarStateController.StateListener> callbackCaptor =
                ArgumentCaptor.forClass(StatusBarStateController.StateListener.class);
        verify(mStatusBarStateController).addCallback(callbackCaptor.capture());
        StatusBarStateController.StateListener callback = callbackCaptor.getValue();

        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        callback.onUpcomingStateChanged(0);

        verify(listener).accept(anyString());
    }

    @Test
    public void notifyListeners_onReceiveUserSwitchBroadcast() {
        ArgumentCaptor<BroadcastReceiver> callbackCaptor =
                ArgumentCaptor.forClass(BroadcastReceiver.class);
        verify(mBroadcastDispatcher).registerReceiver(
                callbackCaptor.capture(),
                argThat(intentFilter -> intentFilter.hasAction(Intent.ACTION_USER_SWITCHED)),
                isNull(),
                isNull(),
                eq(Context.RECEIVER_EXPORTED),
                isNull());
        BroadcastReceiver callback = callbackCaptor.getValue();

        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);
        callback.onReceive(mContext, new Intent(Intent.ACTION_USER_SWITCHED));

        verify(listener).accept(anyString());
    }

    @Test
    public void notifyListeners_onSettingChange_lockScreenShowNotifs() {
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);
        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, true);

        verify(listener).accept(anyString());
    }

    @Test
    public void notifyListeners_onSettingChange_lockScreenAllowPrivateNotifs() {
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);
        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, true);

        verify(listener).accept(anyString());
    }

    @Test
    public void hideSilentNotificationsPerUserSettingWithHighPriorityParent() {
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);
        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, true);
        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_SILENT_NOTIFICATIONS, false);
        GroupEntry parent = new GroupEntryBuilder()
                .setKey("parent")
                .addChild(mEntry)
                .setSummary(new NotificationEntryBuilder()
                        .setUser(new UserHandle(NOTIF_USER_ID))
                        .setImportance(IMPORTANCE_LOW)
                        .build())
                .build();
        mEntry = new NotificationEntryBuilder()
                .setUser(new UserHandle(NOTIF_USER_ID))
                .setImportance(IMPORTANCE_LOW)
                .setParent(parent)
                .build();
        when(mHighPriorityProvider.isHighPriority(any())).thenReturn(false);
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void hideSilentNotificationsPerUserSetting() {
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);
        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, true);
        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_SILENT_NOTIFICATIONS, false);
        mEntry = new NotificationEntryBuilder()
                .setUser(new UserHandle(NOTIF_USER_ID))
                .setImportance(IMPORTANCE_LOW)
                .build();
        when(mHighPriorityProvider.isHighPriority(any())).thenReturn(false);
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void notifyListeners_onSettingChange_zenMode() {
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);
        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        mFakeSettings.putBool(Settings.Global.ZEN_MODE, true);

        verify(listener).accept(anyString());
    }

    @Test
    public void notifyListeners_onSettingChange_lockScreenShowSilentNotifs() {
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);
        Consumer<String> listener = mock(Consumer.class);
        mKeyguardNotificationVisibilityProvider.addOnStateChangedListener(listener);

        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_SILENT_NOTIFICATIONS, true);

        verify(listener).accept(anyString());
    }

    @Test
    public void unfilteredState() {
        // GIVEN an 'unfiltered-keyguard-showing' state
        setupUnfilteredState(mEntry);

        // THEN don't filter out the entry
        assertFalse(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void keyguardNotShowing() {
        // GIVEN the lockscreen isn't showing
        setupUnfilteredState(mEntry);
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(SHADE);

        // THEN don't filter out the entry
        assertFalse(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void doNotShowLockscreenNotifications() {
        // GIVEN an 'unfiltered-keyguard-showing' state
        setupUnfilteredState(mEntry);

        // WHEN we shouldn't show any lockscreen notifications
        when(mLockscreenUserManager.shouldShowLockscreenNotifications()).thenReturn(false);

        // THEN filter out the entry
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void lockdown() {
        // GIVEN an 'unfiltered-keyguard-showing' state
        setupUnfilteredState(mEntry);

        // WHEN the notification's user is in lockdown:
        when(mKeyguardUpdateMonitor.isUserInLockdown(NOTIF_USER_ID)).thenReturn(true);

        // THEN filter out the entry
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void publicMode_settingsDisallow() {
        // GIVEN an 'unfiltered-keyguard-showing' state
        setupUnfilteredState(mEntry);

        // WHEN the notification's user is in public mode and settings are configured to disallow
        // notifications in public mode
        when(mLockscreenUserManager.isLockscreenPublicMode(NOTIF_USER_ID)).thenReturn(true);
        when(mLockscreenUserManager.userAllowsNotificationsInPublic(NOTIF_USER_ID))
                .thenReturn(false);

        // THEN filter out the entry
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void publicMode_notifDisallowed() {
        // GIVEN an 'unfiltered-keyguard-showing' state
        setupUnfilteredState(mEntry);

        // WHEN the notification's user is in public mode and settings are configured to disallow
        // notifications in public mode
        when(mLockscreenUserManager.isLockscreenPublicMode(CURR_USER_ID)).thenReturn(true);
        mEntry.setRanking(new RankingBuilder()
                .setKey(mEntry.getKey())
                .setVisibilityOverride(VISIBILITY_SECRET).build());

        // THEN filter out the entry
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void doesNotExceedThresholdToShow() {
        // GIVEN an 'unfiltered-keyguard-showing' state
        setupUnfilteredState(mEntry);

        // WHEN the notification doesn't exceed the threshold to show on the lockscreen
        mEntry.setRanking(new RankingBuilder()
                .setKey(mEntry.getKey())
                .setImportance(IMPORTANCE_MIN)
                .build());
        when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);

        // THEN filter out the entry
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void showSilentOnLockscreenSetting() {
        // GIVEN an 'unfiltered-keyguard-showing' state
        setupUnfilteredState(mEntry);

        // WHEN the notification is not high priority and not ambient
        mEntry.setRanking(new RankingBuilder()
                .setKey(mEntry.getKey())
                .setImportance(IMPORTANCE_LOW)
                .build());
        when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);

        // WHEN the show silent notifs on lockscreen setting is true
        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_SILENT_NOTIFICATIONS, true);

        // THEN do not filter out the entry
        assertFalse(mKeyguardNotificationVisibilityProvider.shouldHideNotification(mEntry));
    }

    @Test
    public void summaryExceedsThresholdToShow() {
        // GIVEN the notification doesn't exceed the threshold to show on the lockscreen
        // but it's part of a group (has a parent)
        final NotificationEntry entryWithParent = new NotificationEntryBuilder()
                .setUser(new UserHandle(NOTIF_USER_ID))
                .build();

        final GroupEntry parent = new GroupEntryBuilder()
                .setKey("test_group_key")
                .setSummary(new NotificationEntryBuilder()
                        .setImportance(IMPORTANCE_HIGH)
                        .build())
                .addChild(entryWithParent)
                .build();

        setupUnfilteredState(entryWithParent);
        entryWithParent.setRanking(new RankingBuilder()
                .setKey(entryWithParent.getKey())
                .setImportance(IMPORTANCE_MIN)
                .build());

        // WHEN its parent does exceed threshold tot show on the lockscreen
        mFakeSettings.putBool(Settings.Secure.LOCK_SCREEN_SHOW_SILENT_NOTIFICATIONS, false);
        when(mHighPriorityProvider.isHighPriority(parent)).thenReturn(true);

        // THEN filter out the entry regardless of parent
        assertTrue(
                mKeyguardNotificationVisibilityProvider.shouldHideNotification(entryWithParent));

        // WHEN its parent doesn't exceed threshold to show on lockscreen
        when(mHighPriorityProvider.isHighPriority(parent)).thenReturn(false);
        modifyEntry(parent.getSummary(), builder -> builder
                .setImportance(IMPORTANCE_MIN)
                .done());

        // THEN filter out the entry
        assertTrue(mKeyguardNotificationVisibilityProvider.shouldHideNotification(entryWithParent));
    }

    /**
     * setup a state where the notification will not be filtered by the
     * KeyguardNotificationCoordinator when the keyguard is showing.
     */
    private void setupUnfilteredState(NotificationEntry entry) {
        // keyguard is showing
        when(mStatusBarStateController.getCurrentOrUpcomingState()).thenReturn(KEYGUARD);

        // show notifications on the lockscreen
        when(mLockscreenUserManager.shouldShowLockscreenNotifications()).thenReturn(true);

        // neither the current user nor the notification's user is in lockdown
        when(mLockscreenUserManager.getCurrentUserId()).thenReturn(CURR_USER_ID);
        when(mKeyguardUpdateMonitor.isUserInLockdown(NOTIF_USER_ID)).thenReturn(false);
        when(mKeyguardUpdateMonitor.isUserInLockdown(CURR_USER_ID)).thenReturn(false);

        // not in public mode
        when(mLockscreenUserManager.isLockscreenPublicMode(CURR_USER_ID)).thenReturn(false);
        when(mLockscreenUserManager.isLockscreenPublicMode(NOTIF_USER_ID)).thenReturn(false);

        // entry's ranking - should show on all lockscreens
        // + priority of the notification exceeds the threshold to be shown on the lockscreen
        entry.setRanking(new RankingBuilder()
                .setKey(mEntry.getKey())
                .setVisibilityOverride(VISIBILITY_PUBLIC)
                .setImportance(IMPORTANCE_HIGH)
                .build());

        // settings allows notifications in public mode
        when(mLockscreenUserManager.userAllowsNotificationsInPublic(CURR_USER_ID)).thenReturn(true);
        when(mLockscreenUserManager.userAllowsNotificationsInPublic(NOTIF_USER_ID))
                .thenReturn(true);

        // notification doesn't have a summary

        // notification is high priority, so it shouldn't be filtered
        when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(true);
    }

    @SysUISingleton
    @Component(modules = { KeyguardNotificationVisibilityProviderModule.class })
    interface TestComponent {
        KeyguardNotificationVisibilityProvider getProvider();
        Map<Class<?>, CoreStartable> getCoreStartables();

        @Component.Factory
        interface Factory {
            TestComponent create(
                    @BindsInstance Context context,
                    @BindsInstance @Main Handler handler,
                    @BindsInstance KeyguardStateController keyguardStateController,
                    @BindsInstance NotificationLockscreenUserManager lockscreenUserManager,
                    @BindsInstance KeyguardUpdateMonitor keyguardUpdateMonitor,
                    @BindsInstance HighPriorityProvider highPriorityProvider,
                    @BindsInstance SysuiStatusBarStateController statusBarStateController,
                    @BindsInstance BroadcastDispatcher broadcastDispatcher,
                    @BindsInstance SecureSettings secureSettings,
                    @BindsInstance GlobalSettings globalSettings
            );
        }
    }
}