blob: 1bda412f2f89da1d0c0439c5965f1fde5b7e08cc [file] [log] [blame]
jackqdyulei92681e82017-02-28 11:26:28 -08001/*
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
17package com.android.server.power;
18
Makoto Onuki66a78122017-11-14 15:03:21 -080019import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
20import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
Santos Cordon9b510a22018-08-24 16:42:54 +010021import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
22import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
Makoto Onuki66a78122017-11-14 15:03:21 -080023
24import static com.google.common.truth.Truth.assertThat;
25
Santos Cordon12f92eb2019-02-01 21:28:47 +000026import static org.mockito.ArgumentMatchers.any;
27import static org.mockito.ArgumentMatchers.anyInt;
28import static org.mockito.ArgumentMatchers.anyString;
Santos Cordon9b510a22018-08-24 16:42:54 +010029import static org.mockito.ArgumentMatchers.argThat;
Santos Cordon64a6e612018-08-22 19:27:04 +010030import static org.mockito.ArgumentMatchers.eq;
Santos Cordon9b510a22018-08-24 16:42:54 +010031import static org.mockito.ArgumentMatchers.isA;
32import static org.mockito.ArgumentMatchers.isNull;
Santos Cordon12f92eb2019-02-01 21:28:47 +000033import static org.mockito.Mockito.doAnswer;
Santos Cordon64a6e612018-08-22 19:27:04 +010034import static org.mockito.Mockito.mock;
Santos Cordon9b510a22018-08-24 16:42:54 +010035import static org.mockito.Mockito.spy;
36import static org.mockito.Mockito.verify;
Makoto Onuki66a78122017-11-14 15:03:21 -080037import static org.mockito.Mockito.when;
38
Santos Cordon64a6e612018-08-22 19:27:04 +010039import android.app.ActivityManagerInternal;
Santos Cordon12f92eb2019-02-01 21:28:47 +000040import android.attention.AttentionManagerInternal;
Santos Cordon64a6e612018-08-22 19:27:04 +010041import android.content.Context;
Santos Cordon9b510a22018-08-24 16:42:54 +010042import android.content.ContextWrapper;
43import android.content.Intent;
44import android.content.IntentFilter;
45import android.content.res.Resources;
46import android.hardware.SensorManager;
47import android.hardware.display.AmbientDisplayConfiguration;
Santos Cordon64a6e612018-08-22 19:27:04 +010048import android.hardware.display.DisplayManagerInternal;
jackqdyulei92681e82017-02-28 11:26:28 -080049import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Santos Cordon9b510a22018-08-24 16:42:54 +010050import android.os.BatteryManager;
Santos Cordon64a6e612018-08-22 19:27:04 +010051import android.os.BatteryManagerInternal;
Santos Cordon12f92eb2019-02-01 21:28:47 +000052import android.os.Binder;
Santos Cordon9b510a22018-08-24 16:42:54 +010053import android.os.Handler;
54import android.os.IBinder;
Santos Cordon64a6e612018-08-22 19:27:04 +010055import android.os.Looper;
Salvador Martineza6f7b252017-04-10 10:46:15 -070056import android.os.PowerManager;
jackqdyulei92681e82017-02-28 11:26:28 -080057import android.os.PowerSaveState;
Santos Cordon64a6e612018-08-22 19:27:04 +010058import android.os.SystemClock;
Mark Salyzyne65c0c62017-08-15 07:53:47 -070059import android.os.SystemProperties;
Santos Cordon9b510a22018-08-24 16:42:54 +010060import android.os.UserHandle;
61import android.provider.Settings;
62
63import androidx.test.InstrumentationRegistry;
Makoto Onuki66a78122017-11-14 15:03:21 -080064
Santos Cordon64a6e612018-08-22 19:27:04 +010065import com.android.internal.app.IBatteryStats;
66import com.android.server.LocalServices;
67import com.android.server.SystemService;
68import com.android.server.lights.LightsManager;
69import com.android.server.policy.WindowManagerPolicy;
Santos Cordon9b510a22018-08-24 16:42:54 +010070import com.android.server.power.PowerManagerService.BatteryReceiver;
Santos Cordon64a6e612018-08-22 19:27:04 +010071import com.android.server.power.PowerManagerService.Injector;
72import com.android.server.power.PowerManagerService.NativeWrapper;
Santos Cordon9b510a22018-08-24 16:42:54 +010073import com.android.server.power.PowerManagerService.UserSwitchedReceiver;
Kweku Adams7fb72a42019-01-08 16:08:49 -080074import com.android.server.power.batterysaver.BatterySaverPolicy;
Santos Cordon64a6e612018-08-22 19:27:04 +010075import com.android.server.power.batterysaver.BatterySavingStats;
Makoto Onuki66a78122017-11-14 15:03:21 -080076
Santos Cordon9b510a22018-08-24 16:42:54 +010077import org.junit.After;
78import org.junit.Before;
79import org.junit.Test;
80import org.mockito.ArgumentCaptor;
81import org.mockito.ArgumentMatcher;
jackqdyulei92681e82017-02-28 11:26:28 -080082import org.mockito.Mock;
83import org.mockito.MockitoAnnotations;
84
Santos Cordon12f92eb2019-02-01 21:28:47 +000085import java.util.HashMap;
86import java.util.Map;
87
jackqdyulei92681e82017-02-28 11:26:28 -080088/**
89 * Tests for {@link com.android.server.power.PowerManagerService}
90 */
Santos Cordon9b510a22018-08-24 16:42:54 +010091public class PowerManagerServiceTest {
jackqdyulei92681e82017-02-28 11:26:28 -080092 private static final float PRECISION = 0.001f;
93 private static final float BRIGHTNESS_FACTOR = 0.7f;
94 private static final boolean BATTERY_SAVER_ENABLED = true;
Mark Salyzyne65c0c62017-08-15 07:53:47 -070095 private static final String TEST_LAST_REBOOT_PROPERTY = "test.sys.boot.reason";
jackqdyulei92681e82017-02-28 11:26:28 -080096
Santos Cordon9b510a22018-08-24 16:42:54 +010097 @Mock private BatterySaverPolicy mBatterySaverPolicyMock;
98 @Mock private LightsManager mLightsManagerMock;
99 @Mock private DisplayManagerInternal mDisplayManagerInternalMock;
100 @Mock private BatteryManagerInternal mBatteryManagerInternalMock;
101 @Mock private ActivityManagerInternal mActivityManagerInternalMock;
102 @Mock private AttentionManagerInternal mAttentionManagerInternalMock;
103 @Mock private PowerManagerService.NativeWrapper mNativeWrapperMock;
104 @Mock private Notifier mNotifierMock;
105 @Mock private WirelessChargerDetector mWirelessChargerDetectorMock;
106 @Mock private AmbientDisplayConfiguration mAmbientDisplayConfigurationMock;
107
jackqdyulei92681e82017-02-28 11:26:28 -0800108 private PowerManagerService mService;
109 private PowerSaveState mPowerSaveState;
110 private DisplayPowerRequest mDisplayPowerRequest;
Santos Cordon9b510a22018-08-24 16:42:54 +0100111 private ContextWrapper mContextSpy;
112 private BatteryReceiver mBatteryReceiver;
113 private UserSwitchedReceiver mUserSwitchedReceiver;
114 private Resources mResourcesSpy;
Salvador Martineza6f7b252017-04-10 10:46:15 -0700115
Santos Cordon9b510a22018-08-24 16:42:54 +0100116 private class IntentFilterMatcher implements ArgumentMatcher<IntentFilter> {
117 private final IntentFilter mFilter;
Santos Cordon64a6e612018-08-22 19:27:04 +0100118
Santos Cordon9b510a22018-08-24 16:42:54 +0100119 IntentFilterMatcher(IntentFilter filter) {
120 mFilter = filter;
121 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100122
Santos Cordon9b510a22018-08-24 16:42:54 +0100123 @Override
124 public boolean matches(IntentFilter other) {
125 if (other.countActions() != mFilter.countActions()) {
126 return false;
127 }
128 for (int i = 0; i < mFilter.countActions(); i++) {
129 if (!mFilter.getAction(i).equals(other.getAction(i))) {
130 return false;
131 }
132 }
133 return true;
134 }
135 }
136
137 @Before
jackqdyulei92681e82017-02-28 11:26:28 -0800138 public void setUp() throws Exception {
jackqdyulei92681e82017-02-28 11:26:28 -0800139 MockitoAnnotations.initMocks(this);
140
141 mPowerSaveState = new PowerSaveState.Builder()
142 .setBatterySaverEnabled(BATTERY_SAVER_ENABLED)
143 .setBrightnessFactor(BRIGHTNESS_FACTOR)
144 .build();
Santos Cordon64a6e612018-08-22 19:27:04 +0100145 when(mBatterySaverPolicyMock.getBatterySaverPolicy(
Kweku Adams9f488e22019-01-14 16:25:08 -0800146 eq(PowerManager.ServiceType.SCREEN_BRIGHTNESS)))
jackqdyulei92681e82017-02-28 11:26:28 -0800147 .thenReturn(mPowerSaveState);
Santos Cordon64a6e612018-08-22 19:27:04 +0100148
jackqdyulei92681e82017-02-28 11:26:28 -0800149 mDisplayPowerRequest = new DisplayPowerRequest();
Santos Cordon64a6e612018-08-22 19:27:04 +0100150 addLocalServiceMock(LightsManager.class, mLightsManagerMock);
151 addLocalServiceMock(DisplayManagerInternal.class, mDisplayManagerInternalMock);
152 addLocalServiceMock(BatteryManagerInternal.class, mBatteryManagerInternalMock);
153 addLocalServiceMock(ActivityManagerInternal.class, mActivityManagerInternalMock);
Santos Cordon12f92eb2019-02-01 21:28:47 +0000154 addLocalServiceMock(AttentionManagerInternal.class, mAttentionManagerInternalMock);
Santos Cordon64a6e612018-08-22 19:27:04 +0100155
Santos Cordon9b510a22018-08-24 16:42:54 +0100156 mContextSpy = spy(new ContextWrapper(InstrumentationRegistry.getContext()));
157 mResourcesSpy = spy(mContextSpy.getResources());
158 when(mContextSpy.getResources()).thenReturn(mResourcesSpy);
159
160 mService = new PowerManagerService(mContextSpy, new Injector() {
161 @Override
Santos Cordon64a6e612018-08-22 19:27:04 +0100162 Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
163 SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
164 return mNotifierMock;
165 }
166
Santos Cordon9b510a22018-08-24 16:42:54 +0100167 @Override
Santos Cordon64a6e612018-08-22 19:27:04 +0100168 SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
169 return mock(SuspendBlocker.class);
170 }
171
Santos Cordon9b510a22018-08-24 16:42:54 +0100172 @Override
Santos Cordon64a6e612018-08-22 19:27:04 +0100173 BatterySaverPolicy createBatterySaverPolicy(
174 Object lock, Context context, BatterySavingStats batterySavingStats) {
175 return mBatterySaverPolicyMock;
176 }
177
Santos Cordon9b510a22018-08-24 16:42:54 +0100178 @Override
Santos Cordon64a6e612018-08-22 19:27:04 +0100179 NativeWrapper createNativeWrapper() {
180 return mNativeWrapperMock;
181 }
Santos Cordon9b510a22018-08-24 16:42:54 +0100182
183 @Override
184 WirelessChargerDetector createWirelessChargerDetector(
185 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
186 return mWirelessChargerDetectorMock;
187 }
188
189 @Override
190 AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
191 return mAmbientDisplayConfigurationMock;
192 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100193 });
194 }
195
Santos Cordon9b510a22018-08-24 16:42:54 +0100196 @After
Santos Cordon64a6e612018-08-22 19:27:04 +0100197 public void tearDown() throws Exception {
198 LocalServices.removeServiceForTest(LightsManager.class);
199 LocalServices.removeServiceForTest(DisplayManagerInternal.class);
200 LocalServices.removeServiceForTest(BatteryManagerInternal.class);
201 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
Santos Cordon9b510a22018-08-24 16:42:54 +0100202 Settings.Global.putInt(
203 mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 0);
Santos Cordon64a6e612018-08-22 19:27:04 +0100204 }
205
206 /**
207 * Creates a mock and registers it to {@link LocalServices}.
208 */
209 private static <T> void addLocalServiceMock(Class<T> clazz, T mock) {
210 LocalServices.removeServiceForTest(clazz);
211 LocalServices.addService(clazz, mock);
jackqdyulei92681e82017-02-28 11:26:28 -0800212 }
213
Santos Cordon9b510a22018-08-24 16:42:54 +0100214 private void startSystem() throws Exception {
215 mService.systemReady(null);
216
217 // Grab the BatteryReceiver
218 ArgumentCaptor<BatteryReceiver> batCaptor = ArgumentCaptor.forClass(BatteryReceiver.class);
219 IntentFilter batFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
220 batFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
221 verify(mContextSpy).registerReceiver(batCaptor.capture(),
222 argThat(new IntentFilterMatcher(batFilter)), isNull(), isA(Handler.class));
223 mBatteryReceiver = batCaptor.getValue();
224
225 // Grab the UserSwitchedReceiver
226 ArgumentCaptor<UserSwitchedReceiver> userSwitchedCaptor =
227 ArgumentCaptor.forClass(UserSwitchedReceiver.class);
228 IntentFilter usFilter = new IntentFilter(Intent.ACTION_USER_SWITCHED);
229 verify(mContextSpy).registerReceiver(userSwitchedCaptor.capture(),
230 argThat(new IntentFilterMatcher(usFilter)), isNull(), isA(Handler.class));
231 mUserSwitchedReceiver = userSwitchedCaptor.getValue();
232
233 mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
234 }
235
236 private void forceSleep() {
237 mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
238 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
239 }
240
241 private void forceDream() {
242 mService.getBinderServiceInstance().nap(SystemClock.uptimeMillis());
243 }
244
245 private void forceAwake() {
246 mService.getBinderServiceInstance().wakeUp(SystemClock.uptimeMillis(),
247 PowerManager.WAKE_REASON_UNKNOWN, "testing IPowerManager.wakeUp()", "pkg.name");
248 }
249
250 private void forceDozing() {
251 mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
252 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0);
253 }
254
255 private void setPluggedIn(boolean isPluggedIn) {
256 // Set the callback to return the new state
257 when(mBatteryManagerInternalMock.isPowered(BatteryManager.BATTERY_PLUGGED_ANY))
258 .thenReturn(isPluggedIn);
259 // Trigger PowerManager to reread the plug-in state
260 mBatteryReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_BATTERY_CHANGED));
261 }
262
263 @Test
jackqdyulei92681e82017-02-28 11:26:28 -0800264 public void testUpdatePowerScreenPolicy_UpdateDisplayPowerRequest() {
265 mService.updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
266 assertThat(mDisplayPowerRequest.lowPowerMode).isEqualTo(BATTERY_SAVER_ENABLED);
267 assertThat(mDisplayPowerRequest.screenLowPowerBrightnessFactor)
268 .isWithin(PRECISION).of(BRIGHTNESS_FACTOR);
269 }
Salvador Martineza6f7b252017-04-10 10:46:15 -0700270
Santos Cordon9b510a22018-08-24 16:42:54 +0100271 @Test
Salvador Martineza6f7b252017-04-10 10:46:15 -0700272 public void testGetLastShutdownReasonInternal() {
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700273 SystemProperties.set(TEST_LAST_REBOOT_PROPERTY, "shutdown,thermal");
274 int reason = mService.getLastShutdownReasonInternal(TEST_LAST_REBOOT_PROPERTY);
275 SystemProperties.set(TEST_LAST_REBOOT_PROPERTY, "");
Salvador Martineza6f7b252017-04-10 10:46:15 -0700276 assertThat(reason).isEqualTo(PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN);
277 }
Santos Cordon21e9f2b2017-09-13 11:59:39 -0700278
Santos Cordon9b510a22018-08-24 16:42:54 +0100279 @Test
Santos Cordon21e9f2b2017-09-13 11:59:39 -0700280 public void testGetDesiredScreenPolicy_WithVR() throws Exception {
281 // Brighten up the screen
Michael Wrighte3001042019-02-05 00:13:14 +0000282 mService.setWakefulnessLocked(WAKEFULNESS_AWAKE, PowerManager.WAKE_REASON_UNKNOWN, 0);
Santos Cordon21e9f2b2017-09-13 11:59:39 -0700283 assertThat(mService.getDesiredScreenPolicyLocked()).isEqualTo(
284 DisplayPowerRequest.POLICY_BRIGHT);
285
286 // Move to VR
287 mService.setVrModeEnabled(true);
288 assertThat(mService.getDesiredScreenPolicyLocked()).isEqualTo(
289 DisplayPowerRequest.POLICY_VR);
290
291 // Then take a nap
Michael Wrighte3001042019-02-05 00:13:14 +0000292 mService.setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
293 0);
Santos Cordon21e9f2b2017-09-13 11:59:39 -0700294 assertThat(mService.getDesiredScreenPolicyLocked()).isEqualTo(
295 DisplayPowerRequest.POLICY_OFF);
296
297 // Wake up to VR
Michael Wrighte3001042019-02-05 00:13:14 +0000298 mService.setWakefulnessLocked(WAKEFULNESS_AWAKE, PowerManager.WAKE_REASON_UNKNOWN, 0);
Santos Cordon21e9f2b2017-09-13 11:59:39 -0700299 assertThat(mService.getDesiredScreenPolicyLocked()).isEqualTo(
300 DisplayPowerRequest.POLICY_VR);
301
302 // And back to normal
303 mService.setVrModeEnabled(false);
304 assertThat(mService.getDesiredScreenPolicyLocked()).isEqualTo(
305 DisplayPowerRequest.POLICY_BRIGHT);
Santos Cordon64a6e612018-08-22 19:27:04 +0100306 }
Santos Cordon21e9f2b2017-09-13 11:59:39 -0700307
Santos Cordon9b510a22018-08-24 16:42:54 +0100308 @Test
Santos Cordon64a6e612018-08-22 19:27:04 +0100309 public void testWakefulnessAwake_InitialValue() throws Exception {
310 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
311 }
312
Santos Cordon9b510a22018-08-24 16:42:54 +0100313 @Test
Santos Cordon64a6e612018-08-22 19:27:04 +0100314 public void testWakefulnessSleep_NoDozeSleepFlag() throws Exception {
315 // Start with AWAKE state
Santos Cordon9b510a22018-08-24 16:42:54 +0100316 startSystem();
Santos Cordon64a6e612018-08-22 19:27:04 +0100317 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
318
Santos Cordon9b510a22018-08-24 16:42:54 +0100319 // Take a nap and verify.
Santos Cordon64a6e612018-08-22 19:27:04 +0100320 mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
Santos Cordon9b510a22018-08-24 16:42:54 +0100321 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE);
Santos Cordon64a6e612018-08-22 19:27:04 +0100322 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
Santos Cordon21e9f2b2017-09-13 11:59:39 -0700323 }
Alex Kershaw2418ea92018-10-19 17:17:49 +0100324
Santos Cordon9b510a22018-08-24 16:42:54 +0100325 @Test
326 public void testWakefulnessAwake_AcquireCausesWakeup() throws Exception {
327 startSystem();
328 forceSleep();
329
330 IBinder token = new Binder();
331 String tag = "acq_causes_wakeup";
332 String packageName = "pkg.name";
333
334 // First, ensure that a normal full wake lock does not cause a wakeup
335 int flags = PowerManager.FULL_WAKE_LOCK;
336 mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
337 null /* workSource */, null /* historyTag */);
338 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
339 mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
340
341 // Ensure that the flag does *NOT* work with a partial wake lock.
342 flags = PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
343 mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
344 null /* workSource */, null /* historyTag */);
345 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
346 mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
347
348 // Verify that flag forces a wakeup when paired to a FULL_WAKE_LOCK
349 flags = PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
350 mService.getBinderServiceInstance().acquireWakeLock(token, flags, tag, packageName,
351 null /* workSource */, null /* historyTag */);
352 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
353 mService.getBinderServiceInstance().releaseWakeLock(token, 0 /* flags */);
354 }
355
356 @Test
357 public void testWakefulnessAwake_IPowerManagerWakeUp() throws Exception {
358 startSystem();
359 forceSleep();
360 mService.getBinderServiceInstance().wakeUp(SystemClock.uptimeMillis(),
361 PowerManager.WAKE_REASON_UNKNOWN, "testing IPowerManager.wakeUp()", "pkg.name");
362 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
363 }
364
365 /**
366 * Tests a series of variants that control whether a device wakes-up when it is plugged in
367 * or docked.
368 */
369 @Test
370 public void testWakefulnessAwake_ShouldWakeUpWhenPluggedIn() throws Exception {
371 boolean powerState;
372 startSystem();
373 forceSleep();
374
375 // Test 1:
376 // Set config to prevent it wake up, test, verify, reset config value.
377 when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
378 .thenReturn(false);
379 mService.readConfigurationLocked();
380 setPluggedIn(true);
381 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
382 when(mResourcesSpy.getBoolean(com.android.internal.R.bool.config_unplugTurnsOnScreen))
383 .thenReturn(true);
384 mService.readConfigurationLocked();
385
386 // Test 2:
387 // Turn the power off, sleep, then plug into a wireless charger.
388 // Verify that we do not wake up if the phone is being plugged into a wireless charger.
389 setPluggedIn(false);
390 forceSleep();
391 when(mBatteryManagerInternalMock.getPlugType())
392 .thenReturn(BatteryManager.BATTERY_PLUGGED_WIRELESS);
393 when(mWirelessChargerDetectorMock.update(true /* isPowered */,
394 BatteryManager.BATTERY_PLUGGED_WIRELESS)).thenReturn(false);
395 setPluggedIn(true);
396 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
397
398 // Test 3:
399 // Do not wake up if the phone is being REMOVED from a wireless charger
400 when(mBatteryManagerInternalMock.getPlugType()).thenReturn(0);
401 setPluggedIn(false);
402 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
403
404 // Test 4:
405 // Do not wake if we are dreaming.
406 forceAwake(); // Needs to be awake first before it can dream.
407 forceDream();
408 setPluggedIn(true);
409 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_DREAMING);
410 forceSleep();
411
412 // Test 5:
413 // Don't wake if the device is configured not to wake up in theater mode (and theater
414 // mode is enabled).
415 Settings.Global.putInt(
416 mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 1);
417 mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
418 when(mResourcesSpy.getBoolean(
419 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug))
420 .thenReturn(false);
421 setPluggedIn(false);
422 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
423 Settings.Global.putInt(
424 mContextSpy.getContentResolver(), Settings.Global.THEATER_MODE_ON, 0);
425 mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
426
427 // Test 6:
428 // Don't wake up if we are Dozing away and always-on is enabled.
429 when(mAmbientDisplayConfigurationMock.alwaysOnEnabled(UserHandle.USER_CURRENT))
430 .thenReturn(true);
431 mUserSwitchedReceiver.onReceive(mContextSpy, new Intent(Intent.ACTION_USER_SWITCHED));
432 forceAwake();
433 forceDozing();
434 setPluggedIn(true);
435 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_DOZING);
436
437 // Test 7:
438 // Finally, take away all the factors above and ensure the device wakes up!
439 forceAwake();
440 forceSleep();
441 setPluggedIn(false);
442 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
443 }
444
445 @Test
446 public void testWakefulnessDoze_goToSleep() throws Exception {
447 // Start with AWAKE state
448 startSystem();
449 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
450
451 // Take a nap and verify.
452 mService.getBinderServiceInstance().goToSleep(SystemClock.uptimeMillis(),
453 PowerManager.GO_TO_SLEEP_REASON_APPLICATION, 0);
454 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_DOZING);
455 }
456
457 @Test
Alex Kershaw2418ea92018-10-19 17:17:49 +0100458 public void testWasDeviceIdleFor_true() {
459 int interval = 1000;
460 mService.onUserActivity();
Santos Cordon9b510a22018-08-24 16:42:54 +0100461 SystemClock.sleep(interval + 1 /* just a little more */);
Alex Kershaw2418ea92018-10-19 17:17:49 +0100462 assertThat(mService.wasDeviceIdleForInternal(interval)).isTrue();
463 }
464
Santos Cordon9b510a22018-08-24 16:42:54 +0100465 @Test
Alex Kershaw2418ea92018-10-19 17:17:49 +0100466 public void testWasDeviceIdleFor_false() {
467 int interval = 1000;
468 mService.onUserActivity();
469 assertThat(mService.wasDeviceIdleForInternal(interval)).isFalse();
470 }
Santos Cordon12f92eb2019-02-01 21:28:47 +0000471
Santos Cordon9b510a22018-08-24 16:42:54 +0100472 @Test
Santos Cordon12f92eb2019-02-01 21:28:47 +0000473 public void testForceSuspend_putsDeviceToSleep() {
474 mService.systemReady(null);
475 mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
476
477 // Verify that we start awake
478 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
479
480 // Grab the wakefulness value when PowerManager finally calls into the
481 // native component to actually perform the suspend.
482 when(mNativeWrapperMock.nativeForceSuspend()).then(inv -> {
483 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
484 return true;
485 });
486
487 boolean retval = mService.getBinderServiceInstance().forceSuspend();
488 assertThat(retval).isTrue();
489
490 // Still asleep when the function returns.
491 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_ASLEEP);
492 }
493
Santos Cordon9b510a22018-08-24 16:42:54 +0100494 @Test
Santos Cordon12f92eb2019-02-01 21:28:47 +0000495 public void testForceSuspend_pakeLocksDisabled() {
496 final String tag = "TestWakelockTag_098213";
497 final int flags = PowerManager.PARTIAL_WAKE_LOCK;
Santos Cordon9b510a22018-08-24 16:42:54 +0100498 final String pkg = mContextSpy.getOpPackageName();
Santos Cordon12f92eb2019-02-01 21:28:47 +0000499
500 // Set up the Notification mock to keep track of the wakelocks that are currently
501 // active or disabled. We'll use this to verify that wakelocks are disabled when
502 // they should be.
503 final Map<String, Integer> wakelockMap = new HashMap<>(1);
504 doAnswer(inv -> {
505 wakelockMap.put((String) inv.getArguments()[1], (int) inv.getArguments()[0]);
506 return null;
507 }).when(mNotifierMock).onWakeLockAcquired(anyInt(), anyString(), anyString(), anyInt(),
508 anyInt(), any(), any());
509 doAnswer(inv -> {
510 wakelockMap.remove((String) inv.getArguments()[1]);
511 return null;
512 }).when(mNotifierMock).onWakeLockReleased(anyInt(), anyString(), anyString(), anyInt(),
513 anyInt(), any(), any());
514
515 //
516 // TEST STARTS HERE
517 //
518 mService.systemReady(null);
519 mService.onBootPhase(SystemService.PHASE_BOOT_COMPLETED);
520
521 // Verify that we start awake
522 assertThat(mService.getWakefulness()).isEqualTo(WAKEFULNESS_AWAKE);
523
524 // Create a wakelock
525 mService.getBinderServiceInstance().acquireWakeLock(new Binder(), flags, tag, pkg,
526 null /* workSource */, null /* historyTag */);
527 assertThat(wakelockMap.get(tag)).isEqualTo(flags); // Verify wakelock is active.
528
529 // Confirm that the wakelocks have been disabled when the forceSuspend is in flight.
530 when(mNativeWrapperMock.nativeForceSuspend()).then(inv -> {
531 // Verify that the wakelock is disabled by the time we get to the native force
532 // suspend call.
533 assertThat(wakelockMap.containsKey(tag)).isFalse();
534 return true;
535 });
536
537 assertThat(mService.getBinderServiceInstance().forceSuspend()).isTrue();
538 assertThat(wakelockMap.get(tag)).isEqualTo(flags);
539
540 }
541
Santos Cordon9b510a22018-08-24 16:42:54 +0100542 @Test
Santos Cordon12f92eb2019-02-01 21:28:47 +0000543 public void testForceSuspend_forceSuspendFailurePropogated() {
544 when(mNativeWrapperMock.nativeForceSuspend()).thenReturn(false);
545 assertThat(mService.getBinderServiceInstance().forceSuspend()).isFalse();
546 }
jackqdyulei92681e82017-02-28 11:26:28 -0800547}