1 /*
2  * Copyright (C) 2023 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 package com.android.compatibility.common.util;
17 
18 import com.android.tradefed.device.DeviceNotAvailableException;
19 import com.android.tradefed.device.ITestDevice;
20 import com.android.tradefed.invoker.TestInformation;
21 import com.android.tradefed.log.LogUtil.CLog;
22 
23 /**
24  * Helper for user-related needs.
25  */
26 public final class UserUtil {
27 
28     // TODO(b/271153404): static import from tradefed instead
29     private static final String RUN_TESTS_AS_USER_KEY = "RUN_TESTS_AS_USER";
30 
31     private final TestInformation mTestInfo;
32 
UserUtil(TestInformation testInfo)33     public UserUtil(TestInformation testInfo) {
34         mTestInfo = testInfo;
35     }
36 
37     /**
38     * Gets the id of the user running the test.
39     *
40     * <p>Typically, the user running the test is the {@link ITestDevice#getCurrentUser()
41     * current user}, but it could be different if set by a target preparer.
42     */
getTestUserId()43     public int getTestUserId() throws DeviceNotAvailableException {
44         String propValue = mTestInfo.properties().get(RUN_TESTS_AS_USER_KEY);
45         if (propValue != null && !propValue.isEmpty()) {
46             CLog.d("getTestUserId(): returning '%s'", propValue);
47             try {
48                 return Integer.parseInt(propValue);
49             } catch (Exception e) {
50                 String errorMessage = "error parsing property " + RUN_TESTS_AS_USER_KEY
51                         + " (value=" + propValue + ")";
52                 CLog.e("getTestUserId(): %s, e=%s", errorMessage, e);
53                 throw new IllegalStateException(errorMessage, e);
54             }
55         }
56         ITestDevice device = mTestInfo.getDevice();
57         int currentUserId = device.getCurrentUser();
58         CLog.d("getTestUserId(): property %s not set, returning current user (%d)",
59                 RUN_TESTS_AS_USER_KEY, currentUserId);
60         return currentUserId;
61     }
62 }
63