1 /* 2 * Copyright (C) 2021 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.tradefed.targetprep; 18 19 import static com.android.tradefed.targetprep.UserHelper.RUN_TESTS_AS_USER_KEY; 20 21 import com.android.tradefed.config.OptionClass; 22 import com.android.tradefed.device.DeviceNotAvailableException; 23 import com.android.tradefed.device.ITestDevice; 24 import com.android.tradefed.invoker.TestInformation; 25 26 /** 27 * An {@link ITargetPreparer} that marks that tests should be run on the user (rather than the 28 * current user). 29 * 30 * <p>By default, this will switch user so the system user is in the foreground. 31 * 32 * <p>When running on a device with a headless system user, the user will not be switched by 33 * default, but the tests will still run on that user. 34 */ 35 @OptionClass(alias = "run-on-system-user") 36 public class RunOnSystemUserTargetPreparer extends BaseTargetPreparer { 37 38 private Integer mUserToSwitchTo; 39 40 @Override setUp(TestInformation testInfo)41 public void setUp(TestInformation testInfo) 42 throws TargetSetupError, DeviceNotAvailableException { 43 if (!testInfo.getDevice().isHeadlessSystemUserMode()) { 44 ensureSwitchedToUser(testInfo.getDevice(), 0); 45 } 46 47 testInfo.properties().put(RUN_TESTS_AS_USER_KEY, "0"); 48 } 49 50 @Override tearDown(TestInformation testInfo, Throwable e)51 public void tearDown(TestInformation testInfo, Throwable e) throws DeviceNotAvailableException { 52 testInfo.properties().remove(RUN_TESTS_AS_USER_KEY); 53 if (mUserToSwitchTo != null) { 54 ensureSwitchedToUser(testInfo.getDevice(), mUserToSwitchTo); 55 } 56 } 57 ensureSwitchedToUser(ITestDevice device, int userId)58 private void ensureSwitchedToUser(ITestDevice device, int userId) 59 throws DeviceNotAvailableException { 60 int currentUser = device.getCurrentUser(); 61 62 if (currentUser == userId) { 63 return; 64 } 65 66 if (!device.switchUser(userId)) { 67 throw new IllegalStateException("Could not switch to user " + userId); 68 } 69 mUserToSwitchTo = currentUser; 70 } 71 } 72