1 /*
2  * Copyright (C) 2017 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.server.power;
18 
19 import static android.app.ActivityManager.PROCESS_STATE_BOUND_TOP;
20 import static android.app.ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
21 import static android.app.ActivityManager.PROCESS_STATE_RECEIVER;
22 import static android.app.ActivityManager.PROCESS_STATE_TOP_SLEEPING;
23 import static android.os.PowerManager.USER_ACTIVITY_EVENT_BUTTON;
24 import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
25 import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
26 import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
27 import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
28 
29 import static com.google.common.truth.Truth.assertThat;
30 
31 import static org.junit.Assert.assertFalse;
32 import static org.junit.Assert.assertTrue;
33 import static org.mockito.ArgumentMatchers.any;
34 import static org.mockito.ArgumentMatchers.anyBoolean;
35 import static org.mockito.ArgumentMatchers.anyInt;
36 import static org.mockito.ArgumentMatchers.anyLong;
37 import static org.mockito.ArgumentMatchers.anyString;
38 import static org.mockito.ArgumentMatchers.argThat;
39 import static org.mockito.ArgumentMatchers.eq;
40 import static org.mockito.ArgumentMatchers.isA;
41 import static org.mockito.ArgumentMatchers.isNull;
42 import static org.mockito.ArgumentMatchers.same;
43 import static org.mockito.Mockito.atLeastOnce;
44 import static org.mockito.Mockito.atMost;
45 import static org.mockito.Mockito.clearInvocations;
46 import static org.mockito.Mockito.doAnswer;
47 import static org.mockito.Mockito.doReturn;
48 import static org.mockito.Mockito.never;
49 import static org.mockito.Mockito.spy;
50 import static org.mockito.Mockito.times;
51 import static org.mockito.Mockito.verify;
52 import static org.mockito.Mockito.when;
53 
54 import android.app.ActivityManagerInternal;
55 import android.attention.AttentionManagerInternal;
56 import android.compat.testing.PlatformCompatChangeRule;
57 import android.content.AttributionSource;
58 import android.content.Context;
59 import android.content.ContextWrapper;
60 import android.content.Intent;
61 import android.content.IntentFilter;
62 import android.content.PermissionChecker;
63 import android.content.res.Resources;
64 import android.hardware.SensorManager;
65 import android.hardware.display.AmbientDisplayConfiguration;
66 import android.hardware.display.DisplayManagerInternal;
67 import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
68 import android.hardware.power.Boost;
69 import android.hardware.power.Mode;
70 import android.os.BatteryManager;
71 import android.os.BatteryManagerInternal;
72 import android.os.BatterySaverPolicyConfig;
73 import android.os.Binder;
74 import android.os.Handler;
75 import android.os.IBinder;
76 import android.os.IWakeLockCallback;
77 import android.os.Looper;
78 import android.os.PowerManager;
79 import android.os.PowerManagerInternal;
80 import android.os.PowerSaveState;
81 import android.os.UserHandle;
82 import android.os.test.TestLooper;
83 import android.provider.DeviceConfig;
84 import android.provider.Settings;
85 import android.service.dreams.DreamManagerInternal;
86 import android.sysprop.PowerProperties;
87 import android.test.mock.MockContentResolver;
88 import android.view.Display;
89 import android.view.DisplayInfo;
90 
91 import androidx.test.core.app.ApplicationProvider;
92 
93 import com.android.internal.app.IBatteryStats;
94 import com.android.internal.util.test.FakeSettingsProvider;
95 import com.android.server.LocalServices;
96 import com.android.server.SystemService;
97 import com.android.server.display.feature.DeviceConfigParameterProvider;
98 import com.android.server.lights.LightsManager;
99 import com.android.server.policy.WindowManagerPolicy;
100 import com.android.server.power.PowerManagerService.BatteryReceiver;
101 import com.android.server.power.PowerManagerService.BinderService;
102 import com.android.server.power.PowerManagerService.NativeWrapper;
103 import com.android.server.power.PowerManagerService.UserSwitchedReceiver;
104 import com.android.server.power.PowerManagerService.WakeLock;
105 import com.android.server.power.batterysaver.BatterySaverController;
106 import com.android.server.power.batterysaver.BatterySaverPolicy;
107 import com.android.server.power.batterysaver.BatterySaverStateMachine;
108 import com.android.server.power.batterysaver.BatterySavingStats;
109 import com.android.server.testutils.OffsettableClock;
110 
111 import libcore.junit.util.compat.CoreCompatChangeRule.DisableCompatChanges;
112 import libcore.junit.util.compat.CoreCompatChangeRule.EnableCompatChanges;
113 
114 import org.junit.After;
115 import org.junit.Before;
116 import org.junit.Rule;
117 import org.junit.Test;
118 import org.junit.rules.TestRule;
119 import org.mockito.ArgumentCaptor;
120 import org.mockito.ArgumentMatcher;
121 import org.mockito.Mock;
122 import org.mockito.Mockito;
123 import org.mockito.MockitoAnnotations;
124 import org.mockito.stubbing.Answer;
125 
126 import java.time.Duration;
127 import java.util.HashMap;
128 import java.util.Map;
129 import java.util.concurrent.Callable;
130 import java.util.concurrent.Executor;
131 import java.util.concurrent.atomic.AtomicReference;
132 
133 /**
134  * Tests for {@link com.android.server.power.PowerManagerService}.
135  *
136  * Build/Install/Run:
137  *  atest FrameworksServicesTests:PowerManagerServiceTest
138  */
139 @SuppressWarnings("GuardedBy")
140 public class PowerManagerServiceTest {
141     private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
142     private static final String SYSTEM_PROPERTY_REBOOT_REASON = "sys.boot.reason";
143 
144     private static final float BRIGHTNESS_FACTOR = 0.7f;
145     private static final boolean BATTERY_SAVER_ENABLED = true;
146 
147     @Mock private BatterySaverController mBatterySaverControllerMock;
148     @Mock private BatterySaverPolicy mBatterySaverPolicyMock;
149     @Mock private BatterySaverStateMachine mBatterySaverStateMachineMock;
150     @Mock private LightsManager mLightsManagerMock;
151     @Mock private DisplayManagerInternal mDisplayManagerInternalMock;
152     @Mock private BatteryManagerInternal mBatteryManagerInternalMock;
153     @Mock private ActivityManagerInternal mActivityManagerInternalMock;
154     @Mock private AttentionManagerInternal mAttentionManagerInternalMock;
155     @Mock private DreamManagerInternal mDreamManagerInternalMock;
156     @Mock private PowerManagerService.NativeWrapper mNativeWrapperMock;
157     @Mock private Notifier mNotifierMock;
158     @Mock private WirelessChargerDetector mWirelessChargerDetectorMock;
159     @Mock private AmbientDisplayConfiguration mAmbientDisplayConfigurationMock;
160     @Mock private SystemPropertiesWrapper mSystemPropertiesMock;
161     @Mock private LowPowerStandbyController mLowPowerStandbyControllerMock;
162     @Mock private Callable<Void> mInvalidateInteractiveCachesMock;
163     @Mock private InattentiveSleepWarningController mInattentiveSleepWarningControllerMock;
164     @Mock private PowerManagerService.PermissionCheckerWrapper mPermissionCheckerWrapperMock;
165     @Mock private PowerManagerService.PowerPropertiesWrapper mPowerPropertiesWrapper;
166     @Mock private DeviceConfigParameterProvider mDeviceParameterProvider;
167 
168     @Rule public TestRule compatChangeRule = new PlatformCompatChangeRule();
169 
170     private PowerManagerService mService;
171     private ContextWrapper mContextSpy;
172     private BatteryReceiver mBatteryReceiver;
173     private UserSwitchedReceiver mUserSwitchedReceiver;
174     private Resources mResourcesSpy;
175     private OffsettableClock mClock;
176     private long mLastElapsedRealtime;
177     private TestLooper mTestLooper;
178 
179     private static class IntentFilterMatcher implements ArgumentMatcher<IntentFilter> {
180         private final IntentFilter mFilter;
181 
IntentFilterMatcher(IntentFilter filter)182         IntentFilterMatcher(IntentFilter filter) {
183             mFilter = filter;
184         }
185 
186         @Override
matches(IntentFilter other)187         public boolean matches(IntentFilter other) {
188             if (other.countActions() != mFilter.countActions()) {
189                 return false;
190             }
191             for (int i = 0; i < mFilter.countActions(); i++) {
192                 if (!mFilter.getAction(i).equals(other.getAction(i))) {
193                     return false;
194                 }
195             }
196             return true;
197         }
198     }
199 
200     @Before
setUp()201     public void setUp() throws Exception {
202         MockitoAnnotations.initMocks(this);
203         FakeSettingsProvider.clearSettingsProvider();
204 
205         PowerSaveState powerSaveState = new PowerSaveState.Builder()
206                 .setBatterySaverEnabled(BATTERY_SAVER_ENABLED)
207                 .setBrightnessFactor(BRIGHTNESS_FACTOR)
208                 .build();
209         when(mBatterySaverPolicyMock.getBatterySaverPolicy(
210                 eq(PowerManager.ServiceType.SCREEN_BRIGHTNESS)))
211                 .thenReturn(powerSaveState);
212         when(mBatteryManagerInternalMock.isPowered(anyInt())).thenReturn(false);
213         when(mInattentiveSleepWarningControllerMock.isShown()).thenReturn(false);
214         when(mDisplayManagerInternalMock.requestPowerState(anyInt(), any(), anyBoolean()))
215                 .thenReturn(true);
216         when(mSystemPropertiesMock.get(eq(SYSTEM_PROPERTY_QUIESCENT), anyString())).thenReturn("");
217         when(mAmbientDisplayConfigurationMock.ambientDisplayAvailable()).thenReturn(true);
218 
219         addLocalServiceMock(LightsManager.class, mLightsManagerMock);
220         addLocalServiceMock(DisplayManagerInternal.class, mDisplayManagerInternalMock);
221         addLocalServiceMock(BatteryManagerInternal.class, mBatteryManagerInternalMock);
222         addLocalServiceMock(ActivityManagerInternal.class, mActivityManagerInternalMock);
223         addLocalServiceMock(AttentionManagerInternal.class, mAttentionManagerInternalMock);
224         addLocalServiceMock(DreamManagerInternal.class, mDreamManagerInternalMock);
225 
226         mContextSpy = spy(new ContextWrapper(ApplicationProvider.getApplicationContext()));
227         mResourcesSpy = spy(mContextSpy.getResources());
228         when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
229 
230         MockContentResolver cr = new MockContentResolver(mContextSpy);
231         cr.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
232         when(mContextSpy.getContentResolver()).thenReturn(cr);
233 
234         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_dreamsSupported))
235                 .thenReturn(true);
236         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_dreamsEnabledByDefault))
237                 .thenReturn(true);
238         Settings.Global.putInt(mContextSpy.getContentResolver(),
239                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
240         Settings.Secure.putInt(mContextSpy.getContentResolver(),
241                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 0);
242 
243         mClock = new OffsettableClock.Stopped();
244         mTestLooper = new TestLooper(mClock::now);
245     }
246 
createService()247     private PowerManagerService createService() {
248         mService = new PowerManagerService(mContextSpy, new PowerManagerService.Injector() {
249             @Override
250             Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
251                     SuspendBlocker suspendBlocker, WindowManagerPolicy policy,
252                     FaceDownDetector faceDownDetector, ScreenUndimDetector screenUndimDetector,
253                     Executor executor) {
254                 return mNotifierMock;
255             }
256 
257             @Override
258             SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
259                 return super.createSuspendBlocker(service, name);
260             }
261 
262             @Override
263             BatterySaverPolicy createBatterySaverPolicy(
264                     Object lock, Context context, BatterySavingStats batterySavingStats) {
265                 return mBatterySaverPolicyMock;
266             }
267 
268             @Override
269             BatterySaverController createBatterySaverController(
270                     Object lock, Context context, BatterySaverPolicy batterySaverPolicy,
271                     BatterySavingStats batterySavingStats) {
272                 return mBatterySaverControllerMock;
273             }
274 
275             @Override
276             BatterySaverStateMachine createBatterySaverStateMachine(Object lock, Context context,
277                     BatterySaverController batterySaverController) {
278                 return mBatterySaverStateMachineMock;
279             }
280 
281             @Override
282             NativeWrapper createNativeWrapper() {
283                 return mNativeWrapperMock;
284             }
285 
286             @Override
287             WirelessChargerDetector createWirelessChargerDetector(
288                     SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
289                 return mWirelessChargerDetectorMock;
290             }
291 
292             @Override
293             AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
294                 return mAmbientDisplayConfigurationMock;
295             }
296 
297             @Override
298             InattentiveSleepWarningController createInattentiveSleepWarningController() {
299                 return mInattentiveSleepWarningControllerMock;
300             }
301 
302             @Override
303             public SystemPropertiesWrapper createSystemPropertiesWrapper() {
304                 return mSystemPropertiesMock;
305             }
306 
307             @Override
308             PowerManagerService.Clock createClock() {
309                 return new PowerManagerService.Clock() {
310                     @Override
311                     public long uptimeMillis() {
312                         return mClock.now();
313                     }
314 
315                     @Override
316                     public long elapsedRealtime() {
317                         mLastElapsedRealtime = mClock.now();
318                         return mLastElapsedRealtime;
319                     }
320                 };
321             }
322 
323             @Override
324             Handler createHandler(Looper looper, Handler.Callback callback) {
325                 return new Handler(mTestLooper.getLooper(), callback);
326             }
327 
328             @Override
329             void invalidateIsInteractiveCaches() {
330                 try {
331                     mInvalidateInteractiveCachesMock.call();
332                 } catch (Exception e) {
333                     throw new RuntimeException(e);
334                 }
335             }
336 
337             @Override
338             LowPowerStandbyController createLowPowerStandbyController(Context context,
339                     Looper looper) {
340                 return mLowPowerStandbyControllerMock;
341             }
342 
343             @Override
344             PowerManagerService.PermissionCheckerWrapper createPermissionCheckerWrapper() {
345                 return mPermissionCheckerWrapperMock;
346             }
347 
348             @Override
349             PowerManagerService.PowerPropertiesWrapper createPowerPropertiesWrapper() {
350                 return mPowerPropertiesWrapper;
351             }
352 
353             @Override
354             DeviceConfigParameterProvider createDeviceConfigParameterProvider() {
355                 return mDeviceParameterProvider;
356             }
357         });
358         return mService;
359     }
360 
361     @After
tearDown()362     public void tearDown() throws Exception {
363         LocalServices.removeServiceForTest(LightsManager.class);
364         LocalServices.removeServiceForTest(DisplayManagerInternal.class);
365         LocalServices.removeServiceForTest(BatteryManagerInternal.class);
366         LocalServices.removeServiceForTest(ActivityManagerInternal.class);
367         FakeSettingsProvider.clearSettingsProvider();
368     }
369 
370     /**
371      * Creates a mock and registers it to {@link LocalServices}.
372      */
addLocalServiceMock(Class<T> clazz, T mock)373     private static <T> void addLocalServiceMock(Class<T> clazz, T mock) {
374         LocalServices.removeServiceForTest(clazz);
375         LocalServices.addService(clazz, mock);
376     }
377 
startSystem()378     private void startSystem() {
379         mService.onBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
380 
381         // Grab the BatteryReceiver
382         ArgumentCaptor<BatteryReceiver> batCaptor = ArgumentCaptor.forClass(BatteryReceiver.class);
383         IntentFilter batFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
384         batFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
385         verify(mContextSpy).registerReceiver(batCaptor.capture(),
386                 argThat(new IntentFilterMatcher(batFilter)), isNull(), isA(Handler.class));
387         mBatteryReceiver = batCaptor.getValue();
388 
389         // Grab the UserSwitchedReceiver
390         ArgumentCaptor<UserSwitchedReceiver> userSwitchedCaptor =
391                 ArgumentCaptor.forClass(UserSwitchedReceiver.class);
392         IntentFilter usFilter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
393         verify(mContextSpy).registerReceiver(userSwitchedCaptor.capture(),
394                 argThat(new IntentFilterMatcher(usFilter)), isNull(), isA(Handler.class));
395         mUserSwitchedReceiver = userSwitchedCaptor.getValue();
396 
397         mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
398     }
399 
forceSleep()400     private void forceSleep() {
401         mService.getBinderServiceInstance().goToSleep(mClock.now(),
402                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
403     }
404 
forceDream()405     private void forceDream() {
406         mService.getBinderServiceInstance().nap(mClock.now());
407     }
408 
forceAwake()409     private void forceAwake() {
410         mService.getBinderServiceInstance().wakeUp(mClock.now(),
411                 PowerManager.WAKE_REASON_UNKNOWN, "testing IPowerManager.wakeUp()", "pkg.name");
412     }
413 
forceDozing()414     private void forceDozing() {
415         mService.getBinderServiceInstance().goToSleep(mClock.now(),
416                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0);
417     }
418 
setPluggedIn(boolean isPluggedIn)419     private void setPluggedIn(boolean isPluggedIn) {
420         // Set the callback to return the new state
421         when(mBatteryManagerInternalMock.isPowered(anyInt()))
422                 .thenReturn(isPluggedIn);
423         // Trigger PowerManager to reread the plug-in state
424         mBatteryReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_BATTERY_CHANGED));
425     }
426 
setBatteryLevel(int batteryLevel)427     private void setBatteryLevel(int batteryLevel) {
428         when(mBatteryManagerInternalMock.getBatteryLevel())
429                 .thenReturn(batteryLevel);
430         mBatteryReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_BATTERY_CHANGED));
431     }
432 
setBatteryHealth(int batteryHealth)433     private void setBatteryHealth(int batteryHealth) {
434         when(mBatteryManagerInternalMock.getBatteryHealth())
435                 .thenReturn(batteryHealth);
436         mBatteryReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_BATTERY_CHANGED));
437     }
438 
setAttentiveTimeout(int attentiveTimeoutMillis)439     private void setAttentiveTimeout(int attentiveTimeoutMillis) {
440         Settings.Secure.putInt(
441                 mContextSpy.getContentResolver(), Settings.Secure.ATTENTIVE_TIMEOUT,
442                 attentiveTimeoutMillis);
443     }
444 
setAttentiveWarningDuration(int attentiveWarningDurationMillis)445     private void setAttentiveWarningDuration(int attentiveWarningDurationMillis) {
446         when(mResourcesSpy.getInteger(
447                 com.android.internal.R.integer.config_attentiveWarningDuration))
448                 .thenReturn(attentiveWarningDurationMillis);
449     }
450 
setMinimumScreenOffTimeoutConfig(int minimumScreenOffTimeoutConfigMillis)451     private void setMinimumScreenOffTimeoutConfig(int minimumScreenOffTimeoutConfigMillis) {
452         when(mResourcesSpy.getInteger(
453                 com.android.internal.R.integer.config_minimumScreenOffTimeout))
454                 .thenReturn(minimumScreenOffTimeoutConfigMillis);
455     }
456 
setDreamsDisabledByAmbientModeSuppressionConfig(boolean disable)457     private void setDreamsDisabledByAmbientModeSuppressionConfig(boolean disable) {
458         when(mResourcesSpy.getBoolean(
459                 com.android.internal.R.bool.config_dreamsDisabledByAmbientModeSuppressionConfig))
460                 .thenReturn(disable);
461     }
462 
setDreamsBatteryLevelDrainConfig(int threshold)463     private void setDreamsBatteryLevelDrainConfig(int threshold) {
464         when(mResourcesSpy.getInteger(
465                 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff)).thenReturn(
466                 threshold);
467     }
468 
advanceTime(long timeMs)469     private void advanceTime(long timeMs) {
470         mClock.fastForward(timeMs);
471         mTestLooper.dispatchAll();
472     }
473 
474     @Test
testCreateService_initializesNativeServiceAndSetsPowerModes()475     public void testCreateService_initializesNativeServiceAndSetsPowerModes() {
476         PowerManagerService service = createService();
477         verify(mNativeWrapperMock).nativeInit(same(service));
478         verify(mNativeWrapperMock).nativeSetPowerMode(eq(Mode.INTERACTIVE), eq(true));
479         verify(mNativeWrapperMock).nativeSetPowerMode(eq(Mode.DOUBLE_TAP_TO_WAKE), eq(false));
480     }
481 
482     @Test
testGetLastShutdownReasonInternal()483     public void testGetLastShutdownReasonInternal() {
484         when(mSystemPropertiesMock.get(eq(SYSTEM_PROPERTY_REBOOT_REASON), any())).thenReturn(
485                 "shutdown,thermal");
486         createService();
487         int reason = mService.getLastShutdownReasonInternal();
488         assertThat(reason).isEqualTo(PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN);
489     }
490 
491     @Test
testWakefulnessAwake_InitialValue()492     public void testWakefulnessAwake_InitialValue() {
493         createService();
494         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
495     }
496 
497     @Test
testWakefulnessSleep_NoDozeSleepFlag()498     public void testWakefulnessSleep_NoDozeSleepFlag() {
499         createService();
500         // Start with AWAKE state
501         startSystem();
502         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
503 
504         // Take a nap and verify.
505         mService.getBinderServiceInstance().goToSleep(mClock.now(),
506                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
507         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
508     }
509 
510     @Test
testWakefulnessSleep_SoftSleepFlag_NoWakelocks()511     public void testWakefulnessSleep_SoftSleepFlag_NoWakelocks() {
512         createService();
513         // Start with AWAKE state
514         startSystem();
515         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
516 
517         // Take a nap and verify we go to sleep.
518         mService.getBinderServiceInstance().goToSleep(mClock.now(),
519                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION,
520                 PowerManager.GO_TO_SLEEP_FLAG_SOFT_SLEEP);
521         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
522     }
523 
524     @Test
testWakefulnessSleep_SoftSleepFlag_WithPartialWakelock()525     public void testWakefulnessSleep_SoftSleepFlag_WithPartialWakelock() {
526         createService();
527         // Start with AWAKE state
528         startSystem();
529         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
530 
531         // Grab a wakelock
532         final String tag = "wakelock1";
533         final String packageName = "pkg.name";
534         final IBinder token = new Binder();
535         final int flags = PowerManager.PARTIAL_WAKE_LOCK;
536         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
537                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY,
538                 null /* callback */);
539 
540         // Take a nap and verify we stay awake.
541         mService.getBinderServiceInstance().goToSleep(mClock.now(),
542                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION,
543                 PowerManager.GO_TO_SLEEP_FLAG_SOFT_SLEEP);
544         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
545     }
546 
547     @Test
testWakefulnessSleep_SoftSleepFlag_WithFullWakelock()548     public void testWakefulnessSleep_SoftSleepFlag_WithFullWakelock() {
549         createService();
550         // Start with AWAKE state
551         startSystem();
552         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
553 
554         // Grab a wakelock
555         final String tag = "wakelock1";
556         final String packageName = "pkg.name";
557         final IBinder token = new Binder();
558         final int flags = PowerManager.FULL_WAKE_LOCK;
559         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
560                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY,
561                 null /* callback */);
562 
563         // Take a nap and verify we stay awake.
564         mService.getBinderServiceInstance().goToSleep(mClock.now(),
565                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION,
566                 PowerManager.GO_TO_SLEEP_FLAG_SOFT_SLEEP);
567         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
568     }
569 
570     @Test
testWakefulnessSleep_SoftSleepFlag_WithScreenBrightWakelock()571     public void testWakefulnessSleep_SoftSleepFlag_WithScreenBrightWakelock() {
572         createService();
573         // Start with AWAKE state
574         startSystem();
575         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
576 
577         // Grab a wakelock
578         final String tag = "wakelock1";
579         final String packageName = "pkg.name";
580         final IBinder token = new Binder();
581         final int flags = PowerManager.SCREEN_BRIGHT_WAKE_LOCK;
582         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
583                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY,
584                 null /* callback */);
585 
586         // Take a nap and verify we stay awake.
587         mService.getBinderServiceInstance().goToSleep(mClock.now(),
588                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION,
589                 PowerManager.GO_TO_SLEEP_FLAG_SOFT_SLEEP);
590         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
591     }
592     @Test
testWakefulnessSleep_SoftSleepFlag_WithScreenDimWakelock()593     public void testWakefulnessSleep_SoftSleepFlag_WithScreenDimWakelock() {
594         createService();
595         // Start with AWAKE state
596         startSystem();
597         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
598 
599         // Grab a wakelock
600         final String tag = "wakelock1";
601         final String packageName = "pkg.name";
602         final IBinder token = new Binder();
603         final int flags = PowerManager.SCREEN_DIM_WAKE_LOCK;
604         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
605                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY,
606                 null /* callback */);
607 
608         // Take a nap and verify we stay awake.
609         mService.getBinderServiceInstance().goToSleep(mClock.now(),
610                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION,
611                 PowerManager.GO_TO_SLEEP_FLAG_SOFT_SLEEP);
612         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
613     }
614 
615     @Test
616     @EnableCompatChanges({PowerManagerService.REQUIRE_TURN_SCREEN_ON_PERMISSION})
testWakefulnessAwake_AcquireCausesWakeup_turnScreenOnAllowed()617     public void testWakefulnessAwake_AcquireCausesWakeup_turnScreenOnAllowed() {
618         createService();
619         startSystem();
620         forceSleep();
621 
622         IBinder token = new Binder();
623         String tag = "acq_causes_wakeup";
624         String packageName = "pkg.name";
625         AttributionSource attrSrc = new AttributionSource(Binder.getCallingUid(),
626                 packageName, /* attributionTag= */ null);
627 
628         doReturn(PermissionChecker.PERMISSION_GRANTED).when(
629                 mPermissionCheckerWrapperMock).checkPermissionForDataDelivery(any(),
630                 eq(android.Manifest.permission.TURN_SCREEN_ON), anyInt(), eq(attrSrc), anyString());
631 
632         // First, ensure that a normal full wake lock does not cause a wakeup
633         int flags = PowerManager.FULL_WAKE_LOCK;
634         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
635                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
636         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
637         mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
638 
639         // Ensure that the flag does *NOT* work with a partial wake lock.
640         flags = PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
641         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
642                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
643         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
644         mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
645 
646         // Verify that flag forces a wakeup when paired to a FULL_WAKE_LOCK
647         flags = PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
648         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
649                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
650         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
651         mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
652     }
653 
654     @Test
655     @DisableCompatChanges({PowerManagerService.REQUIRE_TURN_SCREEN_ON_PERMISSION})
testWakefulnessAwake_AcquireCausesWakeupOldSdk_turnScreenOnAllowed()656     public void testWakefulnessAwake_AcquireCausesWakeupOldSdk_turnScreenOnAllowed() {
657         createService();
658         startSystem();
659         forceSleep();
660 
661         IBinder token = new Binder();
662         String tag = "acq_causes_wakeup";
663         String packageName = "pkg.name";
664         AttributionSource attrSrc = new AttributionSource(Binder.getCallingUid(),
665                 packageName, /* attributionTag= */ null);
666 
667         // verify that the wakeup is allowed for apps targeting older sdks, and therefore won't have
668         // the TURN_SCREEN_ON permission granted
669         doReturn(PermissionChecker.PERMISSION_HARD_DENIED).when(
670                 mPermissionCheckerWrapperMock).checkPermissionForDataDelivery(any(),
671                 eq(android.Manifest.permission.TURN_SCREEN_ON), anyInt(), eq(attrSrc), anyString());
672 
673         doReturn(false).when(mPowerPropertiesWrapper).waive_target_sdk_check_for_turn_screen_on();
674 
675         int flags = PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
676         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
677                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
678         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
679         mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
680     }
681 
682     @Test
683     @EnableCompatChanges({PowerManagerService.REQUIRE_TURN_SCREEN_ON_PERMISSION})
testWakefulnessAwake_AcquireCausesWakeup_turnScreenOnDenied()684     public void testWakefulnessAwake_AcquireCausesWakeup_turnScreenOnDenied() {
685         createService();
686         startSystem();
687         forceSleep();
688 
689         IBinder token = new Binder();
690         String tag = "acq_causes_wakeup";
691         String packageName = "pkg.name";
692         AttributionSource attrSrc = new AttributionSource(Binder.getCallingUid(),
693                 packageName, /* attributionTag= */ null);
694         doReturn(PermissionChecker.PERMISSION_HARD_DENIED).when(
695                 mPermissionCheckerWrapperMock).checkPermissionForDataDelivery(any(),
696                 eq(android.Manifest.permission.TURN_SCREEN_ON), anyInt(), eq(attrSrc), anyString());
697 
698         doReturn(false).when(mPowerPropertiesWrapper).waive_target_sdk_check_for_turn_screen_on();
699         doReturn(false).when(mPowerPropertiesWrapper).permissionless_turn_screen_on();
700 
701         // Verify that flag has no effect when TURN_SCREEN_ON is not allowed for apps targeting U+
702         int flags = PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
703         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
704                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
705         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
706         mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
707     }
708 
709     @Test
710     @EnableCompatChanges({PowerManagerService.REQUIRE_TURN_SCREEN_ON_PERMISSION})
testWakefulnessAwake_AcquireCausesWakeupOldSdk_turnScreenOnDenied()711     public void testWakefulnessAwake_AcquireCausesWakeupOldSdk_turnScreenOnDenied() {
712         createService();
713         startSystem();
714         forceSleep();
715 
716         IBinder token = new Binder();
717         String tag = "acq_causes_wakeup";
718         String packageName = "pkg.name";
719         AttributionSource attrSrc = new AttributionSource(Binder.getCallingUid(),
720                 packageName, /* attributionTag= */ null);
721         doReturn(PermissionChecker.PERMISSION_HARD_DENIED).when(
722                 mPermissionCheckerWrapperMock).checkPermissionForDataDelivery(any(),
723                 eq(android.Manifest.permission.TURN_SCREEN_ON), anyInt(), eq(attrSrc), anyString());
724 
725         doReturn(true).when(mPowerPropertiesWrapper).waive_target_sdk_check_for_turn_screen_on();
726 
727         // Verify that flag has no effect when TURN_SCREEN_ON is not allowed for apps targeting U+
728         int flags = PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
729         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
730                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
731         if (PowerProperties.permissionless_turn_screen_on().orElse(false)) {
732             assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
733         } else {
734             assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
735         }
736         mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
737     }
738 
739     @Test
testWakefulnessAwake_IPowerManagerWakeUp()740     public void testWakefulnessAwake_IPowerManagerWakeUp() {
741         createService();
742         startSystem();
743         forceSleep();
744         mService.getBinderServiceInstance().wakeUp(mClock.now(),
745                 PowerManager.WAKE_REASON_UNKNOWN, "testing IPowerManager.wakeUp()", "pkg.name");
746         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
747     }
748 
749     /**
750      * Tests a series of variants that control whether a device wakes-up when it is plugged in
751      * or docked.
752      */
753     @Test
testWakefulnessAwake_ShouldWakeUpWhenPluggedIn()754     public void testWakefulnessAwake_ShouldWakeUpWhenPluggedIn() {
755         createService();
756         startSystem();
757         forceSleep();
758 
759         // Test 1:
760         // Set config to prevent it wake up, test, verify, reset config value.
761         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
762                 .thenReturn(false);
763         mService.readConfigurationLocked();
764         setPluggedIn(true);
765         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
766         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
767                 .thenReturn(true);
768         mService.readConfigurationLocked();
769 
770         // Test 2:
771         // Turn the power off, sleep, then plug into a wireless charger.
772         // Verify that we do not wake up if the phone is being plugged into a wireless charger.
773         setPluggedIn(false);
774         forceSleep();
775         when(mBatteryManagerInternalMock.getPlugType())
776                 .thenReturn(BatteryManager.BATTERY_PLUGGED_WIRELESS);
777         when(mWirelessChargerDetectorMock.update(true /* isPowered */,
778                 BatteryManager.BATTERY_PLUGGED_WIRELESS)).thenReturn(false);
779         setPluggedIn(true);
780         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
781 
782         // Test 3:
783         // Do not wake up if the phone is being REMOVED from a wireless charger
784         when(mBatteryManagerInternalMock.getPlugType()).thenReturn(0);
785         setPluggedIn(false);
786         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
787 
788         // Test 4:
789         // Do not wake if we are dreaming.
790         forceAwake();  // Needs to be awake first before it can dream.
791         forceDream();
792         setPluggedIn(true);
793         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
794         forceSleep();
795 
796         // Test 5:
797         // Don't wake if the device is configured not to wake up in theater mode (and theater
798         // mode is enabled).
799         Settings.Global.putInt(
800                 mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 1);
801         mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
802         when(mResourcesSpy.getBoolean(
803                 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug))
804                 .thenReturn(false);
805         setPluggedIn(false);
806         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
807         Settings.Global.putInt(
808                 mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 0);
809         mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
810 
811         // Test 6:
812         // Don't wake up if we are Dozing away and always-on is enabled.
813         when(mAmbientDisplayConfigurationMock.alwaysOnEnabled(UserHandle.USER_CURRENT))
814                 .thenReturn(true);
815         mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
816         forceAwake();
817         forceDozing();
818         setPluggedIn(true);
819         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
820 
821         // Test 7:
822         // Finally, take away all the factors above and ensure the device wakes up!
823         forceAwake();
824         forceSleep();
825         setPluggedIn(false);
826         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
827     }
828 
829     /**
830      * Tests that dreaming stops when undocking and not configured to keep dreaming.
831      */
832     @Test
testWakefulnessDream_shouldStopDreamingWhenUndocked_whenNotConfigured()833     public void testWakefulnessDream_shouldStopDreamingWhenUndocked_whenNotConfigured() {
834         // Make sure "unplug turns on screen" is configured to true.
835         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
836                 .thenReturn(true);
837 
838         createService();
839         startSystem();
840 
841         ArgumentCaptor<DreamManagerInternal.DreamManagerStateListener> dreamManagerStateListener =
842                 ArgumentCaptor.forClass(DreamManagerInternal.DreamManagerStateListener.class);
843         verify(mDreamManagerInternalMock).registerDreamManagerStateListener(
844                 dreamManagerStateListener.capture());
845         dreamManagerStateListener.getValue().onKeepDreamingWhenUnpluggingChanged(false);
846 
847         when(mBatteryManagerInternalMock.getPlugType())
848                 .thenReturn(BatteryManager.BATTERY_PLUGGED_DOCK);
849         setPluggedIn(true);
850 
851         forceAwake();  // Needs to be awake first before it can dream.
852         forceDream();
853         when(mBatteryManagerInternalMock.getPlugType()).thenReturn(0);
854         setPluggedIn(false);
855 
856         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
857     }
858 
859     /**
860      * Tests that dreaming continues when undocking and configured to do so.
861      */
862     @Test
testWakefulnessDream_shouldKeepDreamingWhenUndocked_whenConfigured()863     public void testWakefulnessDream_shouldKeepDreamingWhenUndocked_whenConfigured() {
864         // Make sure "unplug turns on screen" is configured to true.
865         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
866                 .thenReturn(true);
867 
868         createService();
869         startSystem();
870 
871         ArgumentCaptor<DreamManagerInternal.DreamManagerStateListener> dreamManagerStateListener =
872                 ArgumentCaptor.forClass(DreamManagerInternal.DreamManagerStateListener.class);
873         verify(mDreamManagerInternalMock).registerDreamManagerStateListener(
874                 dreamManagerStateListener.capture());
875         dreamManagerStateListener.getValue().onKeepDreamingWhenUnpluggingChanged(true);
876 
877         when(mBatteryManagerInternalMock.getPlugType())
878                 .thenReturn(BatteryManager.BATTERY_PLUGGED_DOCK);
879         setPluggedIn(true);
880 
881         forceAwake();  // Needs to be awake first before it can dream.
882         forceDream();
883         when(mBatteryManagerInternalMock.getPlugType()).thenReturn(0);
884         setPluggedIn(false);
885 
886         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
887     }
888 
889     /**
890      * Tests that dreaming stops when undocking while showing a dream that prevents it.
891      */
892     @Test
testWakefulnessDream_shouldStopDreamingWhenUndocked_whenDreamPrevents()893     public void testWakefulnessDream_shouldStopDreamingWhenUndocked_whenDreamPrevents() {
894         // Make sure "unplug turns on screen" is configured to true.
895         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
896                 .thenReturn(true);
897 
898         createService();
899         startSystem();
900 
901         ArgumentCaptor<DreamManagerInternal.DreamManagerStateListener> dreamManagerStateListener =
902                 ArgumentCaptor.forClass(DreamManagerInternal.DreamManagerStateListener.class);
903         verify(mDreamManagerInternalMock).registerDreamManagerStateListener(
904                 dreamManagerStateListener.capture());
905         dreamManagerStateListener.getValue().onKeepDreamingWhenUnpluggingChanged(true);
906 
907         when(mBatteryManagerInternalMock.getPlugType())
908                 .thenReturn(BatteryManager.BATTERY_PLUGGED_DOCK);
909         setPluggedIn(true);
910 
911         forceAwake();  // Needs to be awake first before it can dream.
912         forceDream();
913         dreamManagerStateListener.getValue().onKeepDreamingWhenUnpluggingChanged(false);
914         when(mBatteryManagerInternalMock.getPlugType()).thenReturn(0);
915         setPluggedIn(false);
916 
917         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
918     }
919 
920     @Test
testWakefulnessDream_shouldStopDreamingWhenUnplugging_whenDreamPrevents()921     public void testWakefulnessDream_shouldStopDreamingWhenUnplugging_whenDreamPrevents() {
922         // Make sure "unplug turns on screen" is configured to true.
923         when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
924                 .thenReturn(true);
925 
926         createService();
927         startSystem();
928 
929         ArgumentCaptor<DreamManagerInternal.DreamManagerStateListener> dreamManagerStateListener =
930                 ArgumentCaptor.forClass(DreamManagerInternal.DreamManagerStateListener.class);
931         verify(mDreamManagerInternalMock).registerDreamManagerStateListener(
932                 dreamManagerStateListener.capture());
933 
934         when(mBatteryManagerInternalMock.getPlugType())
935                 .thenReturn(BatteryManager.BATTERY_PLUGGED_AC);
936         setPluggedIn(true);
937 
938         forceAwake();  // Needs to be awake first before it can dream.
939         forceDream();
940         dreamManagerStateListener.getValue().onKeepDreamingWhenUnpluggingChanged(false);
941         when(mBatteryManagerInternalMock.getPlugType()).thenReturn(0);
942         setPluggedIn(false);
943 
944         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
945     }
946 
947 
948     @Test
testWakefulnessDoze_goToSleep()949     public void testWakefulnessDoze_goToSleep() {
950         createService();
951         // Start with AWAKE state
952         startSystem();
953         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
954 
955         // Take a nap and verify.
956         mService.getBinderServiceInstance().goToSleep(mClock.now(),
957                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0);
958         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
959     }
960 
961     @Test
testWasDeviceIdleFor_true()962     public void testWasDeviceIdleFor_true() {
963         int interval = 1000;
964         createService();
965         startSystem();
966         mService.onUserActivity();
967         advanceTime(interval + 1 /* just a little more */);
968         assertThat(mService.wasDeviceIdleForInternal(interval)).isTrue();
969     }
970 
971     @Test
testWasDeviceIdleFor_false()972     public void testWasDeviceIdleFor_false() {
973         int interval = 1000;
974         createService();
975         startSystem();
976         mService.onUserActivity();
977         assertThat(mService.wasDeviceIdleForInternal(interval)).isFalse();
978     }
979 
980     @Test
testForceSuspend_putsDeviceToSleep()981     public void testForceSuspend_putsDeviceToSleep() {
982         createService();
983         startSystem();
984 
985         // Verify that we start awake
986         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
987 
988         // Grab the wakefulness value when PowerManager finally calls into the
989         // native component to actually perform the suspend.
990         when(mNativeWrapperMock.nativeForceSuspend()).then(inv -> {
991             assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
992             return true;
993         });
994 
995         boolean retval = mService.getBinderServiceInstance().forceSuspend();
996         assertThat(retval).isTrue();
997 
998         // Still asleep when the function returns.
999         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1000     }
1001 
1002     @Test
testForceSuspend_wakeLocksDisabled()1003     public void testForceSuspend_wakeLocksDisabled() {
1004         final String tag = "TestWakelockTag_098213";
1005         final int flags = PowerManager.PARTIAL_WAKE_LOCK;
1006         final String pkg = mContextSpy.getOpPackageName();
1007 
1008         createService();
1009 
1010         // Set up the Notification mock to keep track of the wakelocks that are currently
1011         // active or disabled. We'll use this to verify that wakelocks are disabled when
1012         // they should be.
1013         final Map<String, Integer> wakelockMap = new HashMap<>(1);
1014         doAnswer(inv -> {
1015             wakelockMap.put((String) inv.getArguments()[1], (int) inv.getArguments()[0]);
1016             return null;
1017         }).when(mNotifierMock).onWakeLockAcquired(anyInt(), anyString(), anyString(), anyInt(),
1018                 anyInt(), any(), any(), any());
1019         doAnswer(inv -> {
1020             wakelockMap.remove((String) inv.getArguments()[1]);
1021             return null;
1022         }).when(mNotifierMock).onWakeLockReleased(anyInt(), anyString(), anyString(), anyInt(),
1023                 anyInt(), any(), any(), any());
1024 
1025         //
1026         // TEST STARTS HERE
1027         //
1028         startSystem();
1029 
1030         // Verify that we start awake
1031         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1032 
1033         // Create a wakelock
1034         mService.getBinderServiceInstance().acquireWakeLock(new Binder(), flags, tag, pkg,
1035                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
1036         assertThat(wakelockMap.get(tag)).isEqualTo(flags);  // Verify wakelock is active.
1037 
1038         // Confirm that the wakelocks have been disabled when the forceSuspend is in flight.
1039         when(mNativeWrapperMock.nativeForceSuspend()).then(inv -> {
1040             // Verify that the wakelock is disabled by the time we get to the native force
1041             // suspend call.
1042             assertThat(wakelockMap.containsKey(tag)).isFalse();
1043             return true;
1044         });
1045 
1046         assertThat(mService.getBinderServiceInstance().forceSuspend()).isTrue();
1047         assertThat(wakelockMap.get(tag)).isEqualTo(flags);
1048 
1049     }
1050 
1051     @Test
testForceSuspend_forceSuspendFailurePropagated()1052     public void testForceSuspend_forceSuspendFailurePropagated() {
1053         createService();
1054         startSystem();
1055         when(mNativeWrapperMock.nativeForceSuspend()).thenReturn(false);
1056         assertThat(mService.getBinderServiceInstance().forceSuspend()).isFalse();
1057     }
1058 
1059     @SuppressWarnings("GuardedBy")
1060     @Test
testScreensaverActivateOnSleepDisabled_powered_afterTimeout_goesToDozing()1061     public void testScreensaverActivateOnSleepDisabled_powered_afterTimeout_goesToDozing() {
1062         when(mBatteryManagerInternalMock.isPowered(anyInt())).thenReturn(true);
1063 
1064         doAnswer(inv -> {
1065             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1066             return null;
1067         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
1068 
1069         setMinimumScreenOffTimeoutConfig(5);
1070         createService();
1071         startSystem();
1072 
1073         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1074 
1075         advanceTime(15000);
1076         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
1077     }
1078 
1079     @SuppressWarnings("GuardedBy")
1080     @Test
testScreensaverActivateOnSleepEnabled_powered_afterTimeout_goesToDreaming()1081     public void testScreensaverActivateOnSleepEnabled_powered_afterTimeout_goesToDreaming() {
1082         when(mBatteryManagerInternalMock.isPowered(anyInt())).thenReturn(true);
1083         Settings.Secure.putInt(mContextSpy.getContentResolver(),
1084                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
1085 
1086         doAnswer(inv -> {
1087             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1088             return null;
1089         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
1090 
1091         setMinimumScreenOffTimeoutConfig(5);
1092         createService();
1093         startSystem();
1094 
1095         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1096 
1097         advanceTime(15000);
1098         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1099     }
1100 
1101     @SuppressWarnings("GuardedBy")
1102     @Test
testAmbientSuppression_disablesDreamingAndWakesDevice()1103     public void testAmbientSuppression_disablesDreamingAndWakesDevice() {
1104         Settings.Secure.putInt(mContextSpy.getContentResolver(),
1105                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
1106 
1107         setDreamsDisabledByAmbientModeSuppressionConfig(true);
1108         setMinimumScreenOffTimeoutConfig(10000);
1109         createService();
1110         startSystem();
1111 
1112         doAnswer(inv -> {
1113             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1114             return null;
1115         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
1116 
1117         setPluggedIn(true);
1118         // Allow asynchronous sandman calls to execute.
1119         advanceTime(10000);
1120 
1121         forceDream();
1122         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1123         mService.getBinderServiceInstance().suppressAmbientDisplay("test", true);
1124         advanceTime(50);
1125         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1126     }
1127 
1128     @SuppressWarnings("GuardedBy")
1129     @Test
testAmbientSuppressionDisabled_shouldNotWakeDevice()1130     public void testAmbientSuppressionDisabled_shouldNotWakeDevice() {
1131         Settings.Secure.putInt(mContextSpy.getContentResolver(),
1132                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
1133 
1134         setDreamsDisabledByAmbientModeSuppressionConfig(false);
1135         setMinimumScreenOffTimeoutConfig(10000);
1136         createService();
1137         startSystem();
1138 
1139         doAnswer(inv -> {
1140             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1141             return null;
1142         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
1143 
1144         setPluggedIn(true);
1145         // Allow asynchronous sandman calls to execute.
1146         advanceTime(10000);
1147 
1148         forceDream();
1149         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1150         mService.getBinderServiceInstance().suppressAmbientDisplay("test", true);
1151         advanceTime(50);
1152         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1153     }
1154 
1155     @Test
testAmbientSuppression_doesNotAffectDreamForcing()1156     public void testAmbientSuppression_doesNotAffectDreamForcing() {
1157         Settings.Secure.putInt(mContextSpy.getContentResolver(),
1158                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
1159 
1160         setDreamsDisabledByAmbientModeSuppressionConfig(true);
1161         setMinimumScreenOffTimeoutConfig(10000);
1162         createService();
1163         startSystem();
1164 
1165         doAnswer(inv -> {
1166             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1167             return null;
1168         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
1169 
1170         mService.getBinderServiceInstance().suppressAmbientDisplay("test", true);
1171         setPluggedIn(true);
1172         // Allow asynchronous sandman calls to execute.
1173         advanceTime(10000);
1174 
1175         // Verify that forcing dream still works even though ambient display is suppressed
1176         forceDream();
1177         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1178     }
1179 
1180     @Test
testBatteryDrainDuringDream()1181     public void testBatteryDrainDuringDream() {
1182         Settings.Secure.putInt(mContextSpy.getContentResolver(),
1183                 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP, 1);
1184 
1185         setMinimumScreenOffTimeoutConfig(100);
1186         setDreamsBatteryLevelDrainConfig(5);
1187         createService();
1188         startSystem();
1189 
1190         doAnswer(inv -> {
1191             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1192             return null;
1193         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
1194 
1195         setBatteryLevel(100);
1196         setPluggedIn(true);
1197 
1198         forceAwake();  // Needs to be awake first before it can dream.
1199         forceDream();
1200         advanceTime(10); // Allow async calls to happen
1201         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1202         setBatteryLevel(90);
1203         advanceTime(10); // Allow async calls to happen
1204         assertThat(mService.getDreamsBatteryLevelDrain()).isEqualTo(10);
1205 
1206         // If battery overheat protection is enabled, we shouldn't count battery drain
1207         setBatteryHealth(BatteryManager.BATTERY_HEALTH_OVERHEAT);
1208         setBatteryLevel(70);
1209         advanceTime(10); // Allow async calls to happen
1210         assertThat(mService.getDreamsBatteryLevelDrain()).isEqualTo(10);
1211     }
1212 
1213     @Test
testSetDozeOverrideFromDreamManager_triggersSuspendBlocker()1214     public void testSetDozeOverrideFromDreamManager_triggersSuspendBlocker() {
1215         final String suspendBlockerName = "PowerManagerService.Display";
1216         final String tag = "acq_causes_wakeup";
1217         final String packageName = "pkg.name";
1218         final IBinder token = new Binder();
1219 
1220         final boolean[] isAcquired = new boolean[1];
1221         doAnswer(inv -> {
1222             if (suspendBlockerName.equals(inv.getArguments()[0])) {
1223                 isAcquired[0] = false;
1224             }
1225             return null;
1226         }).when(mNativeWrapperMock).nativeReleaseSuspendBlocker(any());
1227 
1228         doAnswer(inv -> {
1229             if (suspendBlockerName.equals(inv.getArguments()[0])) {
1230                 isAcquired[0] = true;
1231             }
1232             return null;
1233         }).when(mNativeWrapperMock).nativeAcquireSuspendBlocker(any());
1234 
1235         // Need to create the service after we stub the mocks for this test because some of the
1236         // mocks are used during the constructor.
1237         createService();
1238 
1239         // Start with AWAKE state
1240         startSystem();
1241         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1242         assertTrue(isAcquired[0]);
1243 
1244         // Take a nap and verify we no longer hold the blocker
1245         int flags = PowerManager.DOZE_WAKE_LOCK;
1246         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
1247                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
1248         when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1249         mService.getBinderServiceInstance().goToSleep(mClock.now(),
1250                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0);
1251         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
1252         assertFalse(isAcquired[0]);
1253 
1254         // Override the display state by DreamManager and verify is reacquires the blocker.
1255         mService.getLocalServiceInstance()
1256                 .setDozeOverrideFromDreamManager(Display.STATE_ON, PowerManager.BRIGHTNESS_DEFAULT);
1257         assertTrue(isAcquired[0]);
1258     }
1259 
1260     @Test
testSuspendBlockerHeldDuringBoot()1261     public void testSuspendBlockerHeldDuringBoot() {
1262         final String suspendBlockerName = "PowerManagerService.Booting";
1263 
1264         final boolean[] isAcquired = new boolean[1];
1265         doAnswer(inv -> {
1266             isAcquired[0] = false;
1267             return null;
1268         }).when(mNativeWrapperMock).nativeReleaseSuspendBlocker(eq(suspendBlockerName));
1269 
1270         doAnswer(inv -> {
1271             isAcquired[0] = true;
1272             return null;
1273         }).when(mNativeWrapperMock).nativeAcquireSuspendBlocker(eq(suspendBlockerName));
1274 
1275         // Need to create the service after we stub the mocks for this test because some of the
1276         // mocks are used during the constructor.
1277         createService();
1278         assertTrue(isAcquired[0]);
1279 
1280         mService.onBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
1281         assertTrue(isAcquired[0]);
1282 
1283         mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
1284         assertFalse(isAcquired[0]);
1285     }
1286 
1287     @Test
testInattentiveSleep_hideWarningIfStayOnIsEnabledAndPluggedIn()1288     public void testInattentiveSleep_hideWarningIfStayOnIsEnabledAndPluggedIn() {
1289         setMinimumScreenOffTimeoutConfig(5);
1290         setAttentiveWarningDuration(120);
1291         setAttentiveTimeout(100);
1292 
1293         Settings.Global.putInt(mContextSpy.getContentResolver(),
1294                 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
1295 
1296         createService();
1297         startSystem();
1298 
1299         verify(mInattentiveSleepWarningControllerMock, times(1)).show();
1300         verify(mInattentiveSleepWarningControllerMock, never()).dismiss(anyBoolean());
1301         when(mInattentiveSleepWarningControllerMock.isShown()).thenReturn(true);
1302 
1303         setPluggedIn(true);
1304         verify(mInattentiveSleepWarningControllerMock, atLeastOnce()).dismiss(true);
1305     }
1306 
1307     @Test
testInattentiveSleep_hideWarningIfInattentiveSleepIsDisabled()1308     public void testInattentiveSleep_hideWarningIfInattentiveSleepIsDisabled() {
1309         setMinimumScreenOffTimeoutConfig(5);
1310         setAttentiveWarningDuration(120);
1311         setAttentiveTimeout(100);
1312 
1313         createService();
1314         startSystem();
1315 
1316         verify(mInattentiveSleepWarningControllerMock, times(1)).show();
1317         verify(mInattentiveSleepWarningControllerMock, never()).dismiss(anyBoolean());
1318         when(mInattentiveSleepWarningControllerMock.isShown()).thenReturn(true);
1319 
1320         setAttentiveTimeout(-1);
1321         mService.handleSettingsChangedLocked();
1322 
1323         verify(mInattentiveSleepWarningControllerMock, atLeastOnce()).dismiss(true);
1324     }
1325 
1326     @Test
testInattentiveSleep_userActivityDismissesWarning()1327     public void testInattentiveSleep_userActivityDismissesWarning() {
1328         final DisplayInfo info = new DisplayInfo();
1329         info.displayGroupId = Display.DEFAULT_DISPLAY_GROUP;
1330         when(mDisplayManagerInternalMock.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(info);
1331         setMinimumScreenOffTimeoutConfig(5);
1332         setAttentiveWarningDuration(1900);
1333         setAttentiveTimeout(2000);
1334 
1335         createService();
1336         startSystem();
1337 
1338         mService.getBinderServiceInstance().userActivity(Display.DEFAULT_DISPLAY, mClock.now(),
1339                 PowerManager.USER_ACTIVITY_EVENT_TOUCH, 0);
1340         verify(mInattentiveSleepWarningControllerMock, never()).show();
1341 
1342         advanceTime(150);
1343         verify(mInattentiveSleepWarningControllerMock, times(1)).show();
1344         verify(mInattentiveSleepWarningControllerMock, never()).dismiss(anyBoolean());
1345         when(mInattentiveSleepWarningControllerMock.isShown()).thenReturn(true);
1346 
1347         mService.getBinderServiceInstance().userActivity(Display.DEFAULT_DISPLAY, mClock.now(),
1348                 PowerManager.USER_ACTIVITY_EVENT_TOUCH, 0);
1349         verify(mInattentiveSleepWarningControllerMock, times(1)).dismiss(true);
1350     }
1351 
1352     @Test
testInattentiveSleep_warningHiddenAfterWakingUp()1353     public void testInattentiveSleep_warningHiddenAfterWakingUp() {
1354         setMinimumScreenOffTimeoutConfig(5);
1355         setAttentiveWarningDuration(70);
1356         setAttentiveTimeout(100);
1357 
1358         createService();
1359         startSystem();
1360         advanceTime(50);
1361         verify(mInattentiveSleepWarningControllerMock, atLeastOnce()).show();
1362         when(mInattentiveSleepWarningControllerMock.isShown()).thenReturn(true);
1363         advanceTime(70);
1364         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1365         forceAwake();
1366         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1367         verify(mInattentiveSleepWarningControllerMock, atLeastOnce()).dismiss(false);
1368     }
1369 
1370     @Test
testInattentiveSleep_warningStaysWhenDreaming()1371     public void testInattentiveSleep_warningStaysWhenDreaming() {
1372         setMinimumScreenOffTimeoutConfig(5);
1373         setAttentiveWarningDuration(70);
1374         setAttentiveTimeout(100);
1375         createService();
1376         startSystem();
1377         advanceTime(50);
1378         verify(mInattentiveSleepWarningControllerMock, atLeastOnce()).show();
1379         when(mInattentiveSleepWarningControllerMock.isShown()).thenReturn(true);
1380 
1381         forceDream();
1382         when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1383 
1384         advanceTime(10);
1385         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1386         verify(mInattentiveSleepWarningControllerMock, never()).dismiss(anyBoolean());
1387     }
1388 
1389     @Test
testInattentiveSleep_warningNotShownWhenSleeping()1390     public void testInattentiveSleep_warningNotShownWhenSleeping() {
1391         setMinimumScreenOffTimeoutConfig(5);
1392         setAttentiveWarningDuration(70);
1393         setAttentiveTimeout(100);
1394         createService();
1395         startSystem();
1396 
1397         advanceTime(10);
1398         forceSleep();
1399 
1400         advanceTime(50);
1401         verify(mInattentiveSleepWarningControllerMock, never()).show();
1402     }
1403 
1404     @Test
testInattentiveSleep_noWarningShownIfInattentiveSleepDisabled()1405     public void testInattentiveSleep_noWarningShownIfInattentiveSleepDisabled() {
1406         setAttentiveTimeout(-1);
1407         createService();
1408         startSystem();
1409         verify(mInattentiveSleepWarningControllerMock, never()).show();
1410     }
1411 
1412     @Test
testInattentiveSleep_goesToSleepAfterTimeout()1413     public void testInattentiveSleep_goesToSleepAfterTimeout() {
1414         setMinimumScreenOffTimeoutConfig(5);
1415         setAttentiveTimeout(5);
1416         createService();
1417         startSystem();
1418         advanceTime(20);
1419         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1420         assertThat(mService.getBinderServiceInstance().getLastSleepReason()).isEqualTo(
1421                 PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE);
1422     }
1423 
1424     @Test
testInattentiveSleep_goesToSleepWithWakeLock()1425     public void testInattentiveSleep_goesToSleepWithWakeLock() {
1426         final String pkg = mContextSpy.getOpPackageName();
1427         final Binder token = new Binder();
1428         final String tag = "testInattentiveSleep_goesToSleepWithWakeLock";
1429 
1430         setMinimumScreenOffTimeoutConfig(5);
1431         setAttentiveTimeout(30);
1432         createService();
1433         startSystem();
1434 
1435         mService.getBinderServiceInstance().acquireWakeLock(token,
1436                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK, tag, pkg,
1437                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
1438 
1439         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1440         advanceTime(60);
1441         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1442         assertThat(mService.getBinderServiceInstance().getLastSleepReason()).isEqualTo(
1443                 PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE);
1444     }
1445 
1446     @Test
testInattentiveSleep_dreamEnds_goesToSleepAfterTimeout()1447     public void testInattentiveSleep_dreamEnds_goesToSleepAfterTimeout() {
1448         setMinimumScreenOffTimeoutConfig(5);
1449         setAttentiveTimeout(30000);
1450         createService();
1451         startSystem();
1452 
1453         advanceTime(10000);
1454         forceDream();
1455         advanceTime(10000);
1456         final String pkg = mContextSpy.getOpPackageName();
1457         mService.getBinderServiceInstance().wakeUp(mClock.now(),
1458                 PowerManager.WAKE_REASON_DREAM_FINISHED, "PowerManagerServiceTest:DREAM_FINISHED",
1459                 pkg);
1460         advanceTime(10001);
1461 
1462         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1463         assertThat(mService.getBinderServiceInstance().getLastSleepReason()).isEqualTo(
1464                 PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE);
1465     }
1466 
1467     @Test
testInattentiveSleep_wakeLockOnAfterRelease_inattentiveSleepTimeoutNotAffected()1468     public void testInattentiveSleep_wakeLockOnAfterRelease_inattentiveSleepTimeoutNotAffected() {
1469         final DisplayInfo info = new DisplayInfo();
1470         info.displayGroupId = Display.DEFAULT_DISPLAY_GROUP;
1471         when(mDisplayManagerInternalMock.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(info);
1472 
1473         final String pkg = mContextSpy.getOpPackageName();
1474         final Binder token = new Binder();
1475         final String tag = "testInattentiveSleep_wakeLockOnAfterRelease";
1476 
1477         setMinimumScreenOffTimeoutConfig(5);
1478         setAttentiveTimeout(2000);
1479         createService();
1480         startSystem();
1481 
1482         mService.getBinderServiceInstance().acquireWakeLock(token,
1483                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, tag, pkg,
1484                 null /* workSource */, null /* historyTag */, Display.DEFAULT_DISPLAY, null);
1485 
1486         advanceTime(1500);
1487         mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
1488 
1489         advanceTime(520);
1490         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1491         assertThat(mService.getBinderServiceInstance().getLastSleepReason()).isEqualTo(
1492                 PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE);
1493     }
1494 
1495     @Test
testInattentiveSleep_userActivityNoChangeLights_inattentiveSleepTimeoutNotAffected()1496     public void testInattentiveSleep_userActivityNoChangeLights_inattentiveSleepTimeoutNotAffected() {
1497         final DisplayInfo info = new DisplayInfo();
1498         info.displayGroupId = Display.DEFAULT_DISPLAY_GROUP;
1499         when(mDisplayManagerInternalMock.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(info);
1500 
1501         setMinimumScreenOffTimeoutConfig(5);
1502         setAttentiveTimeout(2000);
1503         createService();
1504         startSystem();
1505 
1506         advanceTime(1500);
1507         mService.getBinderServiceInstance().userActivity(Display.DEFAULT_DISPLAY, mClock.now(),
1508                 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1509                 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS);
1510 
1511         advanceTime(520);
1512         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1513         assertThat(mService.getBinderServiceInstance().getLastSleepReason()).isEqualTo(
1514                 PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE);
1515     }
1516 
1517     @Test
testInattentiveSleep_userActivity_inattentiveSleepTimeoutExtended()1518     public void testInattentiveSleep_userActivity_inattentiveSleepTimeoutExtended() {
1519         final DisplayInfo info = new DisplayInfo();
1520         info.displayGroupId = Display.DEFAULT_DISPLAY_GROUP;
1521         when(mDisplayManagerInternalMock.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(info);
1522 
1523         setMinimumScreenOffTimeoutConfig(5);
1524         setAttentiveTimeout(2000);
1525         createService();
1526         startSystem();
1527 
1528         advanceTime(1500);
1529         mService.getBinderServiceInstance().userActivity(Display.DEFAULT_DISPLAY, mClock.now(),
1530                 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0 /* flags */);
1531 
1532         advanceTime(520);
1533         assertThat(mService.getGlobalWakefulnessLocked()).isNotEqualTo(WAKEFULNESS_ASLEEP);
1534     }
1535 
1536 
1537     @SuppressWarnings("GuardedBy")
1538     @Test
testInattentiveSleep_goesToSleepFromDream()1539     public void testInattentiveSleep_goesToSleepFromDream() {
1540         setAttentiveTimeout(20000);
1541         createService();
1542         startSystem();
1543         setPluggedIn(true);
1544         forceAwake();
1545         forceDream();
1546         when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1547         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
1548 
1549         advanceTime(20500);
1550         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1551     }
1552 
1553     @Test
testWakeLock_affectsProperDisplayGroup()1554     public void testWakeLock_affectsProperDisplayGroup() {
1555         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
1556         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
1557                 new AtomicReference<>();
1558         doAnswer((Answer<Void>) invocation -> {
1559             listener.set(invocation.getArgument(0));
1560             return null;
1561         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
1562         final DisplayInfo info = new DisplayInfo();
1563         info.displayGroupId = Display.DEFAULT_DISPLAY_GROUP;
1564         when(mDisplayManagerInternalMock.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(info);
1565 
1566         final String pkg = mContextSpy.getOpPackageName();
1567         final Binder token = new Binder();
1568         final String tag = "testWakeLock_affectsProperDisplayGroup";
1569 
1570         setMinimumScreenOffTimeoutConfig(5);
1571         createService();
1572         startSystem();
1573         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
1574 
1575         mService.getBinderServiceInstance().acquireWakeLock(token,
1576                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK, tag, pkg,
1577                 null /* workSource */, null /* historyTag */, Display.DEFAULT_DISPLAY, null);
1578 
1579         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1580         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
1581                 WAKEFULNESS_AWAKE);
1582         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
1583                 WAKEFULNESS_AWAKE);
1584 
1585         advanceTime(15000);
1586         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1587         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
1588                 WAKEFULNESS_AWAKE);
1589         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
1590                 WAKEFULNESS_DOZING);
1591     }
1592 
1593     @Test
testInvalidDisplayGroupWakeLock_affectsAllDisplayGroups()1594     public void testInvalidDisplayGroupWakeLock_affectsAllDisplayGroups() {
1595         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
1596         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
1597                 new AtomicReference<>();
1598         doAnswer((Answer<Void>) invocation -> {
1599             listener.set(invocation.getArgument(0));
1600             return null;
1601         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
1602         final DisplayInfo info = new DisplayInfo();
1603         info.displayGroupId = Display.DEFAULT_DISPLAY_GROUP;
1604         when(mDisplayManagerInternalMock.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(info);
1605 
1606         final String pkg = mContextSpy.getOpPackageName();
1607         final Binder token = new Binder();
1608         final String tag = "testInvalidDisplayGroupWakeLock_affectsAllDisplayGroups";
1609 
1610         setMinimumScreenOffTimeoutConfig(5);
1611         createService();
1612         startSystem();
1613         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
1614 
1615         mService.getBinderServiceInstance().acquireWakeLock(token,
1616                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK, tag, pkg,
1617                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, null);
1618 
1619         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1620         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
1621                 WAKEFULNESS_AWAKE);
1622         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
1623                 WAKEFULNESS_AWAKE);
1624 
1625         advanceTime(15000);
1626         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1627         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
1628                 WAKEFULNESS_AWAKE);
1629         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
1630                 WAKEFULNESS_AWAKE);
1631     }
1632 
1633     @Test
testRemovedDisplayGroupWakeLock_affectsNoDisplayGroups()1634     public void testRemovedDisplayGroupWakeLock_affectsNoDisplayGroups() {
1635         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
1636         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
1637         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
1638                 new AtomicReference<>();
1639         doAnswer((Answer<Void>) invocation -> {
1640             listener.set(invocation.getArgument(0));
1641             return null;
1642         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
1643         final DisplayInfo info = new DisplayInfo();
1644         info.displayGroupId = nonDefaultDisplayGroupId;
1645         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
1646 
1647         doAnswer(inv -> {
1648             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
1649             return null;
1650         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
1651 
1652         final String pkg = mContextSpy.getOpPackageName();
1653         final Binder token = new Binder();
1654         final String tag = "testRemovedDisplayGroupWakeLock_affectsNoDisplayGroups";
1655 
1656         setMinimumScreenOffTimeoutConfig(5);
1657         createService();
1658         startSystem();
1659         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
1660 
1661         mService.getBinderServiceInstance().acquireWakeLock(token,
1662                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK, tag, pkg,
1663                 null /* workSource */, null /* historyTag */, nonDefaultDisplay, null);
1664 
1665         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
1666                 WAKEFULNESS_AWAKE);
1667         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
1668                 WAKEFULNESS_AWAKE);
1669         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1670 
1671         listener.get().onDisplayGroupRemoved(nonDefaultDisplayGroupId);
1672 
1673         advanceTime(15000);
1674         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
1675                 WAKEFULNESS_DOZING);
1676         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
1677     }
1678 
1679     @Test
testBoot_ShouldBeAwake()1680     public void testBoot_ShouldBeAwake() {
1681         createService();
1682         startSystem();
1683 
1684         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1685         verify(mNotifierMock, never()).onGlobalWakefulnessChangeStarted(anyInt(), anyInt(),
1686                 anyLong());
1687     }
1688 
1689     @Test
testBoot_DesiredScreenPolicyShouldBeBright()1690     public void testBoot_DesiredScreenPolicyShouldBeBright() {
1691         createService();
1692         startSystem();
1693 
1694         assertThat(mService.getDesiredScreenPolicyLocked(Display.DEFAULT_DISPLAY)).isEqualTo(
1695                 DisplayPowerRequest.POLICY_BRIGHT);
1696     }
1697 
1698     @Test
testQuiescentBoot_ShouldBeAsleep()1699     public void testQuiescentBoot_ShouldBeAsleep() {
1700         when(mSystemPropertiesMock.get(eq(SYSTEM_PROPERTY_QUIESCENT), any())).thenReturn("1");
1701         createService();
1702         startSystem();
1703 
1704         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
1705         verify(mNotifierMock).onGlobalWakefulnessChangeStarted(eq(WAKEFULNESS_ASLEEP), anyInt(),
1706                 anyLong());
1707     }
1708 
1709     @Test
testQuiescentBoot_DesiredScreenPolicyShouldBeOff()1710     public void testQuiescentBoot_DesiredScreenPolicyShouldBeOff() {
1711         when(mSystemPropertiesMock.get(eq(SYSTEM_PROPERTY_QUIESCENT), any())).thenReturn("1");
1712         createService();
1713         startSystem();
1714         assertThat(mService.getDesiredScreenPolicyLocked(Display.DEFAULT_DISPLAY)).isEqualTo(
1715                 DisplayPowerRequest.POLICY_OFF);
1716     }
1717 
1718     @Test
testQuiescentBoot_WakeUp_DesiredScreenPolicyShouldBeBright()1719     public void testQuiescentBoot_WakeUp_DesiredScreenPolicyShouldBeBright() {
1720         when(mSystemPropertiesMock.get(eq(SYSTEM_PROPERTY_QUIESCENT), any())).thenReturn("1");
1721         createService();
1722         startSystem();
1723         forceAwake();
1724         assertThat(mService.getDesiredScreenPolicyLocked(Display.DEFAULT_DISPLAY)).isEqualTo(
1725                 DisplayPowerRequest.POLICY_BRIGHT);
1726     }
1727 
1728     @Test
testQuiescentBoot_WakeKeyBeforeBootCompleted_AwakeAfterBootCompleted()1729     public void testQuiescentBoot_WakeKeyBeforeBootCompleted_AwakeAfterBootCompleted() {
1730         when(mSystemPropertiesMock.get(eq(SYSTEM_PROPERTY_QUIESCENT), any())).thenReturn("1");
1731         createService();
1732         startSystem();
1733 
1734         mService.getBinderServiceInstance().wakeUp(mClock.now(),
1735                 PowerManager.WAKE_REASON_UNKNOWN, "testing IPowerManager.wakeUp()", "pkg.name");
1736 
1737         mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
1738         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
1739         assertThat(mService.getDesiredScreenPolicyLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
1740                 DisplayPowerRequest.POLICY_BRIGHT);
1741     }
1742 
1743     @Test
testIsAmbientDisplayAvailable_available()1744     public void testIsAmbientDisplayAvailable_available() {
1745         createService();
1746         when(mAmbientDisplayConfigurationMock.ambientDisplayAvailable()).thenReturn(true);
1747 
1748         assertThat(mService.getBinderServiceInstance().isAmbientDisplayAvailable()).isTrue();
1749     }
1750 
1751     @Test
testIsAmbientDisplayAvailable_unavailable()1752     public void testIsAmbientDisplayAvailable_unavailable() {
1753         createService();
1754         when(mAmbientDisplayConfigurationMock.ambientDisplayAvailable()).thenReturn(false);
1755 
1756         assertThat(mService.getBinderServiceInstance().isAmbientDisplayAvailable()).isFalse();
1757     }
1758 
1759     @Test
testIsAmbientDisplaySuppressed_default_notSuppressed()1760     public void testIsAmbientDisplaySuppressed_default_notSuppressed() {
1761         createService();
1762 
1763         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressed()).isFalse();
1764     }
1765 
1766     @Test
testIsAmbientDisplaySuppressed_suppressed()1767     public void testIsAmbientDisplaySuppressed_suppressed() {
1768         createService();
1769         mService.getBinderServiceInstance().suppressAmbientDisplay("test", true);
1770 
1771         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressed()).isTrue();
1772     }
1773 
1774     @Test
testIsAmbientDisplaySuppressed_notSuppressed()1775     public void testIsAmbientDisplaySuppressed_notSuppressed() {
1776         createService();
1777         mService.getBinderServiceInstance().suppressAmbientDisplay("test", false);
1778 
1779         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressed()).isFalse();
1780     }
1781 
1782     @Test
testIsAmbientDisplaySuppressed_multipleTokens_suppressed()1783     public void testIsAmbientDisplaySuppressed_multipleTokens_suppressed() {
1784         createService();
1785         mService.getBinderServiceInstance().suppressAmbientDisplay("test1", false);
1786         mService.getBinderServiceInstance().suppressAmbientDisplay("test2", true);
1787 
1788         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressed()).isTrue();
1789     }
1790 
1791     @Test
testIsAmbientDisplaySuppressed_multipleTokens_notSuppressed()1792     public void testIsAmbientDisplaySuppressed_multipleTokens_notSuppressed() {
1793         createService();
1794         mService.getBinderServiceInstance().suppressAmbientDisplay("test1", false);
1795         mService.getBinderServiceInstance().suppressAmbientDisplay("test2", false);
1796 
1797         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressed()).isFalse();
1798     }
1799 
1800     @Test
testIsAmbientDisplaySuppressedForToken_default_notSuppressed()1801     public void testIsAmbientDisplaySuppressedForToken_default_notSuppressed() {
1802         createService();
1803 
1804         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressedForToken("test"))
1805             .isFalse();
1806     }
1807 
1808     @Test
testIsAmbientDisplaySuppressedForToken_suppressed()1809     public void testIsAmbientDisplaySuppressedForToken_suppressed() {
1810         createService();
1811         mService.getBinderServiceInstance().suppressAmbientDisplay("test", true);
1812 
1813         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressedForToken("test"))
1814             .isTrue();
1815     }
1816 
1817     @Test
testIsAmbientDisplaySuppressedForToken_notSuppressed()1818     public void testIsAmbientDisplaySuppressedForToken_notSuppressed() {
1819         createService();
1820         mService.getBinderServiceInstance().suppressAmbientDisplay("test", false);
1821 
1822         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressedForToken("test"))
1823             .isFalse();
1824     }
1825 
1826     @Test
testIsAmbientDisplaySuppressedForToken_multipleTokens_suppressed()1827     public void testIsAmbientDisplaySuppressedForToken_multipleTokens_suppressed() {
1828         createService();
1829         mService.getBinderServiceInstance().suppressAmbientDisplay("test1", true);
1830         mService.getBinderServiceInstance().suppressAmbientDisplay("test2", true);
1831 
1832         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressedForToken("test1"))
1833             .isTrue();
1834         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressedForToken("test2"))
1835             .isTrue();
1836     }
1837 
1838     @Test
testIsAmbientDisplaySuppressedForToken_multipleTokens_notSuppressed()1839     public void testIsAmbientDisplaySuppressedForToken_multipleTokens_notSuppressed() {
1840         createService();
1841         mService.getBinderServiceInstance().suppressAmbientDisplay("test1", true);
1842         mService.getBinderServiceInstance().suppressAmbientDisplay("test2", false);
1843 
1844         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressedForToken("test1"))
1845             .isTrue();
1846         assertThat(mService.getBinderServiceInstance().isAmbientDisplaySuppressedForToken("test2"))
1847             .isFalse();
1848     }
1849 
1850     @Test
testIsAmbientDisplaySuppressedForTokenByApp_ambientDisplayUnavailable()1851     public void testIsAmbientDisplaySuppressedForTokenByApp_ambientDisplayUnavailable() {
1852         createService();
1853         when(mAmbientDisplayConfigurationMock.ambientDisplayAvailable()).thenReturn(false);
1854 
1855         BinderService service = mService.getBinderServiceInstance();
1856         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test", Binder.getCallingUid()))
1857             .isFalse();
1858     }
1859 
1860     @Test
testIsAmbientDisplaySuppressedForTokenByApp_default()1861     public void testIsAmbientDisplaySuppressedForTokenByApp_default() {
1862         createService();
1863 
1864         BinderService service = mService.getBinderServiceInstance();
1865         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test", Binder.getCallingUid()))
1866             .isFalse();
1867     }
1868 
1869     @Test
testIsAmbientDisplaySuppressedForTokenByApp_suppressedByCallingApp()1870     public void testIsAmbientDisplaySuppressedForTokenByApp_suppressedByCallingApp() {
1871         createService();
1872         BinderService service = mService.getBinderServiceInstance();
1873         service.suppressAmbientDisplay("test", true);
1874 
1875         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test", Binder.getCallingUid()))
1876             .isTrue();
1877         // Check that isAmbientDisplaySuppressedForTokenByApp doesn't return true for another app.
1878         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test", /* appUid= */ 123))
1879             .isFalse();
1880     }
1881 
1882     @Test
testIsAmbientDisplaySuppressedForTokenByApp_notSuppressedByCallingApp()1883     public void testIsAmbientDisplaySuppressedForTokenByApp_notSuppressedByCallingApp() {
1884         createService();
1885         BinderService service = mService.getBinderServiceInstance();
1886         service.suppressAmbientDisplay("test", false);
1887 
1888         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test", Binder.getCallingUid()))
1889             .isFalse();
1890         // Check that isAmbientDisplaySuppressedForTokenByApp doesn't return true for another app.
1891         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test", /* appUid= */ 123))
1892             .isFalse();
1893     }
1894 
1895     @Test
testIsAmbientDisplaySuppressedForTokenByApp_multipleTokensSuppressedByCallingApp()1896     public void testIsAmbientDisplaySuppressedForTokenByApp_multipleTokensSuppressedByCallingApp() {
1897         createService();
1898         BinderService service = mService.getBinderServiceInstance();
1899         service.suppressAmbientDisplay("test1", true);
1900         service.suppressAmbientDisplay("test2", true);
1901 
1902         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test1", Binder.getCallingUid()))
1903             .isTrue();
1904         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test2", Binder.getCallingUid()))
1905             .isTrue();
1906         // Check that isAmbientDisplaySuppressedForTokenByApp doesn't return true for another app.
1907         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test1", /* appUid= */ 123))
1908             .isFalse();
1909         assertThat(service.isAmbientDisplaySuppressedForTokenByApp("test2", /* appUid= */ 123))
1910             .isFalse();
1911     }
1912 
1913     @Test
testGetAmbientDisplaySuppressionTokens_default()1914     public void testGetAmbientDisplaySuppressionTokens_default() {
1915         createService();
1916         BinderService service = mService.getBinderServiceInstance();
1917 
1918         assertThat(service.getAmbientDisplaySuppressionTokens()).isEmpty();
1919     }
1920 
1921     @Test
testGetAmbientDisplaySuppressionTokens_singleToken()1922     public void testGetAmbientDisplaySuppressionTokens_singleToken() {
1923         createService();
1924         BinderService service = mService.getBinderServiceInstance();
1925         service.suppressAmbientDisplay("test1", true);
1926         service.suppressAmbientDisplay("test2", false);
1927 
1928         assertThat(service.getAmbientDisplaySuppressionTokens()).containsExactly("test1");
1929     }
1930 
1931     @Test
testGetAmbientDisplaySuppressionTokens_multipleTokens()1932     public void testGetAmbientDisplaySuppressionTokens_multipleTokens() {
1933         createService();
1934         BinderService service = mService.getBinderServiceInstance();
1935         service.suppressAmbientDisplay("test1", true);
1936         service.suppressAmbientDisplay("test2", true);
1937 
1938         assertThat(service.getAmbientDisplaySuppressionTokens())
1939                 .containsExactly("test1", "test2");
1940     }
1941 
1942     @Test
testSetPowerBoost_redirectsCallToNativeWrapper()1943     public void testSetPowerBoost_redirectsCallToNativeWrapper() {
1944         createService();
1945         startSystem();
1946 
1947         mService.getBinderServiceInstance().setPowerBoost(Boost.INTERACTION, 1234);
1948 
1949         verify(mNativeWrapperMock).nativeSetPowerBoost(eq(Boost.INTERACTION), eq(1234));
1950     }
1951 
1952     @Test
testSetPowerMode_redirectsCallToNativeWrapper()1953     public void testSetPowerMode_redirectsCallToNativeWrapper() {
1954         createService();
1955         startSystem();
1956 
1957         // Enabled launch boost in BatterySaverController to allow setting launch mode.
1958         when(mBatterySaverControllerMock.isLaunchBoostDisabled()).thenReturn(false);
1959         when(mNativeWrapperMock.nativeSetPowerMode(anyInt(), anyBoolean())).thenReturn(true);
1960 
1961         mService.getBinderServiceInstance().setPowerMode(Mode.LAUNCH, true);
1962 
1963         verify(mNativeWrapperMock).nativeSetPowerMode(eq(Mode.LAUNCH), eq(true));
1964     }
1965 
1966     @Test
testSetPowerMode_withLaunchBoostDisabledAndModeLaunch_ignoresCallToEnable()1967     public void testSetPowerMode_withLaunchBoostDisabledAndModeLaunch_ignoresCallToEnable() {
1968         createService();
1969         startSystem();
1970 
1971         // Disables launch boost in BatterySaverController.
1972         when(mBatterySaverControllerMock.isLaunchBoostDisabled()).thenReturn(true);
1973         when(mNativeWrapperMock.nativeSetPowerMode(anyInt(), anyBoolean())).thenReturn(true);
1974 
1975         mService.getBinderServiceInstance().setPowerMode(Mode.LAUNCH, true);
1976         mService.getBinderServiceInstance().setPowerMode(Mode.LAUNCH, false);
1977 
1978         verify(mNativeWrapperMock, never()).nativeSetPowerMode(eq(Mode.LAUNCH), eq(true));
1979         verify(mNativeWrapperMock).nativeSetPowerMode(eq(Mode.LAUNCH), eq(false));
1980     }
1981 
1982     @Test
testSetPowerModeChecked_returnsNativeCallResult()1983     public void testSetPowerModeChecked_returnsNativeCallResult() {
1984         createService();
1985         startSystem();
1986 
1987         // Disables launch boost in BatterySaverController.
1988         when(mBatterySaverControllerMock.isLaunchBoostDisabled()).thenReturn(true);
1989         when(mNativeWrapperMock.nativeSetPowerMode(anyInt(), anyBoolean())).thenReturn(true);
1990         when(mNativeWrapperMock.nativeSetPowerMode(eq(Mode.INTERACTIVE), anyBoolean()))
1991             .thenReturn(false);
1992 
1993         // Ignored because isLaunchBoostDisabled is true. Should return false.
1994         assertFalse(mService.getBinderServiceInstance().setPowerModeChecked(Mode.LAUNCH, true));
1995         // Native calls return true.
1996         assertTrue(mService.getBinderServiceInstance().setPowerModeChecked(Mode.LAUNCH, false));
1997         assertTrue(mService.getBinderServiceInstance().setPowerModeChecked(Mode.LOW_POWER, true));
1998         // Native call for interactive returns false.
1999         assertFalse(
2000                 mService.getBinderServiceInstance().setPowerModeChecked(Mode.INTERACTIVE, false));
2001     }
2002 
2003     @Test
testMultiDisplay_wakefulnessUpdates()2004     public void testMultiDisplay_wakefulnessUpdates() {
2005         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2006         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2007                 new AtomicReference<>();
2008         doAnswer((Answer<Void>) invocation -> {
2009             listener.set(invocation.getArgument(0));
2010             return null;
2011         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2012 
2013         createService();
2014         startSystem();
2015         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2016 
2017         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2018 
2019         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_ASLEEP, 0, 0, 0, 0,
2020                 null, null);
2021         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2022 
2023         mService.setWakefulnessLocked(nonDefaultDisplayGroupId, WAKEFULNESS_ASLEEP, 0, 0, 0, 0,
2024                 null, null);
2025         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
2026 
2027         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_AWAKE, 0, 0, 0, 0,
2028                 null, null);
2029         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2030     }
2031 
2032     @Test
testMultiDisplay_addDisplayGroup_wakesDeviceUp()2033     public void testMultiDisplay_addDisplayGroup_wakesDeviceUp() {
2034         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2035         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2036                 new AtomicReference<>();
2037         doAnswer((Answer<Void>) invocation -> {
2038             listener.set(invocation.getArgument(0));
2039             return null;
2040         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2041 
2042         createService();
2043         startSystem();
2044 
2045         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2046 
2047         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_ASLEEP, 0, 0, 0, 0,
2048                 null, null);
2049         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
2050 
2051         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2052 
2053         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2054     }
2055 
2056     @Test
testMultiDisplay_removeDisplayGroup_updatesWakefulness()2057     public void testMultiDisplay_removeDisplayGroup_updatesWakefulness() {
2058         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2059         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2060                 new AtomicReference<>();
2061         doAnswer((Answer<Void>) invocation -> {
2062             listener.set(invocation.getArgument(0));
2063             return null;
2064         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2065 
2066         createService();
2067         startSystem();
2068         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2069 
2070         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2071 
2072         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_ASLEEP, 0, 0, 0, 0,
2073                 null, null);
2074         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2075 
2076         listener.get().onDisplayGroupRemoved(nonDefaultDisplayGroupId);
2077         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
2078 
2079         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_AWAKE, 0, 0, 0, 0,
2080                 null, null);
2081         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2082     }
2083 
2084     @Test
testMultiDisplay_updatesLastGlobalWakeTime()2085     public void testMultiDisplay_updatesLastGlobalWakeTime() {
2086         final int nonDefaultPowerGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2087         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2088                 new AtomicReference<>();
2089         long eventTime1 = 10;
2090         long eventTime2 = eventTime1 + 1;
2091         long eventTime3 = eventTime2 + 1;
2092         long eventTime4 = eventTime3 + 1;
2093         doAnswer((Answer<Void>) invocation -> {
2094             listener.set(invocation.getArgument(0));
2095             return null;
2096         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2097 
2098         createService();
2099         startSystem();
2100         listener.get().onDisplayGroupAdded(nonDefaultPowerGroupId);
2101 
2102         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2103 
2104         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_DOZING, eventTime1,
2105                 0, PowerManager.GO_TO_SLEEP_REASON_INATTENTIVE, 0, null, null);
2106         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2107 
2108         mService.setWakefulnessLocked(nonDefaultPowerGroupId, WAKEFULNESS_DOZING, eventTime2,
2109                 0, PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2110         long eventElapsedRealtime1 = mLastElapsedRealtime;
2111         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
2112         assertThat(mService.getBinderServiceInstance().getLastSleepReason()).isEqualTo(
2113                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION);
2114 
2115         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_AWAKE,
2116                 eventTime3, /* uid= */ 0, PowerManager.WAKE_REASON_PLUGGED_IN, /* opUid= */
2117                 0, /* opPackageName= */ null, /* details= */ null);
2118         long eventElapsedRealtime2 = mLastElapsedRealtime;
2119         PowerManager.WakeData wakeData = mService.getLocalServiceInstance().getLastWakeup();
2120         assertThat(wakeData.wakeTime).isEqualTo(eventTime3);
2121         assertThat(wakeData.wakeReason).isEqualTo(PowerManager.WAKE_REASON_PLUGGED_IN);
2122         assertThat(wakeData.sleepDurationRealtime)
2123                 .isEqualTo(eventElapsedRealtime2 - eventElapsedRealtime1);
2124 
2125         // The global wake time and reason as well as sleep duration shouldn't change when another
2126         // PowerGroup wakes up.
2127         mService.setWakefulnessLocked(nonDefaultPowerGroupId, WAKEFULNESS_AWAKE,
2128                 eventTime4, /* uid= */ 0, PowerManager.WAKE_REASON_CAMERA_LAUNCH, /* opUid= */
2129                 0, /* opPackageName= */ null, /* details= */ null);
2130         PowerManager.WakeData wakeData2 = mService.getLocalServiceInstance().getLastWakeup();
2131         assertThat(wakeData2).isEqualTo(wakeData);
2132     }
2133 
2134     @Test
testMultiDisplay_defaultDisplayCanDoze()2135     public void testMultiDisplay_defaultDisplayCanDoze() {
2136         createService();
2137         startSystem();
2138         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2139         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2140                 WAKEFULNESS_AWAKE);
2141 
2142         forceDozing();
2143         // Allow handleSandman() to be called asynchronously
2144         advanceTime(500);
2145         verify(mDreamManagerInternalMock).startDream(eq(true), anyString());
2146     }
2147 
2148     @Test
testMultiDisplay_twoDisplays_defaultDisplayCanDoze()2149     public void testMultiDisplay_twoDisplays_defaultDisplayCanDoze() {
2150         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2151         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
2152         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2153                 new AtomicReference<>();
2154         doAnswer((Answer<Void>) invocation -> {
2155             listener.set(invocation.getArgument(0));
2156             return null;
2157         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2158         final DisplayInfo info = new DisplayInfo();
2159         info.displayGroupId = nonDefaultDisplayGroupId;
2160         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
2161 
2162         createService();
2163         startSystem();
2164 
2165         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2166 
2167         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2168                 WAKEFULNESS_AWAKE);
2169         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
2170                 WAKEFULNESS_AWAKE);
2171         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2172 
2173         forceDozing();
2174 
2175         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2176                 WAKEFULNESS_DOZING);
2177         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
2178                 WAKEFULNESS_AWAKE);
2179         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2180 
2181         // Allow handleSandman() to be called asynchronously
2182         advanceTime(500);
2183         verify(mDreamManagerInternalMock).startDream(eq(true), anyString());
2184     }
2185 
2186     @Test
testMultiDisplay_addNewDisplay_becomeGloballyAwakeButDefaultRemainsDozing()2187     public void testMultiDisplay_addNewDisplay_becomeGloballyAwakeButDefaultRemainsDozing() {
2188         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2189         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
2190         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2191                 new AtomicReference<>();
2192         doAnswer((Answer<Void>) invocation -> {
2193             listener.set(invocation.getArgument(0));
2194             return null;
2195         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2196         final DisplayInfo info = new DisplayInfo();
2197         info.displayGroupId = nonDefaultDisplayGroupId;
2198         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
2199 
2200         doAnswer(inv -> {
2201             when(mDreamManagerInternalMock.isDreaming()).thenReturn(true);
2202             return null;
2203         }).when(mDreamManagerInternalMock).startDream(anyBoolean(), anyString());
2204 
2205         createService();
2206         startSystem();
2207 
2208         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2209                 WAKEFULNESS_AWAKE);
2210 
2211         forceDozing();
2212         advanceTime(500);
2213 
2214         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2215                 WAKEFULNESS_DOZING);
2216         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DOZING);
2217         verify(mDreamManagerInternalMock).stopDream(anyBoolean(), anyString());
2218         verify(mDreamManagerInternalMock).startDream(eq(true), anyString());
2219 
2220         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2221         advanceTime(500);
2222 
2223         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2224         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
2225                 WAKEFULNESS_AWAKE);
2226         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2227                 WAKEFULNESS_DOZING);
2228 
2229         // Make sure there were no additional calls to stopDream or startDream
2230         verify(mDreamManagerInternalMock, atMost(1)).stopDream(anyBoolean(), anyString());
2231         verify(mDreamManagerInternalMock, atMost(1)).startDream(eq(true), anyString());
2232     }
2233 
2234     @Test
testLastSleepTime_notUpdatedWhenDreaming()2235     public void testLastSleepTime_notUpdatedWhenDreaming() {
2236         createService();
2237         startSystem();
2238 
2239         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2240         PowerManager.WakeData initialWakeData = mService.getLocalServiceInstance().getLastWakeup();
2241 
2242         forceDream();
2243         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_DREAMING);
2244         assertThat(mService.getLocalServiceInstance().getLastWakeup()).isEqualTo(initialWakeData);
2245     }
2246 
2247     @Test
testMultiDisplay_onlyOneDisplaySleeps_onWakefulnessChangedEventsFire()2248     public void testMultiDisplay_onlyOneDisplaySleeps_onWakefulnessChangedEventsFire() {
2249         createService();
2250         startSystem();
2251         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2252         forceSleep();
2253         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2254                 WAKEFULNESS_ASLEEP);
2255 
2256         verify(mNotifierMock).onGroupWakefulnessChangeStarted(eq(Display.DEFAULT_DISPLAY_GROUP),
2257                 eq(WAKEFULNESS_ASLEEP), eq(PowerManager.GO_TO_SLEEP_REASON_APPLICATION), anyLong());
2258         verify(mNotifierMock).onGlobalWakefulnessChangeStarted(eq(WAKEFULNESS_ASLEEP),
2259                 eq(PowerManager.GO_TO_SLEEP_REASON_APPLICATION), anyLong());
2260     }
2261 
2262     @Test
testMultiDisplay_bothDisplaysSleep_onWakefulnessChangedEventsFireCorrectly()2263     public void testMultiDisplay_bothDisplaysSleep_onWakefulnessChangedEventsFireCorrectly() {
2264         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2265         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
2266         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2267                 new AtomicReference<>();
2268         doAnswer((Answer<Void>) invocation -> {
2269             listener.set(invocation.getArgument(0));
2270             return null;
2271         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2272         final DisplayInfo info = new DisplayInfo();
2273         info.displayGroupId = nonDefaultDisplayGroupId;
2274         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
2275 
2276         createService();
2277         startSystem();
2278 
2279         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2280         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2281 
2282         mService.setWakefulnessLocked(nonDefaultDisplayGroupId, WAKEFULNESS_ASLEEP, 0, 0,
2283                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2284         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_ASLEEP, 0, 0,
2285                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2286 
2287         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_ASLEEP);
2288         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2289                 WAKEFULNESS_ASLEEP);
2290         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
2291                 WAKEFULNESS_ASLEEP);
2292 
2293         verify(mNotifierMock).onGroupWakefulnessChangeStarted(eq(nonDefaultDisplayGroupId),
2294                 eq(WAKEFULNESS_ASLEEP), eq(PowerManager.GO_TO_SLEEP_REASON_APPLICATION), anyLong());
2295         verify(mNotifierMock).onGroupWakefulnessChangeStarted(eq(Display.DEFAULT_DISPLAY_GROUP),
2296                 eq(WAKEFULNESS_ASLEEP), eq(PowerManager.GO_TO_SLEEP_REASON_APPLICATION), anyLong());
2297         verify(mNotifierMock).onGlobalWakefulnessChangeStarted(eq(WAKEFULNESS_ASLEEP),
2298                 eq(PowerManager.GO_TO_SLEEP_REASON_APPLICATION), anyLong());
2299     }
2300 
2301     @Test
testMultiDisplay_separateWakeStates_onWakefulnessChangedEventsFireCorrectly()2302     public void testMultiDisplay_separateWakeStates_onWakefulnessChangedEventsFireCorrectly() {
2303         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2304         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
2305         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2306                 new AtomicReference<>();
2307         doAnswer((Answer<Void>) invocation -> {
2308             listener.set(invocation.getArgument(0));
2309             return null;
2310         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2311         final DisplayInfo info = new DisplayInfo();
2312         info.displayGroupId = nonDefaultDisplayGroupId;
2313         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
2314 
2315         createService();
2316         startSystem();
2317 
2318         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2319         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2320 
2321         final String pkg = mContextSpy.getOpPackageName();
2322         final Binder token = new Binder();
2323         final String tag =
2324                 "testMultiDisplay_separateWakeStates_onWakefulnessChangedEventFiresCorrectly";
2325         mService.getBinderServiceInstance().acquireWakeLock(token,
2326                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK, tag, pkg,
2327                 null /* workSource */, null /* historyTag */, nonDefaultDisplay, null);
2328 
2329         forceSleep();
2330 
2331         // The wakelock should have kept the second display awake, and we should notify that the
2332         // default display went to sleep.
2333         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2334         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2335                 WAKEFULNESS_ASLEEP);
2336         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
2337                 WAKEFULNESS_AWAKE);
2338         verify(mNotifierMock).onGroupWakefulnessChangeStarted(eq(nonDefaultDisplayGroupId),
2339                 eq(WAKEFULNESS_AWAKE), eq(PowerManager.WAKE_REASON_DISPLAY_GROUP_ADDED), anyLong());
2340         verify(mNotifierMock).onGroupWakefulnessChangeStarted(eq(Display.DEFAULT_DISPLAY_GROUP),
2341                 eq(WAKEFULNESS_ASLEEP), eq(PowerManager.GO_TO_SLEEP_REASON_APPLICATION), anyLong());
2342         verify(mNotifierMock, never()).onGlobalWakefulnessChangeStarted(eq(WAKEFULNESS_ASLEEP),
2343                 anyInt(), anyLong());
2344     }
2345 
2346     @Test
testMultiDisplay_oneDisplayGroupChanges_globalDoesNotChange()2347     public void testMultiDisplay_oneDisplayGroupChanges_globalDoesNotChange() {
2348         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2349         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
2350         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2351                 new AtomicReference<>();
2352         doAnswer((Answer<Void>) invocation -> {
2353             listener.set(invocation.getArgument(0));
2354             return null;
2355         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2356         final DisplayInfo info = new DisplayInfo();
2357         info.displayGroupId = nonDefaultDisplayGroupId;
2358         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
2359 
2360         createService();
2361         startSystem();
2362 
2363         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2364 
2365         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2366                 WAKEFULNESS_AWAKE);
2367         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
2368                 WAKEFULNESS_AWAKE);
2369         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2370 
2371         long eventTime = mClock.now();
2372         mService.setWakefulnessLocked(nonDefaultDisplayGroupId, WAKEFULNESS_ASLEEP, eventTime, 0,
2373                 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2374 
2375         assertThat(mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP)).isEqualTo(
2376                 WAKEFULNESS_AWAKE);
2377         assertThat(mService.getWakefulnessLocked(nonDefaultDisplayGroupId)).isEqualTo(
2378                 WAKEFULNESS_ASLEEP);
2379         assertThat(mService.getGlobalWakefulnessLocked()).isEqualTo(WAKEFULNESS_AWAKE);
2380         verify(mNotifierMock, never()).onGlobalWakefulnessChangeStarted(anyInt(), anyInt(),
2381                 anyLong());
2382         verify(mNotifierMock, atMost(1)).onGroupWakefulnessChangeStarted(
2383                 eq(nonDefaultDisplayGroupId), eq(WAKEFULNESS_ASLEEP),
2384                 eq(PowerManager.GO_TO_SLEEP_REASON_APPLICATION), eq(eventTime));
2385     }
2386 
2387     @Test
testMultiDisplay_isInteractive_nonExistentGroup()2388     public void testMultiDisplay_isInteractive_nonExistentGroup() {
2389         createService();
2390         startSystem();
2391 
2392         int nonExistentDisplayGroup = 999;
2393         BinderService binderService = mService.getBinderServiceInstance();
2394         assertThat(binderService.isDisplayInteractive(nonExistentDisplayGroup)).isFalse();
2395     }
2396 
testMultiDisplay_isInteractive_returnsCorrectValue( boolean defaultDisplayAwake, boolean secondGroupDisplayAwake)2397     private void testMultiDisplay_isInteractive_returnsCorrectValue(
2398             boolean defaultDisplayAwake, boolean secondGroupDisplayAwake) {
2399         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2400         // We use a display id that does not match the group id, to make sure we aren't accidentally
2401         // confusing display id's and display group id's in the implementation.
2402         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 17;
2403         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2404                 new AtomicReference<>();
2405         doAnswer((Answer<Void>) invocation -> {
2406             listener.set(invocation.getArgument(0));
2407             return null;
2408         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2409 
2410         final DisplayInfo defaultDisplayInfo = new DisplayInfo();
2411         defaultDisplayInfo.displayGroupId = Display.DEFAULT_DISPLAY_GROUP;
2412         when(mDisplayManagerInternalMock.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(
2413                 defaultDisplayInfo);
2414 
2415         final DisplayInfo secondDisplayInfo = new DisplayInfo();
2416         secondDisplayInfo.displayGroupId = nonDefaultDisplayGroupId;
2417         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(
2418                 secondDisplayInfo);
2419 
2420         createService();
2421         startSystem();
2422         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2423 
2424         if (!defaultDisplayAwake) {
2425             mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_ASLEEP,
2426                     mClock.now(), 0, PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2427         }
2428         if (!secondGroupDisplayAwake) {
2429             mService.setWakefulnessLocked(nonDefaultDisplayGroupId, WAKEFULNESS_ASLEEP,
2430                     mClock.now(), 0,
2431                     PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2432         }
2433         assertThat(PowerManagerInternal.isInteractive(
2434                 mService.getWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP))).isEqualTo(
2435                 defaultDisplayAwake);
2436         assertThat(PowerManagerInternal.isInteractive(
2437                 mService.getWakefulnessLocked(nonDefaultDisplayGroupId))).isEqualTo(
2438                 secondGroupDisplayAwake);
2439 
2440         BinderService binderService = mService.getBinderServiceInstance();
2441         assertThat(binderService.isInteractive()).isEqualTo(
2442                 defaultDisplayAwake || secondGroupDisplayAwake);
2443         assertThat(binderService.isDisplayInteractive(Display.DEFAULT_DISPLAY)).isEqualTo(
2444                 defaultDisplayAwake);
2445         assertThat(binderService.isDisplayInteractive(nonDefaultDisplay)).isEqualTo(
2446                 secondGroupDisplayAwake);
2447     }
2448 
2449     @Test
testMultiDisplay_isInteractive_defaultGroupIsAwakeSecondGroupIsAwake()2450     public void testMultiDisplay_isInteractive_defaultGroupIsAwakeSecondGroupIsAwake() {
2451         testMultiDisplay_isInteractive_returnsCorrectValue(true, true);
2452     }
2453 
2454     @Test
testMultiDisplay_isInteractive_defaultGroupIsAwakeSecondGroupIsAsleep()2455     public void testMultiDisplay_isInteractive_defaultGroupIsAwakeSecondGroupIsAsleep() {
2456         testMultiDisplay_isInteractive_returnsCorrectValue(true, false);
2457     }
2458 
2459     @Test
testMultiDisplay_isInteractive_defaultGroupIsAsleepSecondGroupIsAwake()2460     public void testMultiDisplay_isInteractive_defaultGroupIsAsleepSecondGroupIsAwake() {
2461         testMultiDisplay_isInteractive_returnsCorrectValue(false, true);
2462     }
2463 
2464     @Test
testMultiDisplay_isInteractive_bothGroupsAreAsleep()2465     public void testMultiDisplay_isInteractive_bothGroupsAreAsleep() {
2466         testMultiDisplay_isInteractive_returnsCorrectValue(false, false);
2467     }
2468 
2469     @Test
testMultiDisplay_defaultGroupWakefulnessChange_causesIsInteractiveInvalidate()2470     public void testMultiDisplay_defaultGroupWakefulnessChange_causesIsInteractiveInvalidate()
2471             throws Exception {
2472         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2473         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
2474         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2475                 new AtomicReference<>();
2476         doAnswer((Answer<Void>) invocation -> {
2477             listener.set(invocation.getArgument(0));
2478             return null;
2479         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2480         final DisplayInfo info = new DisplayInfo();
2481         info.displayGroupId = nonDefaultDisplayGroupId;
2482         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
2483         createService();
2484         startSystem();
2485         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2486 
2487         verify(mInvalidateInteractiveCachesMock).call();
2488 
2489         mService.setWakefulnessLocked(Display.DEFAULT_DISPLAY_GROUP, WAKEFULNESS_ASLEEP,
2490                 mClock.now(), 0, PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2491 
2492         verify(mInvalidateInteractiveCachesMock, times(2)).call();
2493     }
2494 
2495     @Test
testMultiDisplay_secondGroupWakefulness_causesIsInteractiveInvalidate()2496     public void testMultiDisplay_secondGroupWakefulness_causesIsInteractiveInvalidate()
2497             throws Exception {
2498         final int nonDefaultDisplayGroupId = Display.DEFAULT_DISPLAY_GROUP + 1;
2499         final int nonDefaultDisplay = Display.DEFAULT_DISPLAY + 1;
2500         final AtomicReference<DisplayManagerInternal.DisplayGroupListener> listener =
2501                 new AtomicReference<>();
2502         doAnswer((Answer<Void>) invocation -> {
2503             listener.set(invocation.getArgument(0));
2504             return null;
2505         }).when(mDisplayManagerInternalMock).registerDisplayGroupListener(any());
2506         final DisplayInfo info = new DisplayInfo();
2507         info.displayGroupId = nonDefaultDisplayGroupId;
2508         when(mDisplayManagerInternalMock.getDisplayInfo(nonDefaultDisplay)).thenReturn(info);
2509         createService();
2510         startSystem();
2511         listener.get().onDisplayGroupAdded(nonDefaultDisplayGroupId);
2512 
2513         verify(mInvalidateInteractiveCachesMock).call();
2514 
2515         mService.setWakefulnessLocked(nonDefaultDisplayGroupId, WAKEFULNESS_ASLEEP, mClock.now(),
2516                 0, PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0, null, null);
2517 
2518         verify(mInvalidateInteractiveCachesMock, times(2)).call();
2519     }
2520 
2521     @Test
testGetFullPowerSavePolicy_returnsStateMachineResult()2522     public void testGetFullPowerSavePolicy_returnsStateMachineResult() {
2523         createService();
2524         startSystem();
2525         BatterySaverPolicyConfig mockReturnConfig = new BatterySaverPolicyConfig.Builder().build();
2526         when(mBatterySaverStateMachineMock.getFullBatterySaverPolicy())
2527                 .thenReturn(mockReturnConfig);
2528 
2529         mService.getBinderServiceInstance().setPowerSaveModeEnabled(true);
2530         BatterySaverPolicyConfig policyConfig =
2531                 mService.getBinderServiceInstance().getFullPowerSavePolicy();
2532         assertThat(mockReturnConfig).isEqualTo(policyConfig);
2533         verify(mBatterySaverStateMachineMock).getFullBatterySaverPolicy();
2534     }
2535 
2536     @Test
testSetFullPowerSavePolicy_callsStateMachine()2537     public void testSetFullPowerSavePolicy_callsStateMachine() {
2538         createService();
2539         startSystem();
2540         BatterySaverPolicyConfig mockSetPolicyConfig =
2541                 new BatterySaverPolicyConfig.Builder().build();
2542         when(mBatterySaverStateMachineMock.setFullBatterySaverPolicy(any())).thenReturn(true);
2543 
2544         mService.getBinderServiceInstance().setPowerSaveModeEnabled(true);
2545         assertThat(mService.getBinderServiceInstance()
2546                 .setFullPowerSavePolicy(mockSetPolicyConfig)).isTrue();
2547         verify(mBatterySaverStateMachineMock).setFullBatterySaverPolicy(eq(mockSetPolicyConfig));
2548     }
2549 
2550     @Test
testLowPowerStandby_whenInactive_FgsWakeLockEnabled()2551     public void testLowPowerStandby_whenInactive_FgsWakeLockEnabled() {
2552         createService();
2553         startSystem();
2554         WakeLock wakeLock = acquireWakeLock("fgsWakeLock", PowerManager.PARTIAL_WAKE_LOCK);
2555         mService.updateUidProcStateInternal(wakeLock.mOwnerUid, PROCESS_STATE_FOREGROUND_SERVICE);
2556         mService.setDeviceIdleModeInternal(true);
2557 
2558         assertThat(wakeLock.mDisabled).isFalse();
2559     }
2560 
2561     @Test
testLowPowerStandby_whenActive_FgsWakeLockDisabled()2562     public void testLowPowerStandby_whenActive_FgsWakeLockDisabled() {
2563         createService();
2564         startSystem();
2565         WakeLock wakeLock = acquireWakeLock("fgsWakeLock", PowerManager.PARTIAL_WAKE_LOCK);
2566         mService.updateUidProcStateInternal(wakeLock.mOwnerUid, PROCESS_STATE_FOREGROUND_SERVICE);
2567         mService.setDeviceIdleModeInternal(true);
2568         mService.setLowPowerStandbyActiveInternal(true);
2569 
2570         assertThat(wakeLock.mDisabled).isTrue();
2571     }
2572 
2573     @Test
testLowPowerStandby_whenActive_FgsWakeLockEnabledIfAllowlisted()2574     public void testLowPowerStandby_whenActive_FgsWakeLockEnabledIfAllowlisted() {
2575         createService();
2576         startSystem();
2577         WakeLock wakeLock = acquireWakeLock("fgsWakeLock", PowerManager.PARTIAL_WAKE_LOCK);
2578         mService.updateUidProcStateInternal(wakeLock.mOwnerUid, PROCESS_STATE_FOREGROUND_SERVICE);
2579         mService.setDeviceIdleModeInternal(true);
2580         mService.setLowPowerStandbyActiveInternal(true);
2581         mService.setLowPowerStandbyAllowlistInternal(new int[]{wakeLock.mOwnerUid});
2582 
2583         assertThat(wakeLock.mDisabled).isFalse();
2584     }
2585 
2586     @Test
testLowPowerStandby_whenActive_BoundTopWakeLockDisabled()2587     public void testLowPowerStandby_whenActive_BoundTopWakeLockDisabled() {
2588         createService();
2589         startSystem();
2590         WakeLock wakeLock = acquireWakeLock("BoundTopWakeLock", PowerManager.PARTIAL_WAKE_LOCK);
2591         mService.updateUidProcStateInternal(wakeLock.mOwnerUid, PROCESS_STATE_BOUND_TOP);
2592         mService.setDeviceIdleModeInternal(true);
2593         mService.setLowPowerStandbyActiveInternal(true);
2594 
2595         assertThat(wakeLock.mDisabled).isFalse();
2596     }
2597 
2598     @Test
testSetLowPowerStandbyActiveDuringMaintenance_redirectsCallToNativeWrapper()2599     public void testSetLowPowerStandbyActiveDuringMaintenance_redirectsCallToNativeWrapper() {
2600         createService();
2601         startSystem();
2602 
2603         mService.getBinderServiceInstance().setLowPowerStandbyActiveDuringMaintenance(true);
2604         verify(mLowPowerStandbyControllerMock).setActiveDuringMaintenance(true);
2605 
2606         mService.getBinderServiceInstance().setLowPowerStandbyActiveDuringMaintenance(false);
2607         verify(mLowPowerStandbyControllerMock).setActiveDuringMaintenance(false);
2608     }
2609 
acquireWakeLock(String tag, int flags)2610     private WakeLock acquireWakeLock(String tag, int flags) {
2611         IBinder token = new Binder();
2612         String packageName = "pkg.name";
2613         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
2614                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY,
2615                 null /* callback */);
2616         return mService.findWakeLockLocked(token);
2617     }
2618 
2619     /**
2620      * Test IPowerManager.acquireWakeLock() with a IWakeLockCallback.
2621      */
2622     @Test
testNotifyWakeLockCallback()2623     public void testNotifyWakeLockCallback() {
2624         createService();
2625         startSystem();
2626         final String tag = "wakelock1";
2627         final String packageName = "pkg.name";
2628         final IBinder token = new Binder();
2629         final int flags = PowerManager.PARTIAL_WAKE_LOCK;
2630         final IWakeLockCallback callback = Mockito.mock(IWakeLockCallback.class);
2631         final IBinder callbackBinder = Mockito.mock(Binder.class);
2632         when(callback.asBinder()).thenReturn(callbackBinder);
2633         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
2634                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, callback);
2635         verify(mNotifierMock).onWakeLockAcquired(anyInt(), eq(tag), eq(packageName), anyInt(),
2636                 anyInt(), any(), any(), same(callback));
2637 
2638         mService.getBinderServiceInstance().releaseWakeLock(token, 0);
2639         verify(mNotifierMock).onWakeLockReleased(anyInt(), eq(tag), eq(packageName), anyInt(),
2640                 anyInt(), any(), any(), same(callback));
2641     }
2642 
2643     /**
2644      * Test IPowerManager.updateWakeLockCallback() with a new IWakeLockCallback.
2645      */
2646     @Test
testNotifyWakeLockCallbackChange()2647     public void testNotifyWakeLockCallbackChange() {
2648         createService();
2649         startSystem();
2650         final String tag = "wakelock1";
2651         final String packageName = "pkg.name";
2652         final IBinder token = new Binder();
2653         int flags = PowerManager.PARTIAL_WAKE_LOCK;
2654         final IWakeLockCallback callback1 = Mockito.mock(IWakeLockCallback.class);
2655         final IBinder callbackBinder1 = Mockito.mock(Binder.class);
2656         when(callback1.asBinder()).thenReturn(callbackBinder1);
2657         mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
2658                 null /* workSource */, null /* historyTag */, Display.INVALID_DISPLAY, callback1);
2659         verify(mNotifierMock).onWakeLockAcquired(anyInt(), eq(tag), eq(packageName), anyInt(),
2660                 anyInt(), any(), any(), same(callback1));
2661 
2662         final IWakeLockCallback callback2 = Mockito.mock(IWakeLockCallback.class);
2663         final IBinder callbackBinder2 = Mockito.mock(Binder.class);
2664         when(callback2.asBinder()).thenReturn(callbackBinder2);
2665         mService.getBinderServiceInstance().updateWakeLockCallback(token, callback2);
2666         verify(mNotifierMock).onWakeLockChanging(anyInt(), eq(tag), eq(packageName),
2667                 anyInt(), anyInt(), any(), any(), same(callback1),
2668                 anyInt(), eq(tag), eq(packageName), anyInt(), anyInt(), any(), any(),
2669                 same(callback2));
2670 
2671         mService.getBinderServiceInstance().releaseWakeLock(token, 0);
2672         verify(mNotifierMock).onWakeLockReleased(anyInt(), eq(tag), eq(packageName), anyInt(),
2673                 anyInt(), any(), any(), same(callback2));
2674     }
2675 
2676     @Test
testUserActivity_futureEventsAreIgnored()2677     public void testUserActivity_futureEventsAreIgnored() {
2678         createService();
2679         startSystem();
2680         // Starting the system triggers a user activity event, so clear that before calling
2681         // userActivity() directly.
2682         clearInvocations(mNotifierMock);
2683         final long eventTime = mClock.now() + Duration.ofHours(10).toMillis();
2684         mService.getBinderServiceInstance().userActivity(Display.DEFAULT_DISPLAY, eventTime,
2685                 USER_ACTIVITY_EVENT_BUTTON, /* flags= */ 0);
2686         verify(mNotifierMock, never()).onUserActivity(anyInt(),  anyInt(), anyInt());
2687     }
2688 
2689     @Test
testFeatureEnabledProcStateUncachedToCached_fullWakeLockDisabled()2690     public void testFeatureEnabledProcStateUncachedToCached_fullWakeLockDisabled() {
2691         doReturn(true).when(mDeviceParameterProvider)
2692                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2693         createService();
2694         startSystem();
2695         WakeLock wakeLock = acquireWakeLock("fullWakeLock", PowerManager.FULL_WAKE_LOCK);
2696         setUncachedUidProcState(wakeLock.mOwnerUid);
2697 
2698         setCachedUidProcState(wakeLock.mOwnerUid);
2699         assertThat(wakeLock.mDisabled).isTrue();
2700     }
2701 
2702     @Test
testFeatureDisabledProcStateUncachedToCached_fullWakeLockEnabled()2703     public void testFeatureDisabledProcStateUncachedToCached_fullWakeLockEnabled() {
2704         doReturn(false).when(mDeviceParameterProvider)
2705                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2706         createService();
2707         startSystem();
2708         WakeLock wakeLock = acquireWakeLock("fullWakeLock", PowerManager.FULL_WAKE_LOCK);
2709         setUncachedUidProcState(wakeLock.mOwnerUid);
2710 
2711         setCachedUidProcState(wakeLock.mOwnerUid);
2712         assertThat(wakeLock.mDisabled).isFalse();
2713     }
2714 
2715     @Test
testFeatureEnabledProcStateUncachedToCached_screenBrightWakeLockDisabled()2716     public void testFeatureEnabledProcStateUncachedToCached_screenBrightWakeLockDisabled() {
2717         doReturn(true).when(mDeviceParameterProvider)
2718                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2719         createService();
2720         startSystem();
2721         WakeLock wakeLock = acquireWakeLock("screenBrightWakeLock",
2722                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK);
2723         setUncachedUidProcState(wakeLock.mOwnerUid);
2724 
2725         setCachedUidProcState(wakeLock.mOwnerUid);
2726         assertThat(wakeLock.mDisabled).isTrue();
2727     }
2728 
2729     @Test
testFeatureDisabledProcStateUncachedToCached_screenBrightWakeLockEnabled()2730     public void testFeatureDisabledProcStateUncachedToCached_screenBrightWakeLockEnabled() {
2731         doReturn(false).when(mDeviceParameterProvider)
2732                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2733         createService();
2734         startSystem();
2735         WakeLock wakeLock = acquireWakeLock("screenBrightWakeLock",
2736                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK);
2737         setUncachedUidProcState(wakeLock.mOwnerUid);
2738 
2739         setCachedUidProcState(wakeLock.mOwnerUid);
2740         assertThat(wakeLock.mDisabled).isFalse();
2741     }
2742 
2743     @Test
testFeatureEnabledProcStateUncachedToCached_screenDimWakeLockDisabled()2744     public void testFeatureEnabledProcStateUncachedToCached_screenDimWakeLockDisabled() {
2745         doReturn(true).when(mDeviceParameterProvider)
2746                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2747         createService();
2748         startSystem();
2749         WakeLock wakeLock = acquireWakeLock("screenDimWakeLock",
2750                 PowerManager.SCREEN_DIM_WAKE_LOCK);
2751         setUncachedUidProcState(wakeLock.mOwnerUid);
2752 
2753         setCachedUidProcState(wakeLock.mOwnerUid);
2754         assertThat(wakeLock.mDisabled).isTrue();
2755     }
2756 
2757     @Test
testFeatureDisabledProcStateUncachedToCached_screenDimWakeLockEnabled()2758     public void testFeatureDisabledProcStateUncachedToCached_screenDimWakeLockEnabled() {
2759         doReturn(false).when(mDeviceParameterProvider)
2760                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2761         createService();
2762         startSystem();
2763         WakeLock wakeLock = acquireWakeLock("screenDimWakeLock",
2764                 PowerManager.SCREEN_DIM_WAKE_LOCK);
2765         setUncachedUidProcState(wakeLock.mOwnerUid);
2766 
2767         setCachedUidProcState(wakeLock.mOwnerUid);
2768         assertThat(wakeLock.mDisabled).isFalse();
2769     }
2770 
2771     @Test
testFeatureEnabledProcStateCachedToUncached_fullWakeLockEnabled()2772     public void testFeatureEnabledProcStateCachedToUncached_fullWakeLockEnabled() {
2773         doReturn(true).when(mDeviceParameterProvider)
2774                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2775         createService();
2776         startSystem();
2777         WakeLock wakeLock = acquireWakeLock("fullWakeLock", PowerManager.FULL_WAKE_LOCK);
2778         setCachedUidProcState(wakeLock.mOwnerUid);
2779 
2780         setUncachedUidProcState(wakeLock.mOwnerUid);
2781         assertThat(wakeLock.mDisabled).isFalse();
2782     }
2783 
2784     @Test
testFeatureDisabledProcStateCachedToUncached_fullWakeLockEnabled()2785     public void testFeatureDisabledProcStateCachedToUncached_fullWakeLockEnabled() {
2786         doReturn(false).when(mDeviceParameterProvider)
2787                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2788         createService();
2789         startSystem();
2790         WakeLock wakeLock = acquireWakeLock("fullWakeLock", PowerManager.FULL_WAKE_LOCK);
2791         setCachedUidProcState(wakeLock.mOwnerUid);
2792 
2793         setUncachedUidProcState(wakeLock.mOwnerUid);
2794         assertThat(wakeLock.mDisabled).isFalse();
2795     }
2796 
2797     @Test
testFeatureEnabledProcStateCachedToUncached_screenBrightWakeLockEnabled()2798     public void testFeatureEnabledProcStateCachedToUncached_screenBrightWakeLockEnabled() {
2799         doReturn(true).when(mDeviceParameterProvider)
2800                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2801         createService();
2802         startSystem();
2803         WakeLock wakeLock = acquireWakeLock("screenBrightWakeLock",
2804                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK);
2805         setCachedUidProcState(wakeLock.mOwnerUid);
2806 
2807         setUncachedUidProcState(wakeLock.mOwnerUid);
2808         assertThat(wakeLock.mDisabled).isFalse();
2809     }
2810 
2811     @Test
testFeatureDisabledProcStateCachedToUncached_screenBrightWakeLockEnabled()2812     public void testFeatureDisabledProcStateCachedToUncached_screenBrightWakeLockEnabled() {
2813         doReturn(false).when(mDeviceParameterProvider)
2814                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2815         createService();
2816         startSystem();
2817         WakeLock wakeLock = acquireWakeLock("screenBrightWakeLock",
2818                 PowerManager.SCREEN_BRIGHT_WAKE_LOCK);
2819         setCachedUidProcState(wakeLock.mOwnerUid);
2820 
2821         setUncachedUidProcState(wakeLock.mOwnerUid);
2822         assertThat(wakeLock.mDisabled).isFalse();
2823     }
2824 
2825     @Test
testFeatureEnabledProcStateCachedToUncached_screenDimWakeLockEnabled()2826     public void testFeatureEnabledProcStateCachedToUncached_screenDimWakeLockEnabled() {
2827         doReturn(true).when(mDeviceParameterProvider)
2828                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2829         createService();
2830         startSystem();
2831         WakeLock wakeLock = acquireWakeLock("screenDimWakeLock",
2832                 PowerManager.SCREEN_DIM_WAKE_LOCK);
2833         setCachedUidProcState(wakeLock.mOwnerUid);
2834 
2835         setUncachedUidProcState(wakeLock.mOwnerUid);
2836         assertThat(wakeLock.mDisabled).isFalse();
2837     }
2838 
2839     @Test
testFeatureDisabledProcStateCachedToUncached_screenDimWakeLockEnabled()2840     public void testFeatureDisabledProcStateCachedToUncached_screenDimWakeLockEnabled() {
2841         doReturn(false).when(mDeviceParameterProvider)
2842                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2843         createService();
2844         startSystem();
2845         WakeLock wakeLock = acquireWakeLock("screenDimWakeLock",
2846                 PowerManager.SCREEN_DIM_WAKE_LOCK);
2847         setCachedUidProcState(wakeLock.mOwnerUid);
2848 
2849         setUncachedUidProcState(wakeLock.mOwnerUid);
2850         assertThat(wakeLock.mDisabled).isFalse();
2851     }
2852 
2853     @Test
testFeatureDynamicallyDisabledProcStateUncachedToCached_fullWakeLockEnabled()2854     public void testFeatureDynamicallyDisabledProcStateUncachedToCached_fullWakeLockEnabled() {
2855         doReturn(true).when(mDeviceParameterProvider)
2856                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2857         ArgumentCaptor<DeviceConfig.OnPropertiesChangedListener> listenerCaptor =
2858                 ArgumentCaptor.forClass(DeviceConfig.OnPropertiesChangedListener.class);
2859         createService();
2860         startSystem();
2861         verify(mDeviceParameterProvider, times(1))
2862                 .addOnPropertiesChangedListener(any(), listenerCaptor.capture());
2863         WakeLock wakeLock = acquireWakeLock("fullWakeLock", PowerManager.FULL_WAKE_LOCK);
2864         setUncachedUidProcState(wakeLock.mOwnerUid);
2865         // dynamically disable the feature
2866         doReturn(false).when(mDeviceParameterProvider)
2867                 .isDisableScreenWakeLocksWhileCachedFeatureEnabled();
2868         listenerCaptor.getValue().onPropertiesChanged(
2869                 new DeviceConfig.Properties("ignored_namespace", null));
2870 
2871         setUncachedUidProcState(wakeLock.mOwnerUid);
2872         assertThat(wakeLock.mDisabled).isFalse();
2873     }
2874 
setCachedUidProcState(int uid)2875     private void setCachedUidProcState(int uid) {
2876         mService.updateUidProcStateInternal(uid, PROCESS_STATE_TOP_SLEEPING);
2877     }
2878 
setUncachedUidProcState(int uid)2879     private void setUncachedUidProcState(int uid) {
2880         mService.updateUidProcStateInternal(uid, PROCESS_STATE_RECEIVER);
2881     }
2882 }
2883