blob: e27c7248219561e694edd6ae4f254038b7bde95f [file] [log] [blame]
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +09001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.wm;
18
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070019import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
20import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090021import static android.testing.DexmakerShareClassLoaderRule.runWithDexmakerShareClassLoader;
22import static android.view.Display.DEFAULT_DISPLAY;
23
24import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
25
26import static com.android.dx.mockito.inline.extended.ExtendedMockito.any;
27import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyBoolean;
28import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyInt;
29import static com.android.dx.mockito.inline.extended.ExtendedMockito.anyString;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090030import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing;
31import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
32import static com.android.dx.mockito.inline.extended.ExtendedMockito.eq;
33import static com.android.dx.mockito.inline.extended.ExtendedMockito.mock;
34import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
35import static com.android.dx.mockito.inline.extended.ExtendedMockito.nullable;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070036import static com.android.dx.mockito.inline.extended.ExtendedMockito.spy;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090037import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090038
39import android.app.ActivityManagerInternal;
40import android.app.AppOpsManager;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070041import android.app.usage.UsageStatsManagerInternal;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090042import android.content.BroadcastReceiver;
43import android.content.ContentResolver;
44import android.content.Context;
45import android.content.IntentFilter;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070046import android.content.pm.IPackageManager;
47import android.content.pm.PackageManagerInternal;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090048import android.database.ContentObserver;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070049import android.hardware.display.DisplayManager;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090050import android.hardware.display.DisplayManagerInternal;
51import android.net.Uri;
52import android.os.Handler;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070053import android.os.Looper;
54import android.os.PowerManager;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090055import android.os.PowerManagerInternal;
56import android.os.PowerSaveState;
Riddle Hsu2da2d032019-08-28 21:08:58 +080057import android.os.StrictMode;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090058import android.os.UserHandle;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090059import android.view.InputChannel;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070060import android.view.Surface;
61import android.view.SurfaceControl;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090062
63import com.android.dx.mockito.inline.extended.StaticMockitoSession;
Garfield Tan92b93652019-08-07 17:22:35 -070064import com.android.server.AnimationThread;
65import com.android.server.DisplayThread;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090066import com.android.server.LocalServices;
67import com.android.server.LockGuard;
Riddle Hsu73f53572019-09-23 23:13:01 +080068import com.android.server.UiThread;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090069import com.android.server.Watchdog;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070070import com.android.server.am.ActivityManagerService;
71import com.android.server.appop.AppOpsService;
72import com.android.server.display.color.ColorDisplayService;
Riddle Hsu73f53572019-09-23 23:13:01 +080073import com.android.server.firewall.IntentFirewall;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090074import com.android.server.input.InputManagerService;
Nicholas Sauer3f9249f2019-09-10 20:23:41 -070075import com.android.server.pm.UserManagerService;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070076import com.android.server.policy.PermissionPolicyInternal;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090077import com.android.server.policy.WindowManagerPolicy;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070078import com.android.server.statusbar.StatusBarManagerInternal;
79import com.android.server.uri.UriGrantsManagerInternal;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090080
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +090081import org.junit.rules.TestRule;
82import org.junit.runner.Description;
83import org.junit.runners.model.Statement;
Garfield Tane3d37b52019-07-23 12:43:05 -070084import org.mockito.Mockito;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090085import org.mockito.quality.Strictness;
86
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070087import java.io.File;
Yunfan Chendcb1fcf2019-02-07 19:08:41 +090088import java.util.concurrent.atomic.AtomicBoolean;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090089
90/**
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070091 * JUnit test rule to correctly setting up system services like {@link WindowManagerService}
92 * and {@link ActivityTaskManagerService} for tests.
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090093 */
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +090094public class SystemServicesTestRule implements TestRule {
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +090095
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +090096 private static final String TAG = SystemServicesTestRule.class.getSimpleName();
Yunfan Chendcb1fcf2019-02-07 19:08:41 +090097
Wale Ogunwale8a1860a2019-06-05 08:57:19 -070098 static int sNextDisplayId = DEFAULT_DISPLAY + 100;
99 static int sNextTaskId = 100;
100
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900101 private final AtomicBoolean mCurrentMessagesProcessed = new AtomicBoolean(false);
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700102 private static final int[] TEST_USER_PROFILE_IDS = {};
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900103
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700104 private Context mContext;
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900105 private StaticMockitoSession mMockitoSession;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700106 private ActivityManagerService mAmService;
107 private ActivityTaskManagerService mAtmService;
108 private WindowManagerService mWmService;
109 private TestWindowManagerPolicy mWMPolicy;
Garfield Tane3d37b52019-07-23 12:43:05 -0700110 private WindowState.PowerManagerWrapper mPowerManagerWrapper;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700111 private InputManagerService mImService;
Riddle Hsu73f53572019-09-23 23:13:01 +0800112 private InputChannel mInputChannel;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700113 /**
114 * Spied {@link SurfaceControl.Transaction} class than can be used to verify calls.
115 */
116 SurfaceControl.Transaction mTransaction;
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900117
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900118 @Override
119 public Statement apply(Statement base, Description description) {
120 return new Statement() {
121 @Override
122 public void evaluate() throws Throwable {
123 try {
124 runWithDexmakerShareClassLoader(SystemServicesTestRule.this::setUp);
125 base.evaluate();
126 } finally {
127 tearDown();
128 }
129 }
130 };
131 }
132
133 private void setUp() {
Garfield Tane3d37b52019-07-23 12:43:05 -0700134 mMockitoSession = mockitoSession()
135 .spyStatic(LocalServices.class)
136 .mockStatic(LockGuard.class)
137 .mockStatic(Watchdog.class)
138 .strictness(Strictness.LENIENT)
139 .startMocking();
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900140
Garfield Tane3d37b52019-07-23 12:43:05 -0700141 setUpSystemCore();
142 setUpLocalServices();
143 setUpActivityTaskManagerService();
144 setUpWindowManagerService();
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700145 }
146
147 private void setUpSystemCore() {
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900148 doReturn(mock(Watchdog.class)).when(Watchdog::getInstance);
149
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700150 mContext = getInstrumentation().getTargetContext();
151 spyOn(mContext);
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900152
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700153 doReturn(null).when(mContext)
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900154 .registerReceiver(nullable(BroadcastReceiver.class), any(IntentFilter.class));
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700155 doReturn(null).when(mContext)
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900156 .registerReceiverAsUser(any(BroadcastReceiver.class), any(UserHandle.class),
157 any(IntentFilter.class), nullable(String.class), nullable(Handler.class));
158
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700159 final ContentResolver contentResolver = mContext.getContentResolver();
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900160 spyOn(contentResolver);
161 doNothing().when(contentResolver)
162 .registerContentObserver(any(Uri.class), anyBoolean(), any(ContentObserver.class),
163 anyInt());
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700164 }
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900165
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700166 private void setUpLocalServices() {
167 // Tear down any local services just in case.
168 tearDownLocalServices();
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900169
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700170 // UriGrantsManagerInternal
171 final UriGrantsManagerInternal ugmi = mock(UriGrantsManagerInternal.class);
172 LocalServices.addService(UriGrantsManagerInternal.class, ugmi);
173
174 // AppOpsManager
175 final AppOpsManager aom = mock(AppOpsManager.class);
176 doReturn(aom).when(mContext).getSystemService(eq(Context.APP_OPS_SERVICE));
177
Riddle Hsu73f53572019-09-23 23:13:01 +0800178 // Prevent "WakeLock finalized while still held: SCREEN_FROZEN".
179 final PowerManager pm = mock(PowerManager.class);
180 doReturn(pm).when(mContext).getSystemService(eq(Context.POWER_SERVICE));
181 doReturn(mock(PowerManager.WakeLock.class)).when(pm).newWakeLock(anyInt(), anyString());
182
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700183 // DisplayManagerInternal
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900184 final DisplayManagerInternal dmi = mock(DisplayManagerInternal.class);
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900185 doReturn(dmi).when(() -> LocalServices.getService(eq(DisplayManagerInternal.class)));
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900186
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700187 // ColorDisplayServiceInternal
188 final ColorDisplayService.ColorDisplayServiceInternal cds =
189 mock(ColorDisplayService.ColorDisplayServiceInternal.class);
190 doReturn(cds).when(() -> LocalServices.getService(
191 eq(ColorDisplayService.ColorDisplayServiceInternal.class)));
192
193 final UsageStatsManagerInternal usmi = mock(UsageStatsManagerInternal.class);
194 LocalServices.addService(UsageStatsManagerInternal.class, usmi);
195
196 // PackageManagerInternal
197 final PackageManagerInternal packageManagerInternal = mock(PackageManagerInternal.class);
198 LocalServices.addService(PackageManagerInternal.class, packageManagerInternal);
199 doReturn(false).when(packageManagerInternal).isPermissionsReviewRequired(
200 anyString(), anyInt());
201 doReturn(null).when(packageManagerInternal).getDefaultHomeActivity(anyInt());
202
203 // PowerManagerInternal
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900204 final PowerManagerInternal pmi = mock(PowerManagerInternal.class);
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900205 final PowerSaveState state = new PowerSaveState.Builder().build();
206 doReturn(state).when(pmi).getLowPowerState(anyInt());
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900207 doReturn(pmi).when(() -> LocalServices.getService(eq(PowerManagerInternal.class)));
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900208
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700209 // PermissionPolicyInternal
210 final PermissionPolicyInternal ppi = mock(PermissionPolicyInternal.class);
211 LocalServices.addService(PermissionPolicyInternal.class, ppi);
212 doReturn(true).when(ppi).checkStartActivity(any(), anyInt(), any());
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900213
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700214 // InputManagerService
215 mImService = mock(InputManagerService.class);
Riddle Hsu73f53572019-09-23 23:13:01 +0800216 // InputChannel cannot be mocked because it may pass to InputEventReceiver.
217 final InputChannel[] inputChannels = InputChannel.openInputChannelPair(TAG);
218 inputChannels[0].dispose();
219 mInputChannel = inputChannels[1];
220 doReturn(mInputChannel).when(mImService).monitorInput(anyString(), anyInt());
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900221
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700222 // StatusBarManagerInternal
223 final StatusBarManagerInternal sbmi = mock(StatusBarManagerInternal.class);
224 doReturn(sbmi).when(() -> LocalServices.getService(eq(StatusBarManagerInternal.class)));
225 }
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900226
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700227 private void setUpActivityTaskManagerService() {
228 // ActivityManagerService
Riddle Hsu73f53572019-09-23 23:13:01 +0800229 mAmService = new ActivityManagerService(new AMTestInjector(mContext), null /* thread */);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700230 spyOn(mAmService);
231 doReturn(mock(IPackageManager.class)).when(mAmService).getPackageManager();
Patrick Baumannde37e432019-08-28 09:51:29 -0700232 doNothing().when(mAmService).grantImplicitAccess(
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700233 anyInt(), any(), anyInt(), anyInt());
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900234
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700235 // ActivityManagerInternal
236 final ActivityManagerInternal amInternal = mAmService.mInternal;
237 spyOn(amInternal);
238 doNothing().when(amInternal).trimApplications();
239 doNothing().when(amInternal).updateCpuStats();
240 doNothing().when(amInternal).updateOomAdj();
241 doNothing().when(amInternal).updateBatteryStats(any(), anyInt(), anyInt(), anyBoolean());
242 doNothing().when(amInternal).updateActivityUsageStats(
243 any(), anyInt(), anyInt(), any(), any());
244 doNothing().when(amInternal).startProcess(
245 any(), any(), anyBoolean(), anyBoolean(), any(), any());
246 doNothing().when(amInternal).updateOomLevelsForDisplay(anyInt());
Riddle Hsu73f53572019-09-23 23:13:01 +0800247 doNothing().when(amInternal).broadcastGlobalConfigurationChanged(anyInt(), anyBoolean());
248 doNothing().when(amInternal).cleanUpServices(anyInt(), any(), any());
249 doReturn(UserHandle.USER_SYSTEM).when(amInternal).getCurrentUserId();
250 doReturn(TEST_USER_PROFILE_IDS).when(amInternal).getCurrentProfileIds();
251 doReturn(true).when(amInternal).isCurrentProfile(anyInt());
252 doReturn(true).when(amInternal).isUserRunning(anyInt(), anyInt());
253 doReturn(true).when(amInternal).hasStartedUserState(anyInt());
254 doReturn(false).when(amInternal).shouldConfirmCredentials(anyInt());
255 doReturn(false).when(amInternal).isActivityStartsLoggingEnabled();
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700256 LocalServices.addService(ActivityManagerInternal.class, amInternal);
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900257
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700258 mAtmService = new TestActivityTaskManagerService(mContext, mAmService);
259 LocalServices.addService(ActivityTaskManagerInternal.class, mAtmService.getAtmInternal());
260 }
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900261
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700262 private void setUpWindowManagerService() {
Garfield Tane3d37b52019-07-23 12:43:05 -0700263 mPowerManagerWrapper = mock(WindowState.PowerManagerWrapper.class);
264 mWMPolicy = new TestWindowManagerPolicy(this::getWindowManagerService,
265 mPowerManagerWrapper);
Riddle Hsu2da2d032019-08-28 21:08:58 +0800266 // Suppress StrictMode violation (DisplayWindowSettings) to avoid log flood.
267 DisplayThread.getHandler().post(StrictMode::allowThreadDiskWritesMask);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700268 mWmService = WindowManagerService.main(
Vishnu Nair33197392019-08-30 10:29:37 -0700269 mContext, mImService, false, false, mWMPolicy, mAtmService, StubTransaction::new,
270 () -> mock(Surface.class), (unused) -> new MockSurfaceControlBuilder());
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700271 spyOn(mWmService);
Louis Chang3ff72a82019-12-17 12:12:59 +0800272 spyOn(mWmService.mRoot);
273 // Invoked during {@link ActivityStack} creation.
Louis Chang149d5c82019-12-30 09:47:39 +0800274 doNothing().when(mWmService.mRoot).updateUIDsPresentOnDisplay();
Louis Chang3ff72a82019-12-17 12:12:59 +0800275 // Always keep things awake.
Louis Chang149d5c82019-12-30 09:47:39 +0800276 doReturn(true).when(mWmService.mRoot).hasAwakeDisplay();
Louis Chang3ff72a82019-12-17 12:12:59 +0800277 // Called when moving activity to pinned stack.
Louis Chang149d5c82019-12-30 09:47:39 +0800278 doNothing().when(mWmService.mRoot).ensureActivitiesVisible(any(),
Louis Chang3ff72a82019-12-17 12:12:59 +0800279 anyInt(), anyBoolean(), anyBoolean());
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700280
281 // Setup factory classes to prevent calls to native code.
282 mTransaction = spy(StubTransaction.class);
283 // Return a spied Transaction class than can be used to verify calls.
284 mWmService.mTransactionFactory = () -> mTransaction;
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700285 mWmService.mSurfaceAnimationRunner = new SurfaceAnimationRunner(
286 null, null, mTransaction, mWmService.mPowerManagerInternal);
287
288 mWmService.onInitReady();
289 mAmService.setWindowManager(mWmService);
290 mWmService.mDisplayEnabled = true;
291 mWmService.mDisplayReady = true;
292 // Set configuration for default display
293 mWmService.getDefaultDisplayContentLocked().reconfigureDisplayLocked();
294
Louis Chang3ff72a82019-12-17 12:12:59 +0800295 // Mock default display, and home stack.
Louis Chang149d5c82019-12-30 09:47:39 +0800296 final DisplayContent display = mAtmService.mRootWindowContainer.getDefaultDisplay();
Garfield Tan40428522019-12-06 16:17:44 -0800297 // Set default display to be in fullscreen mode. Devices with PC feature may start their
298 // default display in freeform mode but some of tests in WmTests have implicit assumption on
299 // that the default display is in fullscreen mode.
300 display.setDisplayWindowingMode(WINDOWING_MODE_FULLSCREEN);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700301 spyOn(display);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700302 final ActivityStack homeStack = display.getStack(
303 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME);
304 spyOn(homeStack);
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900305 }
306
307 private void tearDown() {
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700308 // Unregister display listener from root to avoid issues with subsequent tests.
309 mContext.getSystemService(DisplayManager.class)
Louis Chang149d5c82019-12-30 09:47:39 +0800310 .unregisterDisplayListener(mAtmService.mRootWindowContainer);
Adrian Roos1c2e9a12019-08-20 18:23:47 +0200311 // The constructor of WindowManagerService registers WindowManagerConstants and
312 // HighRefreshRateBlacklist with DeviceConfig. We need to undo that here to avoid
313 // leaking mWmService.
314 mWmService.mConstants.dispose();
Charles Chenb9f9e64d2019-11-14 17:13:21 +0800315 mWmService.mHighRefreshRateBlacklist.dispose();
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700316
Riddle Hsu73f53572019-09-23 23:13:01 +0800317 waitUntilWindowManagerHandlersIdle();
Garfield Tan92b93652019-08-07 17:22:35 -0700318 // Needs to explicitly dispose current static threads because there could be messages
319 // scheduled at a later time, and all mocks are invalid when it's executed.
320 DisplayThread.dispose();
Louis Chang3ff72a82019-12-17 12:12:59 +0800321 // Dispose SurfaceAnimationThread before AnimationThread does, so it won't create a new
322 // AnimationThread after AnimationThread disposed, see {@link
323 // AnimatorListenerAdapter#onAnimationEnd()}
324 SurfaceAnimationThread.dispose();
Garfield Tan92b93652019-08-07 17:22:35 -0700325 AnimationThread.dispose();
Riddle Hsu73f53572019-09-23 23:13:01 +0800326 UiThread.dispose();
327 mInputChannel.dispose();
328
329 tearDownLocalServices();
Garfield Tan92b93652019-08-07 17:22:35 -0700330 // Reset priority booster because animation thread has been changed.
331 WindowManagerService.sThreadPriorityBooster = new WindowManagerThreadPriorityBooster();
332
Riddle Hsu73f53572019-09-23 23:13:01 +0800333 mMockitoSession.finishMocking();
Garfield Tane3d37b52019-07-23 12:43:05 -0700334 Mockito.framework().clearInlineMocks();
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700335 }
336
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700337 private static void tearDownLocalServices() {
338 LocalServices.removeServiceForTest(DisplayManagerInternal.class);
339 LocalServices.removeServiceForTest(PowerManagerInternal.class);
340 LocalServices.removeServiceForTest(ActivityManagerInternal.class);
341 LocalServices.removeServiceForTest(ActivityTaskManagerInternal.class);
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900342 LocalServices.removeServiceForTest(WindowManagerInternal.class);
343 LocalServices.removeServiceForTest(WindowManagerPolicy.class);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700344 LocalServices.removeServiceForTest(PackageManagerInternal.class);
345 LocalServices.removeServiceForTest(UriGrantsManagerInternal.class);
346 LocalServices.removeServiceForTest(PermissionPolicyInternal.class);
347 LocalServices.removeServiceForTest(ColorDisplayService.ColorDisplayServiceInternal.class);
348 LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
349 LocalServices.removeServiceForTest(StatusBarManagerInternal.class);
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900350 }
351
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900352 WindowManagerService getWindowManagerService() {
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700353 return mWmService;
354 }
355
356 ActivityTaskManagerService getActivityTaskManagerService() {
357 return mAtmService;
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900358 }
359
Garfield Tane3d37b52019-07-23 12:43:05 -0700360 WindowState.PowerManagerWrapper getPowerManagerWrapper() {
361 return mPowerManagerWrapper;
362 }
363
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900364 void cleanupWindowManagerHandlers() {
Tadashi G. Takaokaa5f7c2c2019-01-09 12:17:14 +0900365 final WindowManagerService wm = getWindowManagerService();
366 if (wm == null) {
367 return;
368 }
369 wm.mH.removeCallbacksAndMessages(null);
370 wm.mAnimationHandler.removeCallbacksAndMessages(null);
Wale Ogunwalec9dfbc52019-11-21 07:19:07 -0800371 // This is a different handler object than the wm.mAnimationHandler above.
372 AnimationThread.getHandler().removeCallbacksAndMessages(null);
Tadashi G. Takaokaa5f7c2c2019-01-09 12:17:14 +0900373 SurfaceAnimationThread.getHandler().removeCallbacksAndMessages(null);
374 }
375
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900376 void waitUntilWindowManagerHandlersIdle() {
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900377 final WindowManagerService wm = getWindowManagerService();
378 if (wm == null) {
379 return;
380 }
381 // Removing delayed FORCE_GC message decreases time for waiting idle.
382 wm.mH.removeMessages(WindowManagerService.H.FORCE_GC);
383 waitHandlerIdle(wm.mH);
384 waitHandlerIdle(wm.mAnimationHandler);
Wale Ogunwalec9dfbc52019-11-21 07:19:07 -0800385 // This is a different handler object than the wm.mAnimationHandler above.
386 waitHandlerIdle(AnimationThread.getHandler());
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900387 waitHandlerIdle(SurfaceAnimationThread.getHandler());
388 }
389
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900390 private void waitHandlerIdle(Handler handler) {
391 synchronized (mCurrentMessagesProcessed) {
Yunfan Chendcb1fcf2019-02-07 19:08:41 +0900392 // Add a message to the handler queue and make sure it is fully processed before we move
393 // on. This makes sure all previous messages in the handler are fully processed vs. just
394 // popping them from the message queue.
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900395 mCurrentMessagesProcessed.set(false);
Yunfan Chendcb1fcf2019-02-07 19:08:41 +0900396 handler.post(() -> {
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900397 synchronized (mCurrentMessagesProcessed) {
398 mCurrentMessagesProcessed.set(true);
399 mCurrentMessagesProcessed.notifyAll();
Yunfan Chendcb1fcf2019-02-07 19:08:41 +0900400 }
401 });
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900402 while (!mCurrentMessagesProcessed.get()) {
Yunfan Chendcb1fcf2019-02-07 19:08:41 +0900403 try {
Tadashi G. Takaokad7aa79a2019-02-08 17:42:37 +0900404 mCurrentMessagesProcessed.wait();
Yunfan Chendcb1fcf2019-02-07 19:08:41 +0900405 } catch (InterruptedException e) {
406 }
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900407 }
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900408 }
409 }
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700410
411 protected class TestActivityTaskManagerService extends ActivityTaskManagerService {
412 // ActivityStackSupervisor may be created more than once while setting up AMS and ATMS.
413 // We keep the reference in order to prevent creating it twice.
414 ActivityStackSupervisor mTestStackSupervisor;
415
416 TestActivityTaskManagerService(Context context, ActivityManagerService ams) {
417 super(context);
418 spyOn(this);
419
420 mSupportsMultiWindow = true;
421 mSupportsMultiDisplay = true;
422 mSupportsSplitScreenMultiWindow = true;
423 mSupportsFreeformWindowManagement = true;
424 mSupportsPictureInPicture = true;
425
426 doReturn(mock(IPackageManager.class)).when(this).getPackageManager();
427 // allow background activity starts by default
428 doReturn(true).when(this).isBackgroundActivityStartsEnabled();
429 doNothing().when(this).updateCpuStats();
430
431 // AppOpsService
432 final AppOpsService aos = mock(AppOpsService.class);
433 doReturn(aos).when(this).getAppOpsService();
434 // Make sure permission checks aren't overridden.
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700435 doReturn(AppOpsManager.MODE_DEFAULT).when(aos).noteOperation(anyInt(), anyInt(),
Philip P. Moltmannda554e42019-12-20 11:21:02 -0800436 anyString(), nullable(String.class), anyBoolean(), nullable(String.class));
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700437
Nicholas Sauer3f9249f2019-09-10 20:23:41 -0700438 // UserManagerService
439 final UserManagerService ums = mock(UserManagerService.class);
440 doReturn(ums).when(this).getUserManager();
441 doReturn(TEST_USER_PROFILE_IDS).when(ums).getProfileIds(anyInt(), eq(true));
442
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700443 setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));
444 ams.mActivityTaskManager = this;
445 ams.mAtmInternal = mInternal;
446 onActivityManagerInternalAdded();
Riddle Hsu73f53572019-09-23 23:13:01 +0800447
448 final IntentFirewall intentFirewall = mock(IntentFirewall.class);
449 doReturn(true).when(intentFirewall).checkStartActivity(
450 any(), anyInt(), anyInt(), nullable(String.class), any());
451 initialize(intentFirewall, null /* intentController */,
452 DisplayThread.getHandler().getLooper());
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700453 spyOn(getLifecycleManager());
454 spyOn(getLockTaskController());
455 spyOn(getTaskChangeNotificationController());
Wale Ogunwale2322bed2019-10-10 17:24:19 +0200456
457 AppWarnings appWarnings = getAppWarningsLocked();
458 spyOn(appWarnings);
459 doNothing().when(appWarnings).onStartActivity(any());
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700460 }
461
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700462 @Override
463 int handleIncomingUser(int callingPid, int callingUid, int userId, String name) {
464 return userId;
465 }
466
467 @Override
468 protected ActivityStackSupervisor createStackSupervisor() {
469 if (mTestStackSupervisor == null) {
470 mTestStackSupervisor = new TestActivityStackSupervisor(this, mH.getLooper());
471 }
472 return mTestStackSupervisor;
473 }
474 }
475
476 /**
477 * An {@link ActivityStackSupervisor} which stubs out certain methods that depend on
478 * setup not available in the test environment. Also specifies an injector for
479 */
480 protected class TestActivityStackSupervisor extends ActivityStackSupervisor {
481
482 TestActivityStackSupervisor(ActivityTaskManagerService service, Looper looper) {
483 super(service, looper);
484 spyOn(this);
485
486 // Do not schedule idle that may touch methods outside the scope of the test.
487 doNothing().when(this).scheduleIdleLocked();
488 doNothing().when(this).scheduleIdleTimeoutLocked(any());
489 // unit test version does not handle launch wake lock
490 doNothing().when(this).acquireLaunchWakelock();
491 doReturn(mock(KeyguardController.class)).when(this).getKeyguardController();
492
493 mLaunchingActivityWakeLock = mock(PowerManager.WakeLock.class);
494
495 initialize();
496 }
497 }
498
499 // TODO: Can we just mock this?
500 private static class AMTestInjector extends ActivityManagerService.Injector {
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700501
Riddle Hsu73f53572019-09-23 23:13:01 +0800502 AMTestInjector(Context context) {
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700503 super(context);
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700504 }
505
506 @Override
507 public Context getContext() {
508 return getInstrumentation().getTargetContext();
509 }
510
511 @Override
512 public AppOpsService getAppOpsService(File file, Handler handler) {
513 return null;
514 }
515
516 @Override
517 public Handler getUiHandler(ActivityManagerService service) {
Riddle Hsu73f53572019-09-23 23:13:01 +0800518 return UiThread.getHandler();
Wale Ogunwale8a1860a2019-06-05 08:57:19 -0700519 }
520
521 @Override
522 public boolean isNetworkRestrictedForUid(int uid) {
523 return false;
524 }
525 }
Tadashi G. Takaoka5a108b82018-12-13 17:09:12 +0900526}