1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.systemui.keyguard;
18 
19 import static android.os.PowerManager.WAKE_REASON_WAKE_MOTION;
20 import static android.provider.Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT;
21 import static android.view.WindowManager.TRANSIT_OLD_KEYGUARD_GOING_AWAY;
22 import static android.view.WindowManagerPolicyConstants.OFF_BECAUSE_OF_TIMEOUT;
23 import static android.view.WindowManagerPolicyConstants.OFF_BECAUSE_OF_USER;
24 
25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
26 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT;
27 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN;
28 import static com.android.systemui.keyguard.KeyguardViewMediator.DELAYED_KEYGUARD_ACTION;
29 import static com.android.systemui.keyguard.KeyguardViewMediator.KEYGUARD_LOCK_AFTER_DELAY_DEFAULT;
30 import static com.android.systemui.keyguard.KeyguardViewMediator.REBOOT_MAINLINE_UPDATE;
31 import static com.android.systemui.keyguard.KeyguardViewMediator.SYS_BOOT_REASON_PROP;
32 
33 import static org.junit.Assert.assertEquals;
34 import static org.junit.Assert.assertFalse;
35 import static org.junit.Assert.assertTrue;
36 import static org.mockito.ArgumentMatchers.any;
37 import static org.mockito.ArgumentMatchers.anyBoolean;
38 import static org.mockito.ArgumentMatchers.anyInt;
39 import static org.mockito.ArgumentMatchers.anyLong;
40 import static org.mockito.ArgumentMatchers.anyString;
41 import static org.mockito.Mockito.atLeast;
42 import static org.mockito.Mockito.clearInvocations;
43 import static org.mockito.Mockito.eq;
44 import static org.mockito.Mockito.mock;
45 import static org.mockito.Mockito.never;
46 import static org.mockito.Mockito.verify;
47 import static org.mockito.Mockito.when;
48 
49 import android.app.AlarmManager;
50 import android.app.IActivityManager;
51 import android.app.PendingIntent;
52 import android.app.admin.DevicePolicyManager;
53 import android.app.trust.TrustManager;
54 import android.content.Context;
55 import android.os.PowerManager;
56 import android.os.PowerManager.WakeLock;
57 import android.telephony.TelephonyManager;
58 import android.testing.AndroidTestingRunner;
59 import android.testing.TestableLooper;
60 import android.view.IRemoteAnimationFinishedCallback;
61 import android.view.RemoteAnimationTarget;
62 import android.view.View;
63 import android.view.ViewRootImpl;
64 import android.view.WindowManager;
65 
66 import androidx.test.filters.SmallTest;
67 
68 import com.android.internal.jank.InteractionJankMonitor;
69 import com.android.internal.logging.InstanceId;
70 import com.android.internal.logging.UiEventLogger;
71 import com.android.internal.widget.LockPatternUtils;
72 import com.android.keyguard.KeyguardDisplayManager;
73 import com.android.keyguard.KeyguardSecurityView;
74 import com.android.keyguard.KeyguardUpdateMonitor;
75 import com.android.keyguard.KeyguardUpdateMonitorCallback;
76 import com.android.keyguard.TestScopeProvider;
77 import com.android.keyguard.mediator.ScreenOnCoordinator;
78 import com.android.systemui.DejankUtils;
79 import com.android.systemui.SysuiTestCase;
80 import com.android.systemui.animation.ActivityLaunchAnimator;
81 import com.android.systemui.biometrics.AuthController;
82 import com.android.systemui.broadcast.BroadcastDispatcher;
83 import com.android.systemui.classifier.FalsingCollectorFake;
84 import com.android.systemui.colorextraction.SysuiColorExtractor;
85 import com.android.systemui.dreams.DreamOverlayStateController;
86 import com.android.systemui.dump.DumpManager;
87 import com.android.systemui.flags.FakeFeatureFlags;
88 import com.android.systemui.flags.Flags;
89 import com.android.systemui.flags.SystemPropertiesHelper;
90 import com.android.systemui.keyguard.ui.viewmodel.DreamingToLockscreenTransitionViewModel;
91 import com.android.systemui.log.SessionTracker;
92 import com.android.systemui.navigationbar.NavigationModeController;
93 import com.android.systemui.settings.UserTracker;
94 import com.android.systemui.shade.NotificationShadeWindowControllerImpl;
95 import com.android.systemui.shade.ShadeController;
96 import com.android.systemui.shade.ShadeExpansionStateManager;
97 import com.android.systemui.shade.ShadeWindowLogger;
98 import com.android.systemui.statusbar.NotificationShadeDepthController;
99 import com.android.systemui.statusbar.NotificationShadeWindowController;
100 import com.android.systemui.statusbar.SysuiStatusBarStateController;
101 import com.android.systemui.statusbar.phone.BiometricUnlockController;
102 import com.android.systemui.statusbar.phone.CentralSurfaces;
103 import com.android.systemui.statusbar.phone.DozeParameters;
104 import com.android.systemui.statusbar.phone.KeyguardBypassController;
105 import com.android.systemui.statusbar.phone.ScreenOffAnimationController;
106 import com.android.systemui.statusbar.phone.ScrimController;
107 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
108 import com.android.systemui.statusbar.policy.ConfigurationController;
109 import com.android.systemui.statusbar.policy.KeyguardStateController;
110 import com.android.systemui.statusbar.policy.UserSwitcherController;
111 import com.android.systemui.util.DeviceConfigProxy;
112 import com.android.systemui.util.DeviceConfigProxyFake;
113 import com.android.systemui.util.concurrency.FakeExecutor;
114 import com.android.systemui.util.kotlin.JavaAdapter;
115 import com.android.systemui.util.settings.SecureSettings;
116 import com.android.systemui.util.settings.SystemSettings;
117 import com.android.systemui.util.time.FakeSystemClock;
118 import com.android.systemui.wallpapers.data.repository.FakeWallpaperRepository;
119 import com.android.wm.shell.keyguard.KeyguardTransitions;
120 
121 import org.junit.After;
122 import org.junit.Before;
123 import org.junit.Test;
124 import org.junit.runner.RunWith;
125 import org.mockito.ArgumentCaptor;
126 import org.mockito.Captor;
127 import org.mockito.Mock;
128 import org.mockito.MockitoAnnotations;
129 
130 import kotlinx.coroutines.CoroutineDispatcher;
131 import kotlinx.coroutines.flow.Flow;
132 import kotlinx.coroutines.test.TestScope;
133 
134 @RunWith(AndroidTestingRunner.class)
135 @TestableLooper.RunWithLooper
136 @SmallTest
137 public class KeyguardViewMediatorTest extends SysuiTestCase {
138     private KeyguardViewMediator mViewMediator;
139 
140     private final TestScope mTestScope = TestScopeProvider.getTestScope();
141     private final JavaAdapter mJavaAdapter = new JavaAdapter(mTestScope.getBackgroundScope());
142 
143     private @Mock UserTracker mUserTracker;
144     private @Mock DevicePolicyManager mDevicePolicyManager;
145     private @Mock LockPatternUtils mLockPatternUtils;
146     private @Mock KeyguardUpdateMonitor mUpdateMonitor;
147     private @Mock StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
148     private @Mock BroadcastDispatcher mBroadcastDispatcher;
149     private @Mock DismissCallbackRegistry mDismissCallbackRegistry;
150     private @Mock DumpManager mDumpManager;
151     private @Mock WindowManager mWindowManager;
152     private @Mock IActivityManager mActivityManager;
153     private @Mock ConfigurationController mConfigurationController;
154     private @Mock PowerManager mPowerManager;
155     private @Mock TrustManager mTrustManager;
156     private @Mock UserSwitcherController mUserSwitcherController;
157     private @Mock NavigationModeController mNavigationModeController;
158     private @Mock KeyguardDisplayManager mKeyguardDisplayManager;
159     private @Mock KeyguardBypassController mKeyguardBypassController;
160     private @Mock DozeParameters mDozeParameters;
161     private @Mock SysuiStatusBarStateController mStatusBarStateController;
162     private @Mock KeyguardStateController mKeyguardStateController;
163     private @Mock NotificationShadeDepthController mNotificationShadeDepthController;
164     private @Mock KeyguardUnlockAnimationController mKeyguardUnlockAnimationController;
165     private @Mock ScreenOffAnimationController mScreenOffAnimationController;
166     private @Mock InteractionJankMonitor mInteractionJankMonitor;
167     private @Mock ScreenOnCoordinator mScreenOnCoordinator;
168     private @Mock KeyguardTransitions mKeyguardTransitions;
169     private @Mock ShadeController mShadeController;
170     private NotificationShadeWindowController mNotificationShadeWindowController;
171     private @Mock DreamOverlayStateController mDreamOverlayStateController;
172     private @Mock ActivityLaunchAnimator mActivityLaunchAnimator;
173     private @Mock ScrimController mScrimController;
174     private @Mock SysuiColorExtractor mColorExtractor;
175     private @Mock AuthController mAuthController;
176     private @Mock ShadeExpansionStateManager mShadeExpansionStateManager;
177     private @Mock ShadeWindowLogger mShadeWindowLogger;
178     private @Captor ArgumentCaptor<KeyguardStateController.Callback>
179             mKeyguardStateControllerCallback;
180     private @Captor ArgumentCaptor<KeyguardUpdateMonitorCallback>
181             mKeyguardUpdateMonitorCallbackCaptor;
182     private DeviceConfigProxy mDeviceConfig = new DeviceConfigProxyFake();
183     private FakeExecutor mUiBgExecutor = new FakeExecutor(new FakeSystemClock());
184 
185     private FalsingCollectorFake mFalsingCollector;
186 
187     private @Mock CentralSurfaces mCentralSurfaces;
188     private @Mock UiEventLogger mUiEventLogger;
189     private @Mock SessionTracker mSessionTracker;
190     private @Mock SystemSettings mSystemSettings;
191     private @Mock SecureSettings mSecureSettings;
192     private @Mock AlarmManager mAlarmManager;
193     private FakeSystemClock mSystemClock;
194     private final FakeWallpaperRepository mWallpaperRepository = new FakeWallpaperRepository();
195 
196     private @Mock CoroutineDispatcher mDispatcher;
197     private @Mock DreamingToLockscreenTransitionViewModel mDreamingToLockscreenTransitionViewModel;
198     private @Mock SystemPropertiesHelper mSystemPropertiesHelper;
199 
200     private FakeFeatureFlags mFeatureFlags;
201     private int mInitialUserId;
202 
203     @Before
setUp()204     public void setUp() throws Exception {
205         MockitoAnnotations.initMocks(this);
206         mFalsingCollector = new FalsingCollectorFake();
207         mSystemClock = new FakeSystemClock();
208         when(mLockPatternUtils.getDevicePolicyManager()).thenReturn(mDevicePolicyManager);
209         when(mPowerManager.newWakeLock(anyInt(), any())).thenReturn(mock(WakeLock.class));
210         when(mPowerManager.isInteractive()).thenReturn(true);
211         when(mInteractionJankMonitor.begin(any(), anyInt())).thenReturn(true);
212         when(mInteractionJankMonitor.end(anyInt())).thenReturn(true);
213         mContext.addMockSystemService(Context.ALARM_SERVICE, mAlarmManager);
214         final ViewRootImpl testViewRoot = mock(ViewRootImpl.class);
215         when(testViewRoot.getView()).thenReturn(mock(View.class));
216         when(mStatusBarKeyguardViewManager.getViewRootImpl()).thenReturn(testViewRoot);
217         when(mDreamingToLockscreenTransitionViewModel.getDreamOverlayAlpha())
218                 .thenReturn(mock(Flow.class));
219         when(mDreamingToLockscreenTransitionViewModel.getTransitionEnded())
220                 .thenReturn(mock(Flow.class));
221         mNotificationShadeWindowController = new NotificationShadeWindowControllerImpl(mContext,
222                 mWindowManager, mActivityManager, mDozeParameters, mStatusBarStateController,
223                 mConfigurationController, mViewMediator, mKeyguardBypassController,
224                 mUiBgExecutor, mColorExtractor, mDumpManager, mKeyguardStateController,
225                 mScreenOffAnimationController, mAuthController, mShadeExpansionStateManager,
226                 mShadeWindowLogger);
227         mFeatureFlags = new FakeFeatureFlags();
228         mFeatureFlags.set(Flags.KEYGUARD_WM_STATE_REFACTOR, false);
229 
230         DejankUtils.setImmediate(true);
231 
232         createAndStartViewMediator();
233         mInitialUserId = KeyguardUpdateMonitor.getCurrentUser();
234     }
235 
236     @After
teardown()237     public void teardown() {
238         KeyguardUpdateMonitor.setCurrentUser(mInitialUserId);
239     }
240 
241     @Test
242     @TestableLooper.RunWithLooper(setAsMainLooper = true)
onLockdown_showKeyguard_evenIfKeyguardIsNotEnabledExternally()243     public void onLockdown_showKeyguard_evenIfKeyguardIsNotEnabledExternally() {
244         // GIVEN keyguard is not enabled and isn't showing
245         mViewMediator.onSystemReady();
246         mViewMediator.setKeyguardEnabled(false);
247         TestableLooper.get(this).processAllMessages();
248         captureKeyguardUpdateMonitorCallback();
249         assertFalse(mViewMediator.isShowingAndNotOccluded());
250 
251         // WHEN lockdown occurs
252         when(mLockPatternUtils.isUserInLockdown(anyInt())).thenReturn(true);
253         mKeyguardUpdateMonitorCallbackCaptor.getValue().onStrongAuthStateChanged(0);
254 
255         // THEN keyguard is shown
256         TestableLooper.get(this).processAllMessages();
257         assertTrue(mViewMediator.isShowingAndNotOccluded());
258     }
259 
260     @Test
261     @TestableLooper.RunWithLooper(setAsMainLooper = true)
doNotHideKeyguard_whenLockdown_onKeyguardNotEnabledExternally()262     public void doNotHideKeyguard_whenLockdown_onKeyguardNotEnabledExternally() {
263         // GIVEN keyguard is enabled and lockdown occurred so the keyguard is showing
264         mViewMediator.onSystemReady();
265         mViewMediator.setKeyguardEnabled(true);
266         TestableLooper.get(this).processAllMessages();
267         captureKeyguardUpdateMonitorCallback();
268         when(mLockPatternUtils.isUserInLockdown(anyInt())).thenReturn(true);
269         mKeyguardUpdateMonitorCallbackCaptor.getValue().onStrongAuthStateChanged(0);
270         assertTrue(mViewMediator.isShowingAndNotOccluded());
271 
272         // WHEN keyguard is externally not enabled anymore
273         mViewMediator.setKeyguardEnabled(false);
274 
275         // THEN keyguard is NOT dismissed; it continues to show
276         TestableLooper.get(this).processAllMessages();
277         assertTrue(mViewMediator.isShowingAndNotOccluded());
278     }
279 
280     @Test
testOnGoingToSleep_UpdatesKeyguardGoingAway()281     public void testOnGoingToSleep_UpdatesKeyguardGoingAway() {
282         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
283         verify(mUpdateMonitor).dispatchKeyguardGoingAway(false);
284         verify(mStatusBarKeyguardViewManager, never()).setKeyguardGoingAwayState(anyBoolean());
285     }
286 
287     @Test
288     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testOnStartedWakingUp_whileSleeping_ifWakeAndUnlocking_doesNotShowKeyguard()289     public void testOnStartedWakingUp_whileSleeping_ifWakeAndUnlocking_doesNotShowKeyguard() {
290         when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
291         when(mLockPatternUtils.getPowerButtonInstantlyLocks(anyInt())).thenReturn(true);
292         mViewMediator.onSystemReady();
293         TestableLooper.get(this).processAllMessages();
294 
295         mViewMediator.setShowingLocked(false);
296         TestableLooper.get(this).processAllMessages();
297 
298         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
299         mViewMediator.onWakeAndUnlocking(false);
300         mViewMediator.onStartedWakingUp(OFF_BECAUSE_OF_USER, false);
301         TestableLooper.get(this).processAllMessages();
302 
303         assertFalse(mViewMediator.isShowingAndNotOccluded());
304         verify(mKeyguardStateController, never()).notifyKeyguardState(eq(true), anyBoolean());
305     }
306 
307     @Test
308     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testOnStartedWakingUp_whileSleeping_ifNotWakeAndUnlocking_showsKeyguard()309     public void testOnStartedWakingUp_whileSleeping_ifNotWakeAndUnlocking_showsKeyguard() {
310         when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
311         when(mLockPatternUtils.getPowerButtonInstantlyLocks(anyInt())).thenReturn(true);
312         mViewMediator.onSystemReady();
313         TestableLooper.get(this).processAllMessages();
314 
315         mViewMediator.setShowingLocked(false);
316         TestableLooper.get(this).processAllMessages();
317 
318         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
319         mViewMediator.onStartedWakingUp(OFF_BECAUSE_OF_USER, false);
320 
321         TestableLooper.get(this).processAllMessages();
322 
323         assertTrue(mViewMediator.isShowingAndNotOccluded());
324     }
325 
326     @Test
testRegisterDumpable()327     public void testRegisterDumpable() {
328         verify(mDumpManager).registerDumpable(KeyguardViewMediator.class.getName(), mViewMediator);
329         verify(mStatusBarKeyguardViewManager, never()).setKeyguardGoingAwayState(anyBoolean());
330     }
331 
332     @Test
testKeyguardGone_notGoingaway()333     public void testKeyguardGone_notGoingaway() {
334         mViewMediator.mViewMediatorCallback.keyguardGone();
335         verify(mStatusBarKeyguardViewManager).setKeyguardGoingAwayState(eq(false));
336     }
337 
338     @Test
testIsAnimatingScreenOff()339     public void testIsAnimatingScreenOff() {
340         when(mDozeParameters.shouldControlUnlockedScreenOff()).thenReturn(true);
341         when(mDozeParameters.shouldAnimateDozingChange()).thenReturn(true);
342 
343         mViewMediator.onFinishedGoingToSleep(OFF_BECAUSE_OF_USER, false);
344         mViewMediator.setDozing(true);
345 
346         // Mid-doze, we should be animating the screen off animation.
347         mViewMediator.onDozeAmountChanged(0.5f, 0.5f);
348         assertTrue(mViewMediator.isAnimatingScreenOff());
349 
350         // Once we're 100% dozed, the screen off animation should be completed.
351         mViewMediator.onDozeAmountChanged(1f, 1f);
352         assertFalse(mViewMediator.isAnimatingScreenOff());
353     }
354 
355     @Test
356     @TestableLooper.RunWithLooper(setAsMainLooper = true)
wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOff()357     public void wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOff() {
358         createAndStartViewMediator(false);
359 
360         mViewMediator.onSystemReady();
361         TestableLooper.get(this).processAllMessages();
362 
363         // Given device is dreaming
364         when(mUpdateMonitor.isDreaming()).thenReturn(true);
365 
366         // When keyguard is going away
367         mKeyguardStateController.notifyKeyguardGoingAway(true);
368 
369         // And keyguard is disabled which will call #handleHide
370         mViewMediator.setKeyguardEnabled(false);
371         TestableLooper.get(this).processAllMessages();
372 
373         // Then dream should wake up
374         verify(mPowerManager).wakeUp(anyLong(), anyInt(),
375                 eq("com.android.systemui:UNLOCK_DREAMING"));
376     }
377 
378     @Test
379     @TestableLooper.RunWithLooper(setAsMainLooper = true)
wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOn()380     public void wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOn() {
381         createAndStartViewMediator(true);
382 
383         mViewMediator.onSystemReady();
384         TestableLooper.get(this).processAllMessages();
385         when(mPowerManager.isInteractive()).thenReturn(true);
386 
387         // Given device is dreaming
388         when(mUpdateMonitor.isDreaming()).thenReturn(true);
389 
390         // When keyguard is going away
391         mKeyguardStateController.notifyKeyguardGoingAway(true);
392 
393         // And keyguard is disabled which will call #handleHide
394         mViewMediator.setKeyguardEnabled(false);
395         TestableLooper.get(this).processAllMessages();
396 
397         mViewMediator.mViewMediatorCallback.keyguardDonePending(true,
398                 mUpdateMonitor.getCurrentUser());
399         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
400         final ArgumentCaptor<Runnable> animationRunnableCaptor =
401                 ArgumentCaptor.forClass(Runnable.class);
402         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
403                 animationRunnableCaptor.capture());
404 
405         when(mStatusBarStateController.isDreaming()).thenReturn(true);
406         when(mStatusBarStateController.isDozing()).thenReturn(false);
407         animationRunnableCaptor.getValue().run();
408 
409         when(mKeyguardStateController.isShowing()).thenReturn(false);
410         mViewMediator.mViewMediatorCallback.keyguardGone();
411 
412         // Then dream should wake up
413         verify(mPowerManager).wakeUp(anyLong(), anyInt(),
414                 eq("com.android.systemui:UNLOCK_DREAMING"));
415     }
416 
417     @Test
418     @TestableLooper.RunWithLooper(setAsMainLooper = true)
restoreBouncerWhenSimLockedAndKeyguardIsGoingAway()419     public void restoreBouncerWhenSimLockedAndKeyguardIsGoingAway() {
420         // When showing and provisioned
421         mViewMediator.onSystemReady();
422         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(true);
423         mViewMediator.setShowingLocked(true);
424 
425         // and a SIM becomes locked and requires a PIN
426         mViewMediator.mUpdateCallback.onSimStateChanged(
427                 1 /* subId */,
428                 0 /* slotId */,
429                 TelephonyManager.SIM_STATE_PIN_REQUIRED);
430 
431         // and the keyguard goes away
432         mViewMediator.setShowingLocked(false);
433         when(mKeyguardStateController.isShowing()).thenReturn(false);
434         mViewMediator.mUpdateCallback.onKeyguardVisibilityChanged(false);
435 
436         TestableLooper.get(this).processAllMessages();
437 
438         // then make sure it comes back
439         verify(mStatusBarKeyguardViewManager, atLeast(1)).show(null);
440     }
441 
442     @Test
443     @TestableLooper.RunWithLooper(setAsMainLooper = true)
restoreBouncerWhenSimLockedAndKeyguardIsGoingAway_initiallyNotShowing()444     public void restoreBouncerWhenSimLockedAndKeyguardIsGoingAway_initiallyNotShowing() {
445         // When showing and provisioned
446         mViewMediator.onSystemReady();
447         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(true);
448         mViewMediator.setShowingLocked(false);
449 
450         // and a SIM becomes locked and requires a PIN
451         mViewMediator.mUpdateCallback.onSimStateChanged(
452                 1 /* subId */,
453                 0 /* slotId */,
454                 TelephonyManager.SIM_STATE_PIN_REQUIRED);
455 
456         // and the keyguard goes away
457         mViewMediator.setShowingLocked(false);
458         when(mKeyguardStateController.isShowing()).thenReturn(false);
459         mViewMediator.mUpdateCallback.onKeyguardVisibilityChanged(false);
460 
461         TestableLooper.get(this).processAllMessages();
462 
463         // then make sure it comes back
464         verify(mStatusBarKeyguardViewManager, atLeast(1)).show(null);
465     }
466 
467     @Test
testBouncerPrompt_deviceLockedByAdmin()468     public void testBouncerPrompt_deviceLockedByAdmin() {
469         // GIVEN no trust agents enabled and biometrics aren't enrolled
470         when(mUpdateMonitor.isTrustUsuallyManaged(anyInt())).thenReturn(false);
471         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(false);
472 
473         // WHEN the strong auth reason is AFTER_DPM_LOCK_NOW
474         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
475                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
476         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
477         when(strongAuthTracker.getStrongAuthForUser(anyInt())).thenReturn(
478                 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW);
479 
480         // THEN the bouncer prompt reason should return PROMPT_REASON_DEVICE_ADMIN
481         assertEquals(KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN,
482                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
483     }
484 
485     @Test
testBouncerPrompt_deviceRestartedDueToMainlineUpdate()486     public void testBouncerPrompt_deviceRestartedDueToMainlineUpdate() {
487         // GIVEN biometrics enrolled
488         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(true);
489 
490         // WHEN reboot caused by ota update
491         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
492                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
493         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
494         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(false);
495         when(mSystemPropertiesHelper.get(SYS_BOOT_REASON_PROP)).thenReturn(REBOOT_MAINLINE_UPDATE);
496 
497         // THEN the bouncer prompt reason should return PROMPT_REASON_RESTART_FOR_OTA
498         assertEquals(KeyguardSecurityView.PROMPT_REASON_RESTART_FOR_MAINLINE_UPDATE,
499                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
500     }
501 
502     @Test
testBouncerPrompt_afterUserLockDown()503     public void testBouncerPrompt_afterUserLockDown() {
504         // GIVEN biometrics enrolled
505         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(true);
506 
507         // WHEN user has locked down the device
508         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
509                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
510         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
511         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
512         when(strongAuthTracker.getStrongAuthForUser(anyInt()))
513                 .thenReturn(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
514 
515         // THEN the bouncer prompt reason should return PROMPT_REASON_USER_REQUEST
516         assertEquals(KeyguardSecurityView.PROMPT_REASON_USER_REQUEST,
517                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
518     }
519 
520     @Test
testBouncerPrompt_afterUserLockDown_noBiometricsEnrolled()521     public void testBouncerPrompt_afterUserLockDown_noBiometricsEnrolled() {
522         // GIVEN biometrics not enrolled
523         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(false);
524 
525         // WHEN user has locked down the device
526         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
527                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
528         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
529         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
530         when(strongAuthTracker.getStrongAuthForUser(anyInt()))
531                 .thenReturn(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
532 
533         // THEN the bouncer prompt reason should return the default prompt
534         assertEquals(KeyguardSecurityView.PROMPT_REASON_NONE,
535                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
536     }
537 
538     @Test
testBouncerPrompt_nonStrongIdleTimeout()539     public void testBouncerPrompt_nonStrongIdleTimeout() {
540         // GIVEN trust agents enabled and biometrics are enrolled
541         when(mUpdateMonitor.isTrustUsuallyManaged(anyInt())).thenReturn(true);
542         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(true);
543 
544         // WHEN the strong auth reason is STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT
545         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
546                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
547         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
548         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
549         when(strongAuthTracker.isNonStrongBiometricAllowedAfterIdleTimeout(
550                 anyInt())).thenReturn(false);
551         when(strongAuthTracker.getStrongAuthForUser(anyInt())).thenReturn(
552                 STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT);
553 
554         // THEN the bouncer prompt reason should return
555         // STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT
556         assertEquals(KeyguardSecurityView.PROMPT_REASON_NON_STRONG_BIOMETRIC_TIMEOUT,
557                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
558     }
559 
560     @Test
lockAfterScreenTimeoutUsesValueFromSettings()561     public void lockAfterScreenTimeoutUsesValueFromSettings() {
562         int currentUserId = 99;
563         int userSpecificTimeout = 5999;
564         KeyguardUpdateMonitor.setCurrentUser(currentUserId);
565 
566         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(false);
567         when(mDevicePolicyManager.getMaximumTimeToLock(null, currentUserId)).thenReturn(0L);
568         when(mSecureSettings.getIntForUser(LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
569                 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT, currentUserId)).thenReturn(userSpecificTimeout);
570         mSystemClock.setElapsedRealtime(0L);
571         ArgumentCaptor<PendingIntent> pendingIntent = ArgumentCaptor.forClass(PendingIntent.class);
572 
573         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_TIMEOUT);
574 
575         verify(mAlarmManager).setExactAndAllowWhileIdle(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
576                 eq(Long.valueOf(userSpecificTimeout)), pendingIntent.capture());
577         assertEquals(DELAYED_KEYGUARD_ACTION, pendingIntent.getValue().getIntent().getAction());
578     }
579 
580     @Test
lockAfterSpecifiedAfterDreamStarted()581     public void lockAfterSpecifiedAfterDreamStarted() {
582         int currentUserId = 99;
583         int userSpecificTimeout = 5999;
584         KeyguardUpdateMonitor.setCurrentUser(currentUserId);
585 
586         // set mDeviceInteractive to true
587         mViewMediator.onStartedWakingUp(WAKE_REASON_WAKE_MOTION, false);
588         mFeatureFlags.set(Flags.LOCKSCREEN_WITHOUT_SECURE_LOCK_WHEN_DREAMING, false);
589         when(mLockPatternUtils.isSecure(currentUserId)).thenReturn(true);
590         when(mDevicePolicyManager.getMaximumTimeToLock(null, currentUserId)).thenReturn(0L);
591         when(mSecureSettings.getIntForUser(LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
592                 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT, currentUserId)).thenReturn(userSpecificTimeout);
593         mSystemClock.setElapsedRealtime(0L);
594         ArgumentCaptor<PendingIntent> pendingIntent = ArgumentCaptor.forClass(PendingIntent.class);
595 
596         mViewMediator.onDreamingStarted();
597 
598         verify(mAlarmManager).setExactAndAllowWhileIdle(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
599                 eq(Long.valueOf(userSpecificTimeout)), pendingIntent.capture());
600         assertEquals(DELAYED_KEYGUARD_ACTION, pendingIntent.getValue().getIntent().getAction());
601     }
602 
603     @Test
testHideSurfaceBehindKeyguardMarksKeyguardNotGoingAway()604     public void testHideSurfaceBehindKeyguardMarksKeyguardNotGoingAway() {
605         mViewMediator.hideSurfaceBehindKeyguard();
606 
607         verify(mKeyguardStateController).notifyKeyguardGoingAway(false);
608     }
609 
610     @Test
testUpdateIsKeyguardAfterOccludeAnimationEnds()611     public void testUpdateIsKeyguardAfterOccludeAnimationEnds() {
612         mViewMediator.mOccludeAnimationController.onLaunchAnimationEnd(
613                 false /* isExpandingFullyAbove */);
614 
615         // Since the updateIsKeyguard call is delayed during the animation, ensure it's called once
616         // it ends.
617         verify(mCentralSurfaces).updateIsKeyguard();
618     }
619 
620     @Test
testUpdateIsKeyguardAfterOccludeAnimationIsCancelled()621     public void testUpdateIsKeyguardAfterOccludeAnimationIsCancelled() {
622         mViewMediator.mOccludeAnimationController.onLaunchAnimationCancelled(
623                 null /* newKeyguardOccludedState */);
624 
625         // Since the updateIsKeyguard call is delayed during the animation, ensure it's called if
626         // it's cancelled.
627         verify(mCentralSurfaces).updateIsKeyguard();
628     }
629 
630     @Test
631     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testCancelKeyguardExitAnimation_noPendingLock_keyguardWillNotBeShowing()632     public void testCancelKeyguardExitAnimation_noPendingLock_keyguardWillNotBeShowing() {
633         startMockKeyguardExitAnimation();
634         cancelMockKeyguardExitAnimation();
635 
636         // There should not be a pending lock, but try to handle it anyway to ensure one isn't set.
637         mViewMediator.maybeHandlePendingLock();
638         TestableLooper.get(this).processAllMessages();
639 
640         assertFalse(mViewMediator.isShowingAndNotOccluded());
641         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
642     }
643 
644     @Test
645     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testCancelKeyguardExitAnimationDueToSleep_withPendingLock_keyguardWillBeShowing()646     public void testCancelKeyguardExitAnimationDueToSleep_withPendingLock_keyguardWillBeShowing() {
647         startMockKeyguardExitAnimation();
648 
649         mViewMediator.onStartedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON);
650         mViewMediator.onFinishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, false);
651 
652         cancelMockKeyguardExitAnimation();
653 
654         mViewMediator.maybeHandlePendingLock();
655         TestableLooper.get(this).processAllMessages();
656 
657         assertTrue(mViewMediator.isShowingAndNotOccluded());
658         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(true);
659     }
660 
661     @Test
662     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testCancelKeyguardExitAnimationThenSleep_withPendingLock_keyguardWillBeShowing()663     public void testCancelKeyguardExitAnimationThenSleep_withPendingLock_keyguardWillBeShowing() {
664         startMockKeyguardExitAnimation();
665         cancelMockKeyguardExitAnimation();
666 
667         // Calling cancel above results in keyguard not visible, as there is no pending lock
668         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
669 
670         mViewMediator.maybeHandlePendingLock();
671         TestableLooper.get(this).processAllMessages();
672 
673         mViewMediator.onStartedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON);
674         mViewMediator.onFinishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, false);
675 
676         mViewMediator.maybeHandlePendingLock();
677         TestableLooper.get(this).processAllMessages();
678 
679         assertTrue(mViewMediator.isShowingAndNotOccluded());
680     }
681 
682     @Test
683     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testStartKeyguardExitAnimation_expectSurfaceBehindRemoteAnimationAndExits()684     public void testStartKeyguardExitAnimation_expectSurfaceBehindRemoteAnimationAndExits() {
685         startMockKeyguardExitAnimation();
686         assertTrue(mViewMediator.isAnimatingBetweenKeyguardAndSurfaceBehind());
687 
688         mViewMediator.mViewMediatorCallback.keyguardDonePending(true,
689                 mUpdateMonitor.getCurrentUser());
690         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
691         TestableLooper.get(this).processAllMessages();
692         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
693     }
694 
695     /**
696      * Configures mocks appropriately, then starts the keyguard exit animation.
697      */
startMockKeyguardExitAnimation()698     private void startMockKeyguardExitAnimation() {
699         mViewMediator.onSystemReady();
700         TestableLooper.get(this).processAllMessages();
701 
702         mViewMediator.setShowingLocked(true);
703 
704         RemoteAnimationTarget[] apps = new RemoteAnimationTarget[]{
705                 mock(RemoteAnimationTarget.class)
706         };
707         RemoteAnimationTarget[] wallpapers = new RemoteAnimationTarget[]{
708                 mock(RemoteAnimationTarget.class)
709         };
710         IRemoteAnimationFinishedCallback callback = mock(IRemoteAnimationFinishedCallback.class);
711 
712         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(true);
713         mViewMediator.startKeyguardExitAnimation(TRANSIT_OLD_KEYGUARD_GOING_AWAY, apps, wallpapers,
714                 null, callback);
715         TestableLooper.get(this).processAllMessages();
716     }
717 
718     /**
719      * Configures mocks appropriately, then cancels the keyguard exit animation.
720      */
cancelMockKeyguardExitAnimation()721     private void cancelMockKeyguardExitAnimation() {
722         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(false);
723         mViewMediator.cancelKeyguardExitAnimation();
724         TestableLooper.get(this).processAllMessages();
725     }
726 
727     @Test
728     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testKeyguardDelayedOnGoingToSleep_ifScreenOffAnimationWillPlayButIsntPlayingYet()729     public void testKeyguardDelayedOnGoingToSleep_ifScreenOffAnimationWillPlayButIsntPlayingYet() {
730         mViewMediator.onSystemReady();
731         TestableLooper.get(this).processAllMessages();
732 
733         mViewMediator.setShowingLocked(false);
734         TestableLooper.get(this).processAllMessages();
735 
736         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
737         TestableLooper.get(this).processAllMessages();
738 
739         when(mScreenOffAnimationController.shouldDelayKeyguardShow()).thenReturn(true);
740         when(mScreenOffAnimationController.isKeyguardShowDelayed()).thenReturn(false);
741         mViewMediator.onFinishedGoingToSleep(OFF_BECAUSE_OF_USER, false);
742         TestableLooper.get(this).processAllMessages();
743 
744         assertFalse(mViewMediator.isShowingAndNotOccluded());
745     }
746 
747     @Test
748     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testKeyguardNotDelayedOnGoingToSleep_ifScreenOffAnimationWillNotPlay()749     public void testKeyguardNotDelayedOnGoingToSleep_ifScreenOffAnimationWillNotPlay() {
750         mViewMediator.onSystemReady();
751         TestableLooper.get(this).processAllMessages();
752 
753         mViewMediator.setShowingLocked(false);
754         TestableLooper.get(this).processAllMessages();
755 
756         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
757         TestableLooper.get(this).processAllMessages();
758 
759         when(mScreenOffAnimationController.shouldDelayKeyguardShow()).thenReturn(false);
760         mViewMediator.onFinishedGoingToSleep(OFF_BECAUSE_OF_USER, false);
761         TestableLooper.get(this).processAllMessages();
762 
763         assertTrue(mViewMediator.isShowingAndNotOccluded());
764     }
765 
766     @Test
testWakeAndUnlocking()767     public void testWakeAndUnlocking() {
768         mViewMediator.onWakeAndUnlocking(false);
769         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
770     }
771 
772     @Test
testWakeAndUnlockingOverDream()773     public void testWakeAndUnlockingOverDream() {
774         // Ensure ordering unlock and wake is enabled.
775         createAndStartViewMediator(true);
776 
777         // Send signal to wake
778         mViewMediator.onWakeAndUnlocking(true);
779 
780         // Ensure not woken up yet
781         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
782 
783         // Verify keyguard told of authentication
784         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
785         mViewMediator.mViewMediatorCallback.keyguardDonePending(true,
786                 mUpdateMonitor.getCurrentUser());
787         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
788         final ArgumentCaptor<Runnable> animationRunnableCaptor =
789                 ArgumentCaptor.forClass(Runnable.class);
790         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
791                 animationRunnableCaptor.capture());
792 
793         when(mStatusBarStateController.isDreaming()).thenReturn(true);
794         when(mStatusBarStateController.isDozing()).thenReturn(false);
795         animationRunnableCaptor.getValue().run();
796 
797         when(mKeyguardStateController.isShowing()).thenReturn(false);
798         mViewMediator.mViewMediatorCallback.keyguardGone();
799 
800         // Verify woken up now.
801         verify(mPowerManager).wakeUp(anyLong(), anyInt(), anyString());
802     }
803 
804     @Test
testWakeAndUnlockingOverDream_signalAuthenticateIfStillShowing()805     public void testWakeAndUnlockingOverDream_signalAuthenticateIfStillShowing() {
806         // Ensure ordering unlock and wake is enabled.
807         createAndStartViewMediator(true);
808 
809         // Send signal to wake
810         mViewMediator.onWakeAndUnlocking(true);
811 
812         // Ensure not woken up yet
813         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
814 
815         // Verify keyguard told of authentication
816         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
817         clearInvocations(mStatusBarKeyguardViewManager);
818         mViewMediator.mViewMediatorCallback.keyguardDonePending(true,
819                 mUpdateMonitor.getCurrentUser());
820         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
821         final ArgumentCaptor<Runnable> animationRunnableCaptor =
822                 ArgumentCaptor.forClass(Runnable.class);
823         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
824                 animationRunnableCaptor.capture());
825 
826         when(mStatusBarStateController.isDreaming()).thenReturn(true);
827         when(mStatusBarStateController.isDozing()).thenReturn(false);
828         animationRunnableCaptor.getValue().run();
829 
830         when(mKeyguardStateController.isShowing()).thenReturn(true);
831 
832         mViewMediator.mViewMediatorCallback.keyguardGone();
833 
834 
835         // Verify keyguard view controller informed of authentication again
836         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
837     }
838 
839     @Test
testWakeAndUnlockingOverNonInteractiveDream_noWakeByKeyguardViewMediator()840     public void testWakeAndUnlockingOverNonInteractiveDream_noWakeByKeyguardViewMediator() {
841         // Send signal to wake
842         mViewMediator.onWakeAndUnlocking(false);
843 
844         // Ensure not woken up yet
845         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
846 
847         // Verify keyguard told of authentication
848         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
849         mViewMediator.mViewMediatorCallback.keyguardDonePending(true,
850                 mUpdateMonitor.getCurrentUser());
851         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
852         final ArgumentCaptor<Runnable> animationRunnableCaptor =
853                 ArgumentCaptor.forClass(Runnable.class);
854         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
855                 animationRunnableCaptor.capture());
856 
857         when(mStatusBarStateController.isDreaming()).thenReturn(true);
858         when(mStatusBarStateController.isDozing()).thenReturn(false);
859         animationRunnableCaptor.getValue().run();
860 
861         when(mKeyguardStateController.isShowing()).thenReturn(false);
862         mViewMediator.mViewMediatorCallback.keyguardGone();
863 
864         // Verify not woken up.
865         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
866     }
867 
868     @Test
869     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testDoKeyguardWhileInteractive_resets()870     public void testDoKeyguardWhileInteractive_resets() {
871         mViewMediator.setShowingLocked(true);
872         when(mKeyguardStateController.isShowing()).thenReturn(true);
873         TestableLooper.get(this).processAllMessages();
874 
875         mViewMediator.onSystemReady();
876         TestableLooper.get(this).processAllMessages();
877 
878         assertTrue(mViewMediator.isShowingAndNotOccluded());
879         verify(mStatusBarKeyguardViewManager).reset(false);
880     }
881 
882     @Test
883     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testDoKeyguardWhileNotInteractive_showsInsteadOfResetting()884     public void testDoKeyguardWhileNotInteractive_showsInsteadOfResetting() {
885         mViewMediator.setShowingLocked(true);
886         when(mKeyguardStateController.isShowing()).thenReturn(true);
887         TestableLooper.get(this).processAllMessages();
888 
889         when(mPowerManager.isInteractive()).thenReturn(false);
890 
891         mViewMediator.onSystemReady();
892         TestableLooper.get(this).processAllMessages();
893 
894         assertTrue(mViewMediator.isShowingAndNotOccluded());
895         verify(mStatusBarKeyguardViewManager, never()).reset(anyBoolean());
896     }
897 
898     @Test
899     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testNotStartingKeyguardWhenFlagIsDisabled()900     public void testNotStartingKeyguardWhenFlagIsDisabled() {
901         mViewMediator.setShowingLocked(false);
902         when(mKeyguardStateController.isShowing()).thenReturn(false);
903 
904         mFeatureFlags.set(Flags.LOCKSCREEN_WITHOUT_SECURE_LOCK_WHEN_DREAMING, false);
905         mViewMediator.onDreamingStarted();
906         assertFalse(mViewMediator.isShowingAndNotOccluded());
907     }
908 
909     @Test
910     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testStartingKeyguardWhenFlagIsEnabled()911     public void testStartingKeyguardWhenFlagIsEnabled() {
912         mViewMediator.setShowingLocked(true);
913         when(mKeyguardStateController.isShowing()).thenReturn(true);
914 
915         mFeatureFlags.set(Flags.LOCKSCREEN_WITHOUT_SECURE_LOCK_WHEN_DREAMING, true);
916         mViewMediator.onDreamingStarted();
917         assertTrue(mViewMediator.isShowingAndNotOccluded());
918     }
919 
920     @Test
testOnStartedWakingUp_logsUiEvent()921     public void testOnStartedWakingUp_logsUiEvent() {
922         final InstanceId instanceId = InstanceId.fakeInstanceId(8);
923         when(mSessionTracker.getSessionId((anyInt()))).thenReturn(instanceId);
924         mViewMediator.onStartedWakingUp(PowerManager.WAKE_REASON_LIFT, false);
925 
926         verify(mUiEventLogger).logWithInstanceIdAndPosition(
927                 eq(BiometricUnlockController.BiometricUiEvent.STARTED_WAKING_UP),
928                 anyInt(),
929                 any(),
930                 eq(instanceId),
931                 eq(PowerManager.WAKE_REASON_LIFT)
932         );
933     }
934 
935     @Test
936     @TestableLooper.RunWithLooper(setAsMainLooper = true)
pendingPinLockOnKeyguardGoingAway_doKeyguardLockedOnKeyguardVisibilityChanged()937     public void pendingPinLockOnKeyguardGoingAway_doKeyguardLockedOnKeyguardVisibilityChanged() {
938         // GIVEN SIM_STATE_PIN_REQUIRED
939         mViewMediator.onSystemReady();
940         final KeyguardUpdateMonitorCallback keyguardUpdateMonitorCallback =
941                 mViewMediator.mUpdateCallback;
942         keyguardUpdateMonitorCallback.onSimStateChanged(0, 0,
943                 TelephonyManager.SIM_STATE_PIN_REQUIRED);
944         TestableLooper.get(this).processAllMessages();
945 
946         // ...and then the primary bouncer shows while the keyguard is going away
947         captureKeyguardStateControllerCallback();
948         when(mKeyguardStateController.isPrimaryBouncerShowing()).thenReturn(true);
949         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(true);
950         mKeyguardStateControllerCallback.getValue().onPrimaryBouncerShowingChanged();
951         TestableLooper.get(this).processAllMessages();
952 
953         // WHEN keyguard visibility becomes FALSE
954         mViewMediator.setShowingLocked(false);
955         keyguardUpdateMonitorCallback.onKeyguardVisibilityChanged(false);
956         TestableLooper.get(this).processAllMessages();
957 
958         // THEN keyguard shows due to the pending SIM PIN lock
959         assertTrue(mViewMediator.isShowingAndNotOccluded());
960     }
961 
962     @Test
testBouncerSwipeDown()963     public void testBouncerSwipeDown() {
964         mViewMediator.getViewMediatorCallback().onBouncerSwipeDown();
965         verify(mStatusBarKeyguardViewManager).reset(true);
966     }
createAndStartViewMediator()967     private void createAndStartViewMediator() {
968         createAndStartViewMediator(false);
969     }
970 
createAndStartViewMediator(boolean orderUnlockAndWake)971     private void createAndStartViewMediator(boolean orderUnlockAndWake) {
972         mContext.getOrCreateTestableResources().addOverride(
973                 com.android.internal.R.bool.config_orderUnlockAndWake, orderUnlockAndWake);
974 
975         mViewMediator = new KeyguardViewMediator(
976                 mContext,
977                 mUiEventLogger,
978                 mSessionTracker,
979                 mUserTracker,
980                 mFalsingCollector,
981                 mLockPatternUtils,
982                 mBroadcastDispatcher,
983                 () -> mStatusBarKeyguardViewManager,
984                 mDismissCallbackRegistry,
985                 mUpdateMonitor,
986                 mDumpManager,
987                 mUiBgExecutor,
988                 mPowerManager,
989                 mTrustManager,
990                 mUserSwitcherController,
991                 mDeviceConfig,
992                 mNavigationModeController,
993                 mKeyguardDisplayManager,
994                 mDozeParameters,
995                 mStatusBarStateController,
996                 mKeyguardStateController,
997                 () -> mKeyguardUnlockAnimationController,
998                 mScreenOffAnimationController,
999                 () -> mNotificationShadeDepthController,
1000                 mScreenOnCoordinator,
1001                 mKeyguardTransitions,
1002                 mInteractionJankMonitor,
1003                 mDreamOverlayStateController,
1004                 mJavaAdapter,
1005                 mWallpaperRepository,
1006                 () -> mShadeController,
1007                 () -> mNotificationShadeWindowController,
1008                 () -> mActivityLaunchAnimator,
1009                 () -> mScrimController,
1010                 mFeatureFlags,
1011                 mSecureSettings,
1012                 mSystemSettings,
1013                 mSystemClock,
1014                 mDispatcher,
1015                 () -> mDreamingToLockscreenTransitionViewModel,
1016                 mSystemPropertiesHelper,
1017                 () -> mock(WindowManagerLockscreenVisibilityManager.class));
1018         mViewMediator.start();
1019 
1020         mViewMediator.registerCentralSurfaces(mCentralSurfaces, null, null, null, null, null);
1021     }
1022 
captureKeyguardStateControllerCallback()1023     private void captureKeyguardStateControllerCallback() {
1024         verify(mKeyguardStateController).addCallback(mKeyguardStateControllerCallback.capture());
1025     }
1026 
captureKeyguardUpdateMonitorCallback()1027     private void captureKeyguardUpdateMonitorCallback() {
1028         verify(mUpdateMonitor).registerCallback(mKeyguardUpdateMonitorCallbackCaptor.capture());
1029     }
1030 }
1031