• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.provider.Settings.Secure.LOCK_SCREEN_LOCK_AFTER_TIMEOUT;
20 import static android.view.WindowManager.TRANSIT_OLD_KEYGUARD_GOING_AWAY;
21 import static android.view.WindowManagerPolicyConstants.OFF_BECAUSE_OF_TIMEOUT;
22 import static android.view.WindowManagerPolicyConstants.OFF_BECAUSE_OF_USER;
23 
24 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST;
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.Flags.FLAG_KEYGUARD_WM_STATE_REFACTOR;
29 import static com.android.systemui.Flags.FLAG_RELOCK_WITH_POWER_BUTTON_IMMEDIATELY;
30 import static com.android.systemui.Flags.FLAG_SIM_PIN_BOUNCER_RESET;
31 import static com.android.systemui.keyguard.KeyguardViewMediator.DELAYED_KEYGUARD_ACTION;
32 import static com.android.systemui.keyguard.KeyguardViewMediator.KEYGUARD_LOCK_AFTER_DELAY_DEFAULT;
33 import static com.android.systemui.keyguard.KeyguardViewMediator.REBOOT_MAINLINE_UPDATE;
34 import static com.android.systemui.keyguard.KeyguardViewMediator.SYS_BOOT_REASON_PROP;
35 
36 import static org.junit.Assert.assertEquals;
37 import static org.junit.Assert.assertFalse;
38 import static org.junit.Assert.assertTrue;
39 import static org.junit.Assert.fail;
40 import static org.mockito.ArgumentMatchers.any;
41 import static org.mockito.ArgumentMatchers.anyBoolean;
42 import static org.mockito.ArgumentMatchers.anyInt;
43 import static org.mockito.ArgumentMatchers.anyLong;
44 import static org.mockito.ArgumentMatchers.anyString;
45 import static org.mockito.Mockito.atLeast;
46 import static org.mockito.Mockito.atLeastOnce;
47 import static org.mockito.Mockito.clearInvocations;
48 import static org.mockito.Mockito.doAnswer;
49 import static org.mockito.Mockito.eq;
50 import static org.mockito.Mockito.inOrder;
51 import static org.mockito.Mockito.mock;
52 import static org.mockito.Mockito.never;
53 import static org.mockito.Mockito.reset;
54 import static org.mockito.Mockito.verify;
55 import static org.mockito.Mockito.when;
56 
57 import android.app.AlarmManager;
58 import android.app.IActivityManager;
59 import android.app.IActivityTaskManager;
60 import android.app.PendingIntent;
61 import android.app.admin.DevicePolicyManager;
62 import android.app.trust.TrustManager;
63 import android.content.Context;
64 import android.os.PowerManager;
65 import android.os.PowerManager.WakeLock;
66 import android.os.RemoteException;
67 import android.platform.test.annotations.DisableFlags;
68 import android.platform.test.annotations.EnableFlags;
69 import android.telephony.TelephonyManager;
70 import android.testing.AndroidTestingRunner;
71 import android.testing.TestableLooper;
72 import android.view.IRemoteAnimationFinishedCallback;
73 import android.view.RemoteAnimationTarget;
74 import android.view.View;
75 import android.view.ViewRootImpl;
76 import android.view.WindowManager;
77 
78 import androidx.test.filters.SmallTest;
79 
80 import com.android.internal.foldables.FoldGracePeriodProvider;
81 import com.android.internal.logging.InstanceId;
82 import com.android.internal.logging.UiEventLogger;
83 import com.android.internal.statusbar.IStatusBarService;
84 import com.android.internal.widget.LockPatternUtils;
85 import com.android.keyguard.KeyguardDisplayManager;
86 import com.android.keyguard.KeyguardSecurityView;
87 import com.android.keyguard.KeyguardUpdateMonitor;
88 import com.android.keyguard.KeyguardUpdateMonitorCallback;
89 import com.android.keyguard.TestScopeProvider;
90 import com.android.keyguard.mediator.ScreenOnCoordinator;
91 import com.android.systemui.DejankUtils;
92 import com.android.systemui.SysuiTestCase;
93 import com.android.systemui.animation.ActivityTransitionAnimator;
94 import com.android.systemui.biometrics.AuthController;
95 import com.android.systemui.broadcast.BroadcastDispatcher;
96 import com.android.systemui.classifier.FalsingCollectorFake;
97 import com.android.systemui.colorextraction.SysuiColorExtractor;
98 import com.android.systemui.communal.ui.viewmodel.CommunalTransitionViewModel;
99 import com.android.systemui.dreams.DreamOverlayStateController;
100 import com.android.systemui.dreams.ui.viewmodel.DreamViewModel;
101 import com.android.systemui.dump.DumpManager;
102 import com.android.systemui.flags.FakeFeatureFlags;
103 import com.android.systemui.flags.SystemPropertiesHelper;
104 import com.android.systemui.keyguard.domain.interactor.KeyguardTransitionBootInteractor;
105 import com.android.systemui.kosmos.KosmosJavaAdapter;
106 import com.android.systemui.log.SessionTracker;
107 import com.android.systemui.navigationbar.NavigationModeController;
108 import com.android.systemui.process.ProcessWrapper;
109 import com.android.systemui.scene.FakeWindowRootViewComponent;
110 import com.android.systemui.scene.ui.view.WindowRootView;
111 import com.android.systemui.settings.UserTracker;
112 import com.android.systemui.shade.NotificationShadeWindowControllerImpl;
113 import com.android.systemui.shade.ShadeController;
114 import com.android.systemui.shade.ShadeExpansionStateManager;
115 import com.android.systemui.shade.ShadeWindowLogger;
116 import com.android.systemui.shade.domain.interactor.ShadeInteractor;
117 import com.android.systemui.statusbar.NotificationShadeDepthController;
118 import com.android.systemui.statusbar.NotificationShadeWindowController;
119 import com.android.systemui.statusbar.SysuiStatusBarStateController;
120 import com.android.systemui.statusbar.phone.BiometricUnlockController;
121 import com.android.systemui.statusbar.phone.CentralSurfaces;
122 import com.android.systemui.statusbar.phone.DozeParameters;
123 import com.android.systemui.statusbar.phone.KeyguardBypassController;
124 import com.android.systemui.statusbar.phone.ScreenOffAnimationController;
125 import com.android.systemui.statusbar.phone.ScrimController;
126 import com.android.systemui.statusbar.phone.StatusBarKeyguardViewManager;
127 import com.android.systemui.statusbar.policy.ConfigurationController;
128 import com.android.systemui.statusbar.policy.KeyguardStateController;
129 import com.android.systemui.statusbar.policy.UserSwitcherController;
130 import com.android.systemui.user.domain.interactor.SelectedUserInteractor;
131 import com.android.systemui.util.DeviceConfigProxy;
132 import com.android.systemui.util.DeviceConfigProxyFake;
133 import com.android.systemui.util.concurrency.FakeExecutor;
134 import com.android.systemui.util.kotlin.JavaAdapter;
135 import com.android.systemui.util.settings.SecureSettings;
136 import com.android.systemui.util.settings.SystemSettings;
137 import com.android.systemui.util.time.FakeSystemClock;
138 import com.android.systemui.wallpapers.data.repository.FakeWallpaperRepository;
139 import com.android.window.flags.Flags;
140 import com.android.wm.shell.keyguard.KeyguardTransitions;
141 
142 import kotlinx.coroutines.CoroutineDispatcher;
143 import kotlinx.coroutines.flow.Flow;
144 import kotlinx.coroutines.test.TestScope;
145 
146 import org.junit.After;
147 import org.junit.Before;
148 import org.junit.Test;
149 import org.junit.runner.RunWith;
150 import org.mockito.ArgumentCaptor;
151 import org.mockito.Captor;
152 import org.mockito.InOrder;
153 import org.mockito.Mock;
154 import org.mockito.MockitoAnnotations;
155 
156 @RunWith(AndroidTestingRunner.class)
157 @TestableLooper.RunWithLooper
158 @SmallTest
159 public class KeyguardViewMediatorTest extends SysuiTestCase {
160 
161     private static final boolean ENABLE_NEW_KEYGUARD_SHELL_TRANSITIONS =
162             Flags.ensureKeyguardDoesTransitionStarting();
163 
164     private final KosmosJavaAdapter mKosmos = new KosmosJavaAdapter(this);
165     private KeyguardViewMediator mViewMediator;
166 
167     private final TestScope mTestScope = TestScopeProvider.getTestScope();
168     private final JavaAdapter mJavaAdapter = new JavaAdapter(mTestScope.getBackgroundScope());
169 
170     private @Mock UserTracker mUserTracker;
171     private @Mock DevicePolicyManager mDevicePolicyManager;
172     private @Mock LockPatternUtils mLockPatternUtils;
173     private @Mock KeyguardUpdateMonitor mUpdateMonitor;
174     private @Mock StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
175     private @Mock BroadcastDispatcher mBroadcastDispatcher;
176     private @Mock DismissCallbackRegistry mDismissCallbackRegistry;
177     private @Mock DumpManager mDumpManager;
178     private @Mock WindowManager mWindowManager;
179     private @Mock IActivityManager mActivityManager;
180     private @Mock ConfigurationController mConfigurationController;
181     private @Mock PowerManager mPowerManager;
182     private @Mock TrustManager mTrustManager;
183     private @Mock UserSwitcherController mUserSwitcherController;
184     private @Mock NavigationModeController mNavigationModeController;
185     private @Mock KeyguardDisplayManager mKeyguardDisplayManager;
186     private @Mock KeyguardBypassController mKeyguardBypassController;
187     private @Mock DozeParameters mDozeParameters;
188     private @Mock SysuiStatusBarStateController mStatusBarStateController;
189     private @Mock KeyguardStateController mKeyguardStateController;
190     private @Mock NotificationShadeDepthController mNotificationShadeDepthController;
191     private @Mock KeyguardUnlockAnimationController mKeyguardUnlockAnimationController;
192     private @Mock ScreenOffAnimationController mScreenOffAnimationController;
193     private @Mock ScreenOnCoordinator mScreenOnCoordinator;
194     private @Mock KeyguardTransitions mKeyguardTransitions;
195     private @Mock ShadeController mShadeController;
196     private NotificationShadeWindowController mNotificationShadeWindowController;
197     private @Mock DreamOverlayStateController mDreamOverlayStateController;
198     private @Mock ActivityTransitionAnimator mActivityTransitionAnimator;
199     private @Mock ScrimController mScrimController;
200     private @Mock IActivityTaskManager mActivityTaskManagerService;
201     private @Mock IStatusBarService mStatusBarService;
202     private @Mock SysuiColorExtractor mColorExtractor;
203     private @Mock AuthController mAuthController;
204     private @Mock ShadeExpansionStateManager mShadeExpansionStateManager;
205     private @Mock ShadeInteractor mShadeInteractor;
206     private @Mock ShadeWindowLogger mShadeWindowLogger;
207     private @Mock SelectedUserInteractor mSelectedUserInteractor;
208     private @Mock UserTracker.Callback mUserTrackerCallback;
209     private @Mock KeyguardTransitionBootInteractor mKeyguardTransitionBootInteractor;
210     private @Captor ArgumentCaptor<KeyguardStateController.Callback>
211             mKeyguardStateControllerCallback;
212     private @Captor ArgumentCaptor<KeyguardUpdateMonitorCallback>
213             mKeyguardUpdateMonitorCallbackCaptor;
214     private DeviceConfigProxy mDeviceConfig = new DeviceConfigProxyFake();
215     private FakeExecutor mUiMainExecutor = new FakeExecutor(new FakeSystemClock());
216     private FakeExecutor mUiBgExecutor = new FakeExecutor(new FakeSystemClock());
217 
218     private FalsingCollectorFake mFalsingCollector;
219 
220     private @Mock CentralSurfaces mCentralSurfaces;
221     private @Mock UiEventLogger mUiEventLogger;
222     private @Mock SessionTracker mSessionTracker;
223     private @Mock SystemSettings mSystemSettings;
224     private @Mock SecureSettings mSecureSettings;
225     private @Mock AlarmManager mAlarmManager;
226     private @Mock ProcessWrapper mProcessWrapper;
227     private FakeSystemClock mSystemClock;
228     private final FakeWallpaperRepository mWallpaperRepository = new FakeWallpaperRepository();
229 
230     /** Most recent value passed to {@link KeyguardStateController#notifyKeyguardGoingAway}. */
231     private boolean mKeyguardGoingAway = false;
232 
233     private @Mock CoroutineDispatcher mDispatcher;
234     private @Mock DreamViewModel mDreamViewModel;
235     private @Mock CommunalTransitionViewModel mCommunalTransitionViewModel;
236     private @Mock SystemPropertiesHelper mSystemPropertiesHelper;
237 
238     private FakeFeatureFlags mFeatureFlags;
239     private final int mDefaultUserId = 100;
240 
241     @Before
setUp()242     public void setUp() throws Exception {
243         MockitoAnnotations.initMocks(this);
244         mFalsingCollector = new FalsingCollectorFake();
245         mSystemClock = new FakeSystemClock();
246         when(mLockPatternUtils.getDevicePolicyManager()).thenReturn(mDevicePolicyManager);
247         when(mPowerManager.newWakeLock(anyInt(), any())).thenReturn(mock(WakeLock.class));
248         when(mPowerManager.isInteractive()).thenReturn(true);
249         mContext.addMockSystemService(Context.ALARM_SERVICE, mAlarmManager);
250         final ViewRootImpl testViewRoot = mock(ViewRootImpl.class);
251         when(testViewRoot.getView()).thenReturn(mock(View.class));
252         when(mStatusBarKeyguardViewManager.getViewRootImpl()).thenReturn(testViewRoot);
253         when(mDreamViewModel.getDreamAlpha())
254                 .thenReturn(mock(Flow.class));
255         when(mDreamViewModel.getTransitionEnded())
256                 .thenReturn(mock(Flow.class));
257         when(mCommunalTransitionViewModel.getShowCommunalFromOccluded())
258                 .thenReturn(mock(Flow.class));
259         when(mCommunalTransitionViewModel.getTransitionFromOccludedEnded())
260                 .thenReturn(mock(Flow.class));
261         when(mSelectedUserInteractor.getSelectedUserId()).thenReturn(mDefaultUserId);
262         when(mProcessWrapper.isSystemUser()).thenReturn(true);
263         mNotificationShadeWindowController = new NotificationShadeWindowControllerImpl(
264                 mContext,
265                 new FakeWindowRootViewComponent.Factory(mock(WindowRootView.class)),
266                 mWindowManager,
267                 mActivityManager,
268                 mDozeParameters,
269                 mStatusBarStateController,
270                 mConfigurationController,
271                 mViewMediator,
272                 mKeyguardBypassController,
273                 mUiMainExecutor,
274                 mUiBgExecutor,
275                 mColorExtractor,
276                 mDumpManager,
277                 mKeyguardStateController,
278                 mAuthController,
279                 () -> mShadeInteractor,
280                 mShadeWindowLogger,
281                 () -> mSelectedUserInteractor,
282                 mock(UserTracker.class),
283                 mKosmos.getNotificationShadeWindowModel(),
284                 mKosmos::getCommunalInteractor,
285                 mKosmos.getShadeLayoutParams());
286         mFeatureFlags = new FakeFeatureFlags();
287         mSetFlagsRule.disableFlags(FLAG_KEYGUARD_WM_STATE_REFACTOR);
288 
289         DejankUtils.setImmediate(true);
290 
291         // Keep track of what we told KeyguardStateController about whether we're going away or
292         // not.
293         mKeyguardGoingAway = false;
294         doAnswer(invocation -> {
295             mKeyguardGoingAway = invocation.getArgument(0);
296             return null;
297         }).when(mKeyguardStateController).notifyKeyguardGoingAway(anyBoolean());
298 
299         createAndStartViewMediator();
300     }
301 
302     /**
303      * After each test, verify that System UI's going away/showing state matches the most recent
304      * calls we made to ATMS.
305      *
306      * This will help us catch showing and going away state mismatch issues.
307      */
308     @After
assertATMSAndKeyguardViewMediatorStatesMatch()309     public void assertATMSAndKeyguardViewMediatorStatesMatch() {
310         try {
311             if (mKeyguardGoingAway) {
312                 assertATMSKeyguardGoingAway();
313             } else {
314                 assertATMSLockScreenShowing(mViewMediator.isShowing());
315             }
316 
317         } catch (Exception e) {
318             // Just so we don't have to add the exception signature to every test.
319             fail(e.getMessage());
320         }
321     }
322 
323     @Test
324     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testHandleSystemReadyWhileUserIsSwitching()325     public void testHandleSystemReadyWhileUserIsSwitching() {
326         int userId = 1099;
327         when(mUserTracker.getUserId()).thenReturn(userId);
328 
329         /* First test the default behavior: handleUserSwitching() is not invoked */
330         when(mUserTracker.isUserSwitching()).thenReturn(false);
331         mViewMediator.onSystemReady();
332         TestableLooper.get(this).processAllMessages();
333 
334         verify(mUserTrackerCallback, never()).onUserChanging(eq(userId), eq(mContext),
335                 any(Runnable.class));
336 
337         /* Next test user switching is already in progress when started */
338         when(mUserTracker.isUserSwitching()).thenReturn(true);
339         mViewMediator.onSystemReady();
340         TestableLooper.get(this).processAllMessages();
341 
342         verify(mUserTrackerCallback).onUserChanging(eq(userId), eq(mContext),
343                 any(Runnable.class));
344     }
345 
346     @Test
347     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testGoingAwayFollowedByBeforeUserSwitchDoesNotHideKeyguard()348     public void testGoingAwayFollowedByBeforeUserSwitchDoesNotHideKeyguard() {
349         setCurrentUser(/* userId= */1099, /* isSecure= */false);
350 
351         // Setup keyguard
352         mViewMediator.onSystemReady();
353         processAllMessagesAndBgExecutorMessages();
354         mViewMediator.setShowingLocked(true, "");
355 
356         // Request keyguard going away
357         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(true);
358         mViewMediator.mKeyguardGoingAwayRunnable.run();
359 
360         // After the request, begin a switch to a new secure user
361         int nextUserId = 500;
362         setCurrentUser(nextUserId, /* isSecure= */true);
363         Runnable result = mock(Runnable.class);
364         mViewMediator.handleBeforeUserSwitching(nextUserId, result);
365         processAllMessagesAndBgExecutorMessages();
366         verify(result).run();
367 
368         // After that request has begun, have WM tell us to exit keyguard
369         RemoteAnimationTarget[] apps = new RemoteAnimationTarget[]{
370                 mock(RemoteAnimationTarget.class)
371         };
372         RemoteAnimationTarget[] wallpapers = new RemoteAnimationTarget[]{
373                 mock(RemoteAnimationTarget.class)
374         };
375         IRemoteAnimationFinishedCallback callback = mock(IRemoteAnimationFinishedCallback.class);
376         mViewMediator.startKeyguardExitAnimation(TRANSIT_OLD_KEYGUARD_GOING_AWAY, apps, wallpapers,
377                 null, callback);
378         processAllMessagesAndBgExecutorMessages();
379 
380         // The call to exit should be rejected, and keyguard should still be visible
381         verify(mKeyguardUnlockAnimationController, never()).notifyStartSurfaceBehindRemoteAnimation(
382                 any(), any(), any(), anyLong(), anyBoolean());
383         try {
384             assertATMSLockScreenShowing(true);
385         } catch (Exception e) {
386             fail(e.getMessage());
387         }
388         assertTrue(mViewMediator.isShowingAndNotOccluded());
389     }
390 
391     @Test
392     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testUserSwitchToSecureUserShowsBouncer()393     public void testUserSwitchToSecureUserShowsBouncer() {
394         setCurrentUser(/* userId= */1099, /* isSecure= */true);
395 
396         // Setup keyguard
397         mViewMediator.onSystemReady();
398         processAllMessagesAndBgExecutorMessages();
399         mViewMediator.setShowingLocked(true, "");
400 
401         // After the request, begin a switch to a new secure user
402         int nextUserId = 500;
403         setCurrentUser(nextUserId, /* isSecure= */true);
404 
405         Runnable beforeResult = mock(Runnable.class);
406         mViewMediator.handleBeforeUserSwitching(nextUserId, beforeResult);
407         processAllMessagesAndBgExecutorMessages();
408         verify(beforeResult).run();
409 
410         // Dismiss should not be called while user switch is in progress
411         Runnable onSwitchResult = mock(Runnable.class);
412         mViewMediator.handleUserSwitching(nextUserId, onSwitchResult);
413         processAllMessagesAndBgExecutorMessages();
414         verify(onSwitchResult).run();
415         verify(mStatusBarKeyguardViewManager, never()).dismissAndCollapse();
416 
417         // The attempt to dismiss only comes on user switch complete, which will trigger a call to
418         // show the bouncer in StatusBarKeyguardViewManager
419         mViewMediator.handleUserSwitchComplete(nextUserId);
420         TestableLooper.get(this).moveTimeForward(600);
421         processAllMessagesAndBgExecutorMessages();
422 
423         verify(mStatusBarKeyguardViewManager).dismissAndCollapse();
424     }
425 
426     @Test
427     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testUserSwitchToInsecureUserDismissesKeyguard()428     public void testUserSwitchToInsecureUserDismissesKeyguard() {
429         int userId = 1099;
430         when(mUserTracker.getUserId()).thenReturn(userId);
431 
432         // Setup keyguard
433         mViewMediator.onSystemReady();
434         processAllMessagesAndBgExecutorMessages();
435         mViewMediator.setShowingLocked(true, "");
436 
437         // After the request, begin a switch to an insecure user
438         int nextUserId = 500;
439         when(mLockPatternUtils.isSecure(nextUserId)).thenReturn(false);
440 
441         Runnable beforeResult = mock(Runnable.class);
442         mViewMediator.handleBeforeUserSwitching(nextUserId, beforeResult);
443         processAllMessagesAndBgExecutorMessages();
444         verify(beforeResult).run();
445 
446         // The call to dismiss comes during the user switch
447         Runnable onSwitchResult = mock(Runnable.class);
448         mViewMediator.handleUserSwitching(nextUserId, onSwitchResult);
449         processAllMessagesAndBgExecutorMessages();
450         verify(onSwitchResult).run();
451 
452         verify(mStatusBarKeyguardViewManager).dismissAndCollapse();
453     }
454 
455     @Test
456     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testUserSwitchToSecureUserWhileKeyguardNotVisibleShowsKeyguard()457     public void testUserSwitchToSecureUserWhileKeyguardNotVisibleShowsKeyguard() {
458         setCurrentUser(/* userId= */1099, /* isSecure= */true);
459 
460         // Setup keyguard as not visible
461         mViewMediator.onSystemReady();
462         processAllMessagesAndBgExecutorMessages();
463         mViewMediator.setShowingLocked(false, "");
464         processAllMessagesAndBgExecutorMessages();
465 
466         // Begin a switch to a new secure user
467         int nextUserId = 500;
468         setCurrentUser(nextUserId, /* isSecure= */true);
469 
470         Runnable beforeResult = mock(Runnable.class);
471         mViewMediator.handleBeforeUserSwitching(nextUserId, beforeResult);
472         processAllMessagesAndBgExecutorMessages();
473         verify(beforeResult).run();
474 
475         try {
476             assertATMSLockScreenShowing(true);
477         } catch (Exception e) {
478             fail();
479         }
480         assertTrue(mViewMediator.isShowingAndNotOccluded());
481     }
482 
483     @Test
484     @TestableLooper.RunWithLooper(setAsMainLooper = true)
onLockdown_showKeyguard_evenIfKeyguardIsNotEnabledExternally()485     public void onLockdown_showKeyguard_evenIfKeyguardIsNotEnabledExternally() {
486         // GIVEN keyguard is not enabled and isn't showing
487         mViewMediator.onSystemReady();
488         mViewMediator.setKeyguardEnabled(false);
489         TestableLooper.get(this).processAllMessages();
490         captureKeyguardUpdateMonitorCallback();
491         assertFalse(mViewMediator.isShowingAndNotOccluded());
492 
493         // WHEN lockdown occurs
494         when(mLockPatternUtils.isUserInLockdown(anyInt())).thenReturn(true);
495         mKeyguardUpdateMonitorCallbackCaptor.getValue().onStrongAuthStateChanged(0);
496 
497         // THEN keyguard is shown
498         TestableLooper.get(this).processAllMessages();
499         assertTrue(mViewMediator.isShowingAndNotOccluded());
500     }
501 
502     @Test
503     @TestableLooper.RunWithLooper(setAsMainLooper = true)
showKeyguardAfterKeyguardNotEnabled()504     public void showKeyguardAfterKeyguardNotEnabled() {
505         // GIVEN feature is enabled
506         final FoldGracePeriodProvider mockedFoldGracePeriodProvider =
507                 mock(FoldGracePeriodProvider.class);
508         mViewMediator.mFoldGracePeriodProvider = mockedFoldGracePeriodProvider;
509         when(mockedFoldGracePeriodProvider.isEnabled()).thenReturn(true);
510         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(true);
511 
512         // GIVEN keyguard is not enabled and isn't showing
513         mViewMediator.onSystemReady();
514         mViewMediator.setKeyguardEnabled(false);
515         TestableLooper.get(this).processAllMessages();
516         captureKeyguardUpdateMonitorCallback();
517         assertFalse(mViewMediator.isShowingAndNotOccluded());
518 
519         // WHEN showKeyguard is requested
520         mViewMediator.showDismissibleKeyguard();
521 
522         // THEN keyguard is shown
523         TestableLooper.get(this).processAllMessages();
524         assertTrue(mViewMediator.isShowingAndNotOccluded());
525     }
526 
527     @Test
528     @TestableLooper.RunWithLooper(setAsMainLooper = true)
doNotShowKeyguard_deviceNotProvisioned()529     public void doNotShowKeyguard_deviceNotProvisioned() {
530         // GIVEN feature is enabled
531         final FoldGracePeriodProvider mockedFoldGracePeriodProvider =
532                 mock(FoldGracePeriodProvider.class);
533         mViewMediator.mFoldGracePeriodProvider = mockedFoldGracePeriodProvider;
534         when(mockedFoldGracePeriodProvider.isEnabled()).thenReturn(true);
535 
536         // GIVEN keyguard is not enabled and isn't showing
537         mViewMediator.onSystemReady();
538         mViewMediator.setKeyguardEnabled(false);
539         TestableLooper.get(this).processAllMessages();
540         captureKeyguardUpdateMonitorCallback();
541         assertFalse(mViewMediator.isShowingAndNotOccluded());
542 
543         // WHEN device is NOT provisioned
544         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(false);
545 
546         // WHEN showKeyguard is requested
547         mViewMediator.showDismissibleKeyguard();
548 
549         // THEN keyguard is NOT shown
550         TestableLooper.get(this).processAllMessages();
551         assertFalse(mViewMediator.isShowingAndNotOccluded());
552     }
553 
554     @Test
555     @TestableLooper.RunWithLooper(setAsMainLooper = true)
showKeyguardAfterKeyguardNotEnabled_featureNotEnabled()556     public void showKeyguardAfterKeyguardNotEnabled_featureNotEnabled() {
557         // GIVEN feature is NOT enabled
558         final FoldGracePeriodProvider mockedFoldGracePeriodProvider =
559                 mock(FoldGracePeriodProvider.class);
560         mViewMediator.mFoldGracePeriodProvider = mockedFoldGracePeriodProvider;
561         when(mockedFoldGracePeriodProvider.isEnabled()).thenReturn(false);
562         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(true);
563 
564         // GIVEN keyguard is not enabled and isn't showing
565         mViewMediator.onSystemReady();
566         mViewMediator.setKeyguardEnabled(false);
567         TestableLooper.get(this).processAllMessages();
568         captureKeyguardUpdateMonitorCallback();
569         assertFalse(mViewMediator.isShowingAndNotOccluded());
570 
571         // WHEN showKeyguard is requested
572         mViewMediator.showDismissibleKeyguard();
573 
574         // THEN keyguard is still NOT shown
575         TestableLooper.get(this).processAllMessages();
576         assertFalse(mViewMediator.isShowingAndNotOccluded());
577     }
578 
579     @Test
580     @TestableLooper.RunWithLooper(setAsMainLooper = true)
doNotHideKeyguard_whenLockdown_onKeyguardNotEnabledExternally()581     public void doNotHideKeyguard_whenLockdown_onKeyguardNotEnabledExternally() {
582         // GIVEN keyguard is enabled and lockdown occurred so the keyguard is showing
583         mViewMediator.onSystemReady();
584         mViewMediator.setKeyguardEnabled(true);
585         TestableLooper.get(this).processAllMessages();
586         captureKeyguardUpdateMonitorCallback();
587         when(mLockPatternUtils.isUserInLockdown(anyInt())).thenReturn(true);
588         mKeyguardUpdateMonitorCallbackCaptor.getValue().onStrongAuthStateChanged(0);
589         assertTrue(mViewMediator.isShowingAndNotOccluded());
590 
591         // WHEN keyguard is externally not enabled anymore
592         mViewMediator.setKeyguardEnabled(false);
593 
594         // THEN keyguard is NOT dismissed; it continues to show
595         TestableLooper.get(this).processAllMessages();
596         assertTrue(mViewMediator.isShowingAndNotOccluded());
597     }
598 
599     @Test
testOnGoingToSleep_UpdatesKeyguardGoingAway()600     public void testOnGoingToSleep_UpdatesKeyguardGoingAway() {
601         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
602         verify(mUpdateMonitor).dispatchKeyguardGoingAway(false);
603         verify(mStatusBarKeyguardViewManager, never()).setKeyguardGoingAwayState(anyBoolean());
604     }
605 
606     @Test
607     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testOnStartedWakingUp_whileSleeping_ifWakeAndUnlocking_doesNotShowKeyguard()608     public void testOnStartedWakingUp_whileSleeping_ifWakeAndUnlocking_doesNotShowKeyguard() {
609         when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
610         when(mLockPatternUtils.getPowerButtonInstantlyLocks(anyInt())).thenReturn(true);
611         mViewMediator.onSystemReady();
612         TestableLooper.get(this).processAllMessages();
613 
614         mViewMediator.setShowingLocked(false, "");
615         TestableLooper.get(this).processAllMessages();
616 
617         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
618         mViewMediator.onWakeAndUnlocking(false);
619         mViewMediator.onStartedWakingUp(OFF_BECAUSE_OF_USER, false);
620         TestableLooper.get(this).processAllMessages();
621 
622         assertFalse(mViewMediator.isShowingAndNotOccluded());
623         verify(mKeyguardStateController, never()).notifyKeyguardState(eq(true), anyBoolean());
624     }
625 
626     @Test
627     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testOnStartedWakingUp_whileSleeping_ifNotWakeAndUnlocking_showsKeyguard()628     public void testOnStartedWakingUp_whileSleeping_ifNotWakeAndUnlocking_showsKeyguard() {
629         when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
630         when(mLockPatternUtils.getPowerButtonInstantlyLocks(anyInt())).thenReturn(true);
631         mViewMediator.onSystemReady();
632         TestableLooper.get(this).processAllMessages();
633 
634         mViewMediator.setShowingLocked(false, "");
635         TestableLooper.get(this).processAllMessages();
636 
637         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
638         mViewMediator.onStartedWakingUp(OFF_BECAUSE_OF_USER, false);
639 
640         TestableLooper.get(this).processAllMessages();
641 
642         assertTrue(mViewMediator.isShowingAndNotOccluded());
643     }
644 
645     @Test
testRegisterDumpable()646     public void testRegisterDumpable() {
647         verify(mDumpManager).registerDumpable(mViewMediator);
648         verify(mStatusBarKeyguardViewManager, never()).setKeyguardGoingAwayState(anyBoolean());
649     }
650 
651     @Test
testKeyguardGone_notGoingaway()652     public void testKeyguardGone_notGoingaway() {
653         mViewMediator.mViewMediatorCallback.keyguardGone();
654         verify(mStatusBarKeyguardViewManager).setKeyguardGoingAwayState(eq(false));
655     }
656 
657     @Test
testIsAnimatingScreenOff()658     public void testIsAnimatingScreenOff() {
659         when(mDozeParameters.shouldControlUnlockedScreenOff()).thenReturn(true);
660         when(mDozeParameters.shouldAnimateDozingChange()).thenReturn(true);
661 
662         mViewMediator.onFinishedGoingToSleep(OFF_BECAUSE_OF_USER, false);
663         mViewMediator.setDozing(true);
664 
665         // Mid-doze, we should be animating the screen off animation.
666         mViewMediator.onDozeAmountChanged(0.5f, 0.5f);
667         assertTrue(mViewMediator.isAnimatingScreenOff());
668 
669         // Once we're 100% dozed, the screen off animation should be completed.
670         mViewMediator.onDozeAmountChanged(1f, 1f);
671         assertFalse(mViewMediator.isAnimatingScreenOff());
672     }
673 
674     @Test
675     @TestableLooper.RunWithLooper(setAsMainLooper = true)
wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOff()676     public void wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOff() {
677         createAndStartViewMediator(false);
678 
679         mViewMediator.onSystemReady();
680         TestableLooper.get(this).processAllMessages();
681 
682         // Given device is dreaming
683         when(mUpdateMonitor.isDreaming()).thenReturn(true);
684 
685         // When keyguard is going away
686         mKeyguardStateController.notifyKeyguardGoingAway(true);
687 
688         // And keyguard is disabled which will call #handleHide
689         mViewMediator.setKeyguardEnabled(false);
690         TestableLooper.get(this).processAllMessages();
691 
692         // Then dream should wake up
693         verify(mPowerManager).wakeUp(anyLong(), anyInt(),
694                 eq("com.android.systemui:UNLOCK_DREAMING"));
695     }
696 
697     @Test
698     @TestableLooper.RunWithLooper(setAsMainLooper = true)
wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOn()699     public void wakeupFromDreamingWhenKeyguardHides_orderUnlockAndWakeOn() {
700         createAndStartViewMediator(true);
701 
702         mViewMediator.onSystemReady();
703         TestableLooper.get(this).processAllMessages();
704         when(mPowerManager.isInteractive()).thenReturn(true);
705 
706         // Given device is dreaming
707         when(mUpdateMonitor.isDreaming()).thenReturn(true);
708 
709         // When keyguard is going away
710         mKeyguardStateController.notifyKeyguardGoingAway(true);
711 
712         // And keyguard is disabled which will call #handleHide
713         mViewMediator.setKeyguardEnabled(false);
714         TestableLooper.get(this).processAllMessages();
715 
716         mViewMediator.mViewMediatorCallback.keyguardDonePending(mDefaultUserId);
717         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
718         final ArgumentCaptor<Runnable> animationRunnableCaptor =
719                 ArgumentCaptor.forClass(Runnable.class);
720         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
721                 animationRunnableCaptor.capture());
722 
723         when(mStatusBarStateController.isDreaming()).thenReturn(true);
724         when(mStatusBarStateController.isDozing()).thenReturn(false);
725         animationRunnableCaptor.getValue().run();
726 
727         when(mKeyguardStateController.isShowing()).thenReturn(false);
728         mViewMediator.mViewMediatorCallback.keyguardGone();
729 
730         // Then dream should wake up
731         verify(mPowerManager).wakeUp(anyLong(), anyInt(),
732                 eq("com.android.systemui:UNLOCK_DREAMING"));
733     }
734 
735     @Test
736     @TestableLooper.RunWithLooper(setAsMainLooper = true)
restoreBouncerWhenSimLockedAndKeyguardIsGoingAway()737     public void restoreBouncerWhenSimLockedAndKeyguardIsGoingAway() {
738         // When showing and provisioned
739         mViewMediator.onSystemReady();
740         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(true);
741         mViewMediator.setShowingLocked(true, "");
742 
743         // and a SIM becomes locked and requires a PIN
744         mViewMediator.mUpdateCallback.onSimStateChanged(
745                 1 /* subId */,
746                 0 /* slotId */,
747                 TelephonyManager.SIM_STATE_PIN_REQUIRED);
748 
749         // and the keyguard goes away
750         mViewMediator.setShowingLocked(false, "");
751         when(mKeyguardStateController.isShowing()).thenReturn(false);
752         mViewMediator.mUpdateCallback.onKeyguardVisibilityChanged(false);
753 
754         TestableLooper.get(this).processAllMessages();
755 
756         // then make sure it comes back
757         verify(mStatusBarKeyguardViewManager, atLeast(1)).show(null);
758     }
759 
760     @Test
761     @TestableLooper.RunWithLooper(setAsMainLooper = true)
762     @EnableFlags(FLAG_SIM_PIN_BOUNCER_RESET)
resetStateLocked_whenSimNotReadyAndWasLockedPrior()763     public void resetStateLocked_whenSimNotReadyAndWasLockedPrior() {
764         // When showing and provisioned
765         mViewMediator.onSystemReady();
766         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(true);
767         mViewMediator.setShowingLocked(true, "");
768 
769         // and a SIM becomes locked and requires a PIN
770         mViewMediator.mUpdateCallback.onSimStateChanged(
771                 1 /* subId */,
772                 0 /* slotId */,
773                 TelephonyManager.SIM_STATE_PIN_REQUIRED);
774         TestableLooper.get(this).processAllMessages();
775 
776         reset(mStatusBarKeyguardViewManager);
777 
778         // but then disabled by a NOT_READY
779         mViewMediator.mUpdateCallback.onSimStateChanged(
780                 1 /* subId */,
781                 0 /* slotId */,
782                 TelephonyManager.SIM_STATE_NOT_READY);
783         TestableLooper.get(this).processAllMessages();
784 
785         // A call to reset the keyguard and bouncer was invoked
786         verify(mStatusBarKeyguardViewManager).reset(true);
787     }
788 
789     @Test
790     @TestableLooper.RunWithLooper(setAsMainLooper = true)
restoreBouncerWhenSimLockedAndKeyguardIsGoingAway_initiallyNotShowing()791     public void restoreBouncerWhenSimLockedAndKeyguardIsGoingAway_initiallyNotShowing() {
792         // When showing and provisioned
793         mViewMediator.onSystemReady();
794         when(mUpdateMonitor.isDeviceProvisioned()).thenReturn(true);
795         mViewMediator.setShowingLocked(false, "");
796 
797         // and a SIM becomes locked and requires a PIN
798         mViewMediator.mUpdateCallback.onSimStateChanged(
799                 1 /* subId */,
800                 0 /* slotId */,
801                 TelephonyManager.SIM_STATE_PIN_REQUIRED);
802 
803         // and the keyguard goes away
804         mViewMediator.setShowingLocked(false, "");
805         when(mKeyguardStateController.isShowing()).thenReturn(false);
806         mViewMediator.mUpdateCallback.onKeyguardVisibilityChanged(false);
807 
808         TestableLooper.get(this).processAllMessages();
809 
810         // then make sure it comes back
811         verify(mStatusBarKeyguardViewManager, atLeast(1)).show(null);
812     }
813 
814     @Test
testBouncerPrompt_deviceLockedByAdmin()815     public void testBouncerPrompt_deviceLockedByAdmin() {
816         // GIVEN no trust agents enabled and biometrics aren't enrolled
817         when(mUpdateMonitor.isTrustUsuallyManaged(anyInt())).thenReturn(false);
818         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(false);
819 
820         // WHEN the strong auth reason is AFTER_DPM_LOCK_NOW
821         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
822                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
823         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
824         when(strongAuthTracker.getStrongAuthForUser(anyInt())).thenReturn(
825                 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW);
826 
827         // THEN the bouncer prompt reason should return PROMPT_REASON_DEVICE_ADMIN
828         assertEquals(KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN,
829                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
830     }
831 
832     @Test
testBouncerPrompt_deviceLockedByAdaptiveAuth()833     public void testBouncerPrompt_deviceLockedByAdaptiveAuth() {
834         // GIVEN no trust agents enabled and biometrics aren't enrolled
835         when(mUpdateMonitor.isTrustUsuallyManaged(anyInt())).thenReturn(false);
836         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(false);
837 
838         // WHEN the strong auth reason is SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST
839         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
840                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
841         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
842         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
843         when(strongAuthTracker.getStrongAuthForUser(anyInt())).thenReturn(
844                 SOME_AUTH_REQUIRED_AFTER_ADAPTIVE_AUTH_REQUEST);
845 
846         // THEN the bouncer prompt reason should return PROMPT_REASON_ADAPTIVE_AUTH_REQUEST
847         assertEquals(KeyguardSecurityView.PROMPT_REASON_ADAPTIVE_AUTH_REQUEST,
848                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
849     }
850 
851     @Test
testBouncerPrompt_deviceRestartedDueToMainlineUpdate()852     public void testBouncerPrompt_deviceRestartedDueToMainlineUpdate() {
853         // GIVEN biometrics enrolled
854         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(true);
855 
856         // WHEN reboot caused by ota update
857         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
858                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
859         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
860         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(false);
861         when(mSystemPropertiesHelper.get(SYS_BOOT_REASON_PROP)).thenReturn(REBOOT_MAINLINE_UPDATE);
862 
863         // THEN the bouncer prompt reason should return PROMPT_REASON_RESTART_FOR_OTA
864         assertEquals(KeyguardSecurityView.PROMPT_REASON_RESTART_FOR_MAINLINE_UPDATE,
865                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
866     }
867 
868     @Test
testBouncerPrompt_afterUserLockDown()869     public void testBouncerPrompt_afterUserLockDown() {
870         // GIVEN biometrics enrolled
871         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(true);
872 
873         // WHEN user has locked down the device
874         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
875                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
876         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
877         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
878         when(strongAuthTracker.getStrongAuthForUser(anyInt()))
879                 .thenReturn(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
880 
881         // THEN the bouncer prompt reason should return PROMPT_REASON_USER_REQUEST
882         assertEquals(KeyguardSecurityView.PROMPT_REASON_USER_REQUEST,
883                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
884     }
885 
886     @Test
testBouncerPrompt_afterUserLockDown_noBiometricsEnrolled()887     public void testBouncerPrompt_afterUserLockDown_noBiometricsEnrolled() {
888         // GIVEN biometrics not enrolled
889         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(false);
890 
891         // WHEN user has locked down the device
892         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
893                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
894         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
895         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
896         when(strongAuthTracker.getStrongAuthForUser(anyInt()))
897                 .thenReturn(STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN);
898 
899         // THEN the bouncer prompt reason should return the default prompt
900         assertEquals(KeyguardSecurityView.PROMPT_REASON_NONE,
901                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
902     }
903 
904     @Test
testBouncerPrompt_nonStrongIdleTimeout()905     public void testBouncerPrompt_nonStrongIdleTimeout() {
906         // GIVEN trust agents enabled and biometrics are enrolled
907         when(mUpdateMonitor.isTrustUsuallyManaged(anyInt())).thenReturn(true);
908         when(mUpdateMonitor.isUnlockingWithBiometricsPossible(anyInt())).thenReturn(true);
909 
910         // WHEN the strong auth reason is STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT
911         KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
912                 mock(KeyguardUpdateMonitor.StrongAuthTracker.class);
913         when(mUpdateMonitor.getStrongAuthTracker()).thenReturn(strongAuthTracker);
914         when(strongAuthTracker.hasUserAuthenticatedSinceBoot()).thenReturn(true);
915         when(strongAuthTracker.isNonStrongBiometricAllowedAfterIdleTimeout(
916                 anyInt())).thenReturn(false);
917         when(strongAuthTracker.getStrongAuthForUser(anyInt())).thenReturn(
918                 STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT);
919 
920         // THEN the bouncer prompt reason should return
921         // STRONG_AUTH_REQUIRED_AFTER_NON_STRONG_BIOMETRICS_TIMEOUT
922         assertEquals(KeyguardSecurityView.PROMPT_REASON_NON_STRONG_BIOMETRIC_TIMEOUT,
923                 mViewMediator.mViewMediatorCallback.getBouncerPromptReason());
924     }
925 
926     @Test
lockAfterScreenTimeoutUsesValueFromSettings()927     public void lockAfterScreenTimeoutUsesValueFromSettings() {
928         int currentUserId = 99;
929         int userSpecificTimeout = 5999;
930 
931         when(mSelectedUserInteractor.getSelectedUserId()).thenReturn(currentUserId);
932         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(false);
933         when(mDevicePolicyManager.getMaximumTimeToLock(null, currentUserId)).thenReturn(0L);
934         when(mSecureSettings.getIntForUser(LOCK_SCREEN_LOCK_AFTER_TIMEOUT,
935                 KEYGUARD_LOCK_AFTER_DELAY_DEFAULT, currentUserId)).thenReturn(userSpecificTimeout);
936         mSystemClock.setElapsedRealtime(0L);
937         ArgumentCaptor<PendingIntent> pendingIntent = ArgumentCaptor.forClass(PendingIntent.class);
938 
939         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_TIMEOUT);
940 
941         verify(mAlarmManager).setExactAndAllowWhileIdle(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
942                 eq(Long.valueOf(userSpecificTimeout)), pendingIntent.capture());
943         assertEquals(DELAYED_KEYGUARD_ACTION, pendingIntent.getValue().getIntent().getAction());
944     }
945 
946     @Test
testHideSurfaceBehindKeyguardMarksKeyguardNotGoingAway()947     public void testHideSurfaceBehindKeyguardMarksKeyguardNotGoingAway() {
948         mViewMediator.hideSurfaceBehindKeyguard();
949 
950         verify(mKeyguardStateController).notifyKeyguardGoingAway(false);
951     }
952 
953     @Test
testUpdateIsKeyguardAfterOccludeAnimationEnds()954     public void testUpdateIsKeyguardAfterOccludeAnimationEnds() {
955         mViewMediator.mOccludeAnimationController.onTransitionAnimationEnd(
956                 false /* isExpandingFullyAbove */);
957 
958         // Since the updateIsKeyguard call is delayed during the animation, ensure it's called once
959         // it ends.
960         verify(mCentralSurfaces).updateIsKeyguard();
961     }
962 
963     @Test
testUpdateIsKeyguardAfterOccludeAnimationIsCancelled()964     public void testUpdateIsKeyguardAfterOccludeAnimationIsCancelled() {
965         mViewMediator.mOccludeAnimationController.onTransitionAnimationCancelled(
966                 null /* newKeyguardOccludedState */);
967 
968         // Since the updateIsKeyguard call is delayed during the animation, ensure it's called if
969         // it's cancelled.
970         verify(mCentralSurfaces).updateIsKeyguard();
971     }
972 
973     @Test
974     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testCancelKeyguardExitAnimation_noPendingLock_keyguardWillNotBeShowing()975     public void testCancelKeyguardExitAnimation_noPendingLock_keyguardWillNotBeShowing() {
976         startMockKeyguardExitAnimation();
977         cancelMockKeyguardExitAnimation();
978 
979         // There should not be a pending lock, but try to handle it anyway to ensure one isn't set.
980         mViewMediator.maybeHandlePendingLock();
981         TestableLooper.get(this).processAllMessages();
982 
983         assertFalse(mViewMediator.isShowingAndNotOccluded());
984         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
985     }
986 
987     @Test
988     @TestableLooper.RunWithLooper(setAsMainLooper = true)
989     @EnableFlags(FLAG_RELOCK_WITH_POWER_BUTTON_IMMEDIATELY)
testCancelKeyguardExitAnimationDueToSleep_withPendingLockAndRelockFlag_keyguardWillBeShowing()990     public void testCancelKeyguardExitAnimationDueToSleep_withPendingLockAndRelockFlag_keyguardWillBeShowing() {
991         startMockKeyguardExitAnimation();
992 
993         mViewMediator.onStartedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON);
994         mViewMediator.onFinishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, false);
995 
996         cancelMockKeyguardExitAnimation();
997 
998         mViewMediator.maybeHandlePendingLock();
999         TestableLooper.get(this).processAllMessages();
1000 
1001         assertTrue(mViewMediator.isShowingAndNotOccluded());
1002 
1003         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(true);
1004 
1005         // Unlock animators call `exitKeyguardAndFinishSurfaceBehindRemoteAnimation` when canceled
1006         mViewMediator.exitKeyguardAndFinishSurfaceBehindRemoteAnimation(false);
1007         TestableLooper.get(this).processAllMessages();
1008 
1009         verify(mUpdateMonitor, never()).dispatchKeyguardDismissAnimationFinished();
1010     }
1011 
1012     @Test
1013     @TestableLooper.RunWithLooper(setAsMainLooper = true)
1014     @DisableFlags(FLAG_RELOCK_WITH_POWER_BUTTON_IMMEDIATELY)
testCancelKeyguardExitAnimationDueToSleep_withPendingLock_keyguardWillBeShowing()1015     public void testCancelKeyguardExitAnimationDueToSleep_withPendingLock_keyguardWillBeShowing() {
1016         startMockKeyguardExitAnimation();
1017 
1018         mViewMediator.onStartedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON);
1019         mViewMediator.onFinishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, false);
1020 
1021         cancelMockKeyguardExitAnimation();
1022 
1023         mViewMediator.maybeHandlePendingLock();
1024         TestableLooper.get(this).processAllMessages();
1025 
1026         assertTrue(mViewMediator.isShowingAndNotOccluded());
1027         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(true);
1028     }
1029 
1030     @Test
1031     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testCancelKeyguardExitAnimationThenSleep_withPendingLock_keyguardWillBeShowing()1032     public void testCancelKeyguardExitAnimationThenSleep_withPendingLock_keyguardWillBeShowing() {
1033         startMockKeyguardExitAnimation();
1034         cancelMockKeyguardExitAnimation();
1035 
1036         // Calling cancel above results in keyguard not visible, as there is no pending lock
1037         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
1038 
1039         mViewMediator.maybeHandlePendingLock();
1040         TestableLooper.get(this).processAllMessages();
1041 
1042         mViewMediator.onStartedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON);
1043         mViewMediator.onFinishedGoingToSleep(PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, false);
1044 
1045         mViewMediator.maybeHandlePendingLock();
1046         TestableLooper.get(this).processAllMessages();
1047 
1048         assertTrue(mViewMediator.isShowingAndNotOccluded());
1049     }
1050 
1051     @Test
1052     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testStartKeyguardExitAnimation_expectSurfaceBehindRemoteAnimationAndExits()1053     public void testStartKeyguardExitAnimation_expectSurfaceBehindRemoteAnimationAndExits() {
1054         startMockKeyguardExitAnimation();
1055         assertTrue(mViewMediator.isAnimatingBetweenKeyguardAndSurfaceBehind());
1056 
1057         mViewMediator.mViewMediatorCallback.keyguardDonePending(mDefaultUserId);
1058         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
1059         TestableLooper.get(this).processAllMessages();
1060         verify(mKeyguardUnlockAnimationController).notifyFinishedKeyguardExitAnimation(false);
1061     }
1062 
1063     @Test
1064     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testKeyguardDelayedOnGoingToSleep_ifScreenOffAnimationWillPlayButIsntPlayingYet()1065     public void testKeyguardDelayedOnGoingToSleep_ifScreenOffAnimationWillPlayButIsntPlayingYet() {
1066         mViewMediator.onSystemReady();
1067         TestableLooper.get(this).processAllMessages();
1068 
1069         mViewMediator.setShowingLocked(false, "");
1070         TestableLooper.get(this).processAllMessages();
1071 
1072         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
1073         TestableLooper.get(this).processAllMessages();
1074 
1075         when(mScreenOffAnimationController.shouldDelayKeyguardShow()).thenReturn(true);
1076         when(mScreenOffAnimationController.isKeyguardShowDelayed()).thenReturn(false);
1077         mViewMediator.onFinishedGoingToSleep(OFF_BECAUSE_OF_USER, false);
1078         TestableLooper.get(this).processAllMessages();
1079 
1080         assertFalse(mViewMediator.isShowingAndNotOccluded());
1081     }
1082 
1083     @Test
1084     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testKeyguardNotDelayedOnGoingToSleep_ifScreenOffAnimationWillNotPlay()1085     public void testKeyguardNotDelayedOnGoingToSleep_ifScreenOffAnimationWillNotPlay() {
1086         mViewMediator.onSystemReady();
1087         TestableLooper.get(this).processAllMessages();
1088 
1089         mViewMediator.setShowingLocked(false, "");
1090         TestableLooper.get(this).processAllMessages();
1091 
1092         mViewMediator.onStartedGoingToSleep(OFF_BECAUSE_OF_USER);
1093         TestableLooper.get(this).processAllMessages();
1094 
1095         when(mScreenOffAnimationController.shouldDelayKeyguardShow()).thenReturn(false);
1096         mViewMediator.onFinishedGoingToSleep(OFF_BECAUSE_OF_USER, false);
1097         TestableLooper.get(this).processAllMessages();
1098 
1099         assertTrue(mViewMediator.isShowingAndNotOccluded());
1100     }
1101 
1102     @Test
testWakeAndUnlocking()1103     public void testWakeAndUnlocking() {
1104         mViewMediator.onWakeAndUnlocking(false);
1105         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
1106     }
1107 
1108     @Test
testWakeAndUnlockingOverDream()1109     public void testWakeAndUnlockingOverDream() {
1110         // Ensure ordering unlock and wake is enabled.
1111         createAndStartViewMediator(true);
1112 
1113         // Send signal to wake
1114         mViewMediator.onWakeAndUnlocking(true);
1115 
1116         // Ensure not woken up yet
1117         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
1118 
1119         // Verify keyguard told of authentication
1120         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
1121         mViewMediator.mViewMediatorCallback.keyguardDonePending(mDefaultUserId);
1122         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
1123         final ArgumentCaptor<Runnable> animationRunnableCaptor =
1124                 ArgumentCaptor.forClass(Runnable.class);
1125         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
1126                 animationRunnableCaptor.capture());
1127 
1128         when(mStatusBarStateController.isDreaming()).thenReturn(true);
1129         when(mStatusBarStateController.isDozing()).thenReturn(false);
1130         animationRunnableCaptor.getValue().run();
1131 
1132         when(mKeyguardStateController.isShowing()).thenReturn(false);
1133         mViewMediator.mViewMediatorCallback.keyguardGone();
1134 
1135         // Verify woken up now.
1136         verify(mPowerManager).wakeUp(anyLong(), anyInt(), anyString());
1137     }
1138 
1139     @Test
testWakeAndUnlockingOverDream_signalAuthenticateIfStillShowing()1140     public void testWakeAndUnlockingOverDream_signalAuthenticateIfStillShowing() {
1141         // Ensure ordering unlock and wake is enabled.
1142         createAndStartViewMediator(true);
1143 
1144         // Send signal to wake
1145         mViewMediator.onWakeAndUnlocking(true);
1146 
1147         // Ensure not woken up yet
1148         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
1149 
1150         // Verify keyguard told of authentication
1151         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
1152         clearInvocations(mStatusBarKeyguardViewManager);
1153         mViewMediator.mViewMediatorCallback.keyguardDonePending(mDefaultUserId);
1154         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
1155         final ArgumentCaptor<Runnable> animationRunnableCaptor =
1156                 ArgumentCaptor.forClass(Runnable.class);
1157         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
1158                 animationRunnableCaptor.capture());
1159 
1160         when(mStatusBarStateController.isDreaming()).thenReturn(true);
1161         when(mStatusBarStateController.isDozing()).thenReturn(false);
1162         animationRunnableCaptor.getValue().run();
1163 
1164         when(mKeyguardStateController.isShowing()).thenReturn(true);
1165 
1166         mViewMediator.mViewMediatorCallback.keyguardGone();
1167 
1168 
1169         // Verify keyguard view controller informed of authentication again
1170         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
1171     }
1172 
1173     @Test
testWakeAndUnlockingOverNonInteractiveDream_noWakeByKeyguardViewMediator()1174     public void testWakeAndUnlockingOverNonInteractiveDream_noWakeByKeyguardViewMediator() {
1175         // Send signal to wake
1176         mViewMediator.onWakeAndUnlocking(false);
1177 
1178         // Ensure not woken up yet
1179         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
1180 
1181         // Verify keyguard told of authentication
1182         verify(mStatusBarKeyguardViewManager).notifyKeyguardAuthenticated(anyBoolean());
1183         mViewMediator.mViewMediatorCallback.keyguardDonePending(mDefaultUserId);
1184         mViewMediator.mViewMediatorCallback.readyForKeyguardDone();
1185         final ArgumentCaptor<Runnable> animationRunnableCaptor =
1186                 ArgumentCaptor.forClass(Runnable.class);
1187         verify(mStatusBarKeyguardViewManager).startPreHideAnimation(
1188                 animationRunnableCaptor.capture());
1189 
1190         when(mStatusBarStateController.isDreaming()).thenReturn(true);
1191         when(mStatusBarStateController.isDozing()).thenReturn(false);
1192         animationRunnableCaptor.getValue().run();
1193 
1194         when(mKeyguardStateController.isShowing()).thenReturn(false);
1195         mViewMediator.mViewMediatorCallback.keyguardGone();
1196 
1197         // Verify not woken up.
1198         verify(mPowerManager, never()).wakeUp(anyLong(), anyInt(), anyString());
1199     }
1200 
1201     @Test
1202     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testDoKeyguardWhileInteractive_resets()1203     public void testDoKeyguardWhileInteractive_resets() {
1204         mViewMediator.setShowingLocked(true, "");
1205         when(mKeyguardStateController.isShowing()).thenReturn(true);
1206         TestableLooper.get(this).processAllMessages();
1207 
1208         mViewMediator.onSystemReady();
1209         TestableLooper.get(this).processAllMessages();
1210 
1211         assertTrue(mViewMediator.isShowingAndNotOccluded());
1212         verify(mStatusBarKeyguardViewManager).reset(false);
1213     }
1214 
1215     @Test
1216     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testDoKeyguardWhileNotInteractive_showsInsteadOfResetting()1217     public void testDoKeyguardWhileNotInteractive_showsInsteadOfResetting() {
1218         mViewMediator.setShowingLocked(true, "");
1219         when(mKeyguardStateController.isShowing()).thenReturn(true);
1220         TestableLooper.get(this).processAllMessages();
1221 
1222         when(mPowerManager.isInteractive()).thenReturn(false);
1223 
1224         mViewMediator.onSystemReady();
1225         TestableLooper.get(this).processAllMessages();
1226 
1227         assertTrue(mViewMediator.isShowingAndNotOccluded());
1228         verify(mStatusBarKeyguardViewManager, never()).reset(anyBoolean());
1229     }
1230 
1231     @Test
1232     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testStartKeyguardExitAnimation_thenCancelImmediately_doesNotResetAndUpdatesWM()1233     public void testStartKeyguardExitAnimation_thenCancelImmediately_doesNotResetAndUpdatesWM() {
1234         startMockKeyguardExitAnimation();
1235         cancelMockKeyguardExitAnimation();
1236 
1237         // This will trigger doKeyguardLocked and we can verify that we ask ATMS to show the
1238         // keyguard explicitly, even though we're already showing, because we cancelled immediately.
1239         mViewMediator.onSystemReady();
1240         reset(mActivityTaskManagerService);
1241         processAllMessagesAndBgExecutorMessages();
1242 
1243         verify(mStatusBarKeyguardViewManager, never()).reset(anyBoolean());
1244 
1245     }
1246 
1247     @Test
1248     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testStartKeyguardExitAnimation_whenNotInteractive_doesShowAndUpdatesWM()1249     public void testStartKeyguardExitAnimation_whenNotInteractive_doesShowAndUpdatesWM() {
1250         // If the exit animation was triggered but the device became non-interactive, make sure
1251         // relock happens
1252         when(mPowerManager.isInteractive()).thenReturn(false);
1253 
1254         startMockKeyguardExitAnimation();
1255         cancelMockKeyguardExitAnimation();
1256 
1257         verify(mStatusBarKeyguardViewManager, atLeast(1)).show(null);
1258         assertATMSAndKeyguardViewMediatorStatesMatch();
1259     }
1260 
1261     /**
1262      * Interactions with the ActivityTaskManagerService and others are posted to an executor that
1263      * doesn't use the testable looper. Use this method to ensure those are run as well.
1264      */
processAllMessagesAndBgExecutorMessages()1265     private void processAllMessagesAndBgExecutorMessages() {
1266         TestableLooper.get(this).processAllMessages();
1267         mUiBgExecutor.runAllReady();
1268     }
1269 
1270     /**
1271      * Configures mocks appropriately, then starts the keyguard exit animation.
1272      */
startMockKeyguardExitAnimation()1273     private void startMockKeyguardExitAnimation() {
1274         mViewMediator.onSystemReady();
1275         processAllMessagesAndBgExecutorMessages();
1276 
1277         mViewMediator.setShowingLocked(true, "");
1278 
1279         RemoteAnimationTarget[] apps = new RemoteAnimationTarget[]{
1280                 mock(RemoteAnimationTarget.class)
1281         };
1282         RemoteAnimationTarget[] wallpapers = new RemoteAnimationTarget[]{
1283                 mock(RemoteAnimationTarget.class)
1284         };
1285         IRemoteAnimationFinishedCallback callback = mock(IRemoteAnimationFinishedCallback.class);
1286 
1287         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(true);
1288         mViewMediator.mKeyguardGoingAwayRunnable.run();
1289         mViewMediator.startKeyguardExitAnimation(TRANSIT_OLD_KEYGUARD_GOING_AWAY, apps, wallpapers,
1290                 null, callback);
1291         processAllMessagesAndBgExecutorMessages();
1292     }
1293 
1294     /**
1295      * Configures mocks appropriately, then cancels the keyguard exit animation.
1296      */
cancelMockKeyguardExitAnimation()1297     private void cancelMockKeyguardExitAnimation() {
1298         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(false);
1299         mViewMediator.cancelKeyguardExitAnimation();
1300         processAllMessagesAndBgExecutorMessages();
1301     }
1302     /**
1303      * Asserts the last value passed to ATMS#setLockScreenShown. This should be confirmed alongside
1304      * {@link KeyguardViewMediator#isShowingAndNotOccluded()} to verify that state is not mismatched
1305      * between SysUI and WM.
1306      */
assertATMSLockScreenShowing(boolean showing)1307     private void assertATMSLockScreenShowing(boolean showing)
1308             throws RemoteException {
1309 
1310         if (ENABLE_NEW_KEYGUARD_SHELL_TRANSITIONS) {
1311             // ATMS is called via bgExecutor, so make sure to run all of those calls first.
1312             processAllMessagesAndBgExecutorMessages();
1313 
1314             final InOrder orderedSetLockScreenShownCalls = inOrder(mKeyguardTransitions);
1315             final ArgumentCaptor<Boolean> showingCaptor = ArgumentCaptor.forClass(Boolean.class);
1316             orderedSetLockScreenShownCalls
1317                     .verify(mKeyguardTransitions, atLeastOnce())
1318                     .startKeyguardTransition(showingCaptor.capture(), anyBoolean());
1319 
1320             // The captor will have the most recent startKeyguardTransition call's value.
1321             assertEquals(showing, showingCaptor.getValue());
1322 
1323             // We're now just after the last startKeyguardTransition call. If we expect the
1324             // lockscreen to be showing, ensure that we didn't subsequently ask for it to go away.
1325             if (showing) {
1326                 orderedSetLockScreenShownCalls.verify(mKeyguardTransitions, never())
1327                         .startKeyguardTransition(eq(false), anyBoolean());
1328             }
1329             return;
1330         }
1331 
1332         // ATMS is called via bgExecutor, so make sure to run all of those calls first.
1333         processAllMessagesAndBgExecutorMessages();
1334 
1335         final InOrder orderedSetLockScreenShownCalls = inOrder(mActivityTaskManagerService);
1336         final ArgumentCaptor<Boolean> showingCaptor = ArgumentCaptor.forClass(Boolean.class);
1337         orderedSetLockScreenShownCalls
1338                 .verify(mActivityTaskManagerService, atLeastOnce())
1339                 .setLockScreenShown(showingCaptor.capture(), anyBoolean());
1340 
1341         // The captor will have the most recent setLockScreenShown call's value.
1342         assertEquals(showing, showingCaptor.getValue());
1343     }
1344 
1345     /**
1346      * Asserts that we eventually called ATMS#keyguardGoingAway and did not subsequently call
1347      * ATMS#setLockScreenShown(true) which would cancel the going away.
1348      */
assertATMSKeyguardGoingAway()1349     private void assertATMSKeyguardGoingAway() throws RemoteException {
1350         // ATMS is called via bgExecutor, so make sure to run all of those calls first.
1351         processAllMessagesAndBgExecutorMessages();
1352 
1353         if (ENABLE_NEW_KEYGUARD_SHELL_TRANSITIONS) {
1354             final InOrder orderedGoingAwayCalls = inOrder(mKeyguardTransitions);
1355             orderedGoingAwayCalls.verify(mKeyguardTransitions, atLeastOnce())
1356                     .startKeyguardTransition(eq(false) /* keyguardShowing */,
1357                             eq(false) /* aodShowing */);
1358 
1359             // Advance the inOrder to just past the last goingAway call. Let's make sure we didn't
1360             // re-show the lockscreen, which would cancel going away.
1361             orderedGoingAwayCalls.verify(mKeyguardTransitions, never())
1362                     .startKeyguardTransition(eq(true) /* keyguardShowing */,
1363                             anyBoolean() /* aodShowing */);
1364             return;
1365         }
1366 
1367         final InOrder orderedGoingAwayCalls = inOrder(mActivityTaskManagerService);
1368         orderedGoingAwayCalls.verify(mActivityTaskManagerService, atLeastOnce())
1369                 .keyguardGoingAway(anyInt());
1370 
1371         // Advance the inOrder to just past the last goingAway call. Let's make sure we didn't
1372         // re-show the lockscreen, which would cancel going away.
1373         orderedGoingAwayCalls.verify(mActivityTaskManagerService, never())
1374                 .setLockScreenShown(eq(true), anyBoolean());
1375     }
1376 
1377     @Test
1378     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testNotStartingKeyguardWhenFlagIsDisabled()1379     public void testNotStartingKeyguardWhenFlagIsDisabled() {
1380         mViewMediator.setShowingLocked(false, "");
1381         when(mKeyguardStateController.isShowing()).thenReturn(false);
1382 
1383         mViewMediator.onDreamingStarted();
1384         assertFalse(mViewMediator.isShowingAndNotOccluded());
1385     }
1386 
1387     @Test
1388     @TestableLooper.RunWithLooper(setAsMainLooper = true)
testStartingKeyguardWhenFlagIsEnabled()1389     public void testStartingKeyguardWhenFlagIsEnabled() {
1390         mViewMediator.setShowingLocked(true, "");
1391         when(mKeyguardStateController.isShowing()).thenReturn(true);
1392 
1393         mViewMediator.onDreamingStarted();
1394         assertTrue(mViewMediator.isShowingAndNotOccluded());
1395     }
1396 
1397     @Test
testOnStartedWakingUp_logsUiEvent()1398     public void testOnStartedWakingUp_logsUiEvent() {
1399         final InstanceId instanceId = InstanceId.fakeInstanceId(8);
1400         when(mSessionTracker.getSessionId((anyInt()))).thenReturn(instanceId);
1401         mViewMediator.onStartedWakingUp(PowerManager.WAKE_REASON_LIFT, false);
1402 
1403         verify(mUiEventLogger).logWithInstanceIdAndPosition(
1404                 eq(BiometricUnlockController.BiometricUiEvent.STARTED_WAKING_UP),
1405                 anyInt(),
1406                 any(),
1407                 eq(instanceId),
1408                 eq(PowerManager.WAKE_REASON_LIFT)
1409         );
1410     }
1411 
1412     @Test
1413     @TestableLooper.RunWithLooper(setAsMainLooper = true)
pendingPinLockOnKeyguardGoingAway_doKeyguardLockedOnKeyguardVisibilityChanged()1414     public void pendingPinLockOnKeyguardGoingAway_doKeyguardLockedOnKeyguardVisibilityChanged() {
1415         // GIVEN SIM_STATE_PIN_REQUIRED
1416         mViewMediator.onSystemReady();
1417         final KeyguardUpdateMonitorCallback keyguardUpdateMonitorCallback =
1418                 mViewMediator.mUpdateCallback;
1419         keyguardUpdateMonitorCallback.onSimStateChanged(0, 0,
1420                 TelephonyManager.SIM_STATE_PIN_REQUIRED);
1421         TestableLooper.get(this).processAllMessages();
1422 
1423         // ...and then the primary bouncer shows while the keyguard is going away
1424         captureKeyguardStateControllerCallback();
1425         when(mKeyguardStateController.isPrimaryBouncerShowing()).thenReturn(true);
1426         when(mKeyguardStateController.isKeyguardGoingAway()).thenReturn(true);
1427         mKeyguardStateControllerCallback.getValue().onPrimaryBouncerShowingChanged();
1428         TestableLooper.get(this).processAllMessages();
1429 
1430         // WHEN keyguard visibility becomes FALSE
1431         mViewMediator.setShowingLocked(false, "");
1432         keyguardUpdateMonitorCallback.onKeyguardVisibilityChanged(false);
1433         TestableLooper.get(this).processAllMessages();
1434 
1435         // THEN keyguard shows due to the pending SIM PIN lock
1436         assertTrue(mViewMediator.isShowingAndNotOccluded());
1437     }
1438 
1439     @Test
testBouncerSwipeDown()1440     public void testBouncerSwipeDown() {
1441         mViewMediator.getViewMediatorCallback().onBouncerSwipeDown();
1442         verify(mStatusBarKeyguardViewManager).reset(true);
1443     }
createAndStartViewMediator()1444     private void createAndStartViewMediator() {
1445         createAndStartViewMediator(false);
1446     }
1447 
createAndStartViewMediator(boolean orderUnlockAndWake)1448     private void createAndStartViewMediator(boolean orderUnlockAndWake) {
1449         mContext.getOrCreateTestableResources().addOverride(
1450                 com.android.internal.R.bool.config_orderUnlockAndWake, orderUnlockAndWake);
1451 
1452         mViewMediator = new KeyguardViewMediator(
1453                 mContext,
1454                 mUiEventLogger,
1455                 mSessionTracker,
1456                 mUserTracker,
1457                 mFalsingCollector,
1458                 mLockPatternUtils,
1459                 mBroadcastDispatcher,
1460                 () -> mStatusBarKeyguardViewManager,
1461                 mDismissCallbackRegistry,
1462                 mUpdateMonitor,
1463                 mDumpManager,
1464                 mUiBgExecutor,
1465                 mPowerManager,
1466                 mTrustManager,
1467                 mUserSwitcherController,
1468                 mDeviceConfig,
1469                 mNavigationModeController,
1470                 mKeyguardDisplayManager,
1471                 mDozeParameters,
1472                 mStatusBarStateController,
1473                 mKeyguardStateController,
1474                 () -> mKeyguardUnlockAnimationController,
1475                 mScreenOffAnimationController,
1476                 () -> mNotificationShadeDepthController,
1477                 mScreenOnCoordinator,
1478                 mKeyguardTransitions,
1479                 mKosmos.getInteractionJankMonitor(),
1480                 mDreamOverlayStateController,
1481                 mJavaAdapter,
1482                 mWallpaperRepository,
1483                 () -> mShadeController,
1484                 () -> mNotificationShadeWindowController,
1485                 () -> mActivityTransitionAnimator,
1486                 () -> mScrimController,
1487                 mActivityTaskManagerService,
1488                 mStatusBarService,
1489                 mFeatureFlags,
1490                 mSecureSettings,
1491                 mSystemSettings,
1492                 mSystemClock,
1493                 mProcessWrapper,
1494                 mDispatcher,
1495                 () -> mDreamViewModel,
1496                 () -> mCommunalTransitionViewModel,
1497                 mSystemPropertiesHelper,
1498                 () -> mock(WindowManagerLockscreenVisibilityManager.class),
1499                 mSelectedUserInteractor,
1500                 mKosmos.getKeyguardInteractor(),
1501                 mKeyguardTransitionBootInteractor,
1502                 mKosmos::getCommunalSceneInteractor,
1503                 mKosmos::getCommunalSettingsInteractor,
1504                 mock(WindowManagerOcclusionManager.class));
1505         mViewMediator.mUserChangedCallback = mUserTrackerCallback;
1506         mViewMediator.start();
1507 
1508         mViewMediator.registerCentralSurfaces(mCentralSurfaces, null, null, null, null);
1509         mViewMediator.onBootCompleted();
1510     }
1511 
captureKeyguardStateControllerCallback()1512     private void captureKeyguardStateControllerCallback() {
1513         verify(mKeyguardStateController).addCallback(mKeyguardStateControllerCallback.capture());
1514     }
1515 
captureKeyguardUpdateMonitorCallback()1516     private void captureKeyguardUpdateMonitorCallback() {
1517         verify(mUpdateMonitor).registerCallback(mKeyguardUpdateMonitorCallbackCaptor.capture());
1518     }
1519 
setCurrentUser(int userId, boolean isSecure)1520     private void setCurrentUser(int userId, boolean isSecure) {
1521         when(mUserTracker.getUserId()).thenReturn(userId);
1522         when(mSelectedUserInteractor.getSelectedUserId()).thenReturn(userId);
1523         when(mLockPatternUtils.isSecure(userId)).thenReturn(isSecure);
1524     }
1525 }
1526