1 /*
2  * Copyright (C) 2018 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.google.common.base.MoreObjects.firstNonNull;
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 import com.android.tradefed.log.LogUtil.CLog;
26 
27 /** A {@link ITargetPreparer} that removes secondary users on teardown. */
28 @OptionClass(alias = "user-cleaner")
29 public class UserCleaner extends BaseTargetPreparer {
30 
31     @Override
setUp(TestInformation testInfo)32     public void setUp(TestInformation testInfo)
33             throws TargetSetupError, BuildError, DeviceNotAvailableException {
34         // no-op
35     }
36 
37     @Override
tearDown(TestInformation testInfo, Throwable e)38     public void tearDown(TestInformation testInfo, Throwable e) throws DeviceNotAvailableException {
39         ITestDevice device = testInfo.getDevice();
40         // treat current user as primary if no primary user found
41         int ownerId = firstNonNull(device.getPrimaryUserId(), device.getCurrentUser());
42         device.switchUser(ownerId);
43 
44         for (Integer id : device.listUsers()) {
45             if (id != ownerId && !device.removeUser(id)) {
46                 CLog.w("Failed to remove user %d", id);
47             }
48         }
49     }
50 }
51