• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 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 android.server.wm;
18 
19 import static android.hardware.devicestate.DeviceStateManager.MAXIMUM_DEVICE_STATE;
20 import static android.hardware.devicestate.DeviceStateManager.MINIMUM_DEVICE_STATE;
21 
22 import static org.junit.Assert.assertTrue;
23 
24 import androidx.annotation.NonNull;
25 
26 import com.android.compatibility.common.util.SystemUtil;
27 import com.android.compatibility.common.util.ThrowingRunnable;
28 
29 /** Utility methods for CTS tests requiring the use of {@DeviceStateManager}. */
30 public final class DeviceStateUtils {
31     /**
32      * Runs the supplied {@code runnable} with the
33      * {@link android.Manifest.permission.CONTROL_DEVICE_STATE} permission held.
34      *
35      * @throws Throwable if the runnable throws an exception during execution.
36      */
runWithControlDeviceStatePermission(@onNull ThrowingRunnable runnable)37     public static void runWithControlDeviceStatePermission(@NonNull ThrowingRunnable runnable)
38             throws Throwable {
39         try {
40             SystemUtil.runWithShellPermissionIdentity(runnable,
41                     android.Manifest.permission.CONTROL_DEVICE_STATE);
42         } catch (RuntimeException e) {
43             // runWithShellPermissionIdentity() wraps exceptions thrown by the underlying runnable
44             // in runtime exceptions.
45             Throwable t = e.getCause();
46             if (t != null) {
47                 throw t;
48             }
49             throw e;
50         }
51     }
52 
53     /**
54      * Asserts that the provided {@code state} is in the range
55      * [{@link MINIMUM_DEVICE_STATE}, {@link MAXIMUM_DEVICE_STATE}].
56      */
assertValidState(int state)57     public static void assertValidState(int state) {
58         assertTrue(state >= MINIMUM_DEVICE_STATE);
59         assertTrue(state <= MAXIMUM_DEVICE_STATE);
60     }
61 
DeviceStateUtils()62     private DeviceStateUtils() {}
63 }
64