• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 android.companion.cts.common
18 
19 import android.app.Instrumentation
20 import android.net.MacAddress
21 import java.lang.UnsupportedOperationException
22 
23 /** Utility class for interacting with applications via Shell */
24 class AppHelper(
25     private val instrumentation: Instrumentation,
26     val userId: Int,
27     val packageName: String,
28     private val apkPath: String? = null
29 ) {
associatenull30     fun associate(macAddress: MacAddress) =
31             runShellCommand("cmd companiondevice associate $userId $packageName $macAddress")
32 
33     fun disassociate(macAddress: MacAddress) =
34             runShellCommand("cmd companiondevice disassociate $userId $packageName $macAddress")
35 
36     fun isInstalled(): Boolean =
37             runShellCommand("pm list packages --user $userId $packageName").isNotBlank()
38 
39     fun install() = apkPath?.let { runShellCommand("pm install --user $userId $apkPath") }
40             ?: throw UnsupportedOperationException("APK path is not provided.")
41 
uninstallnull42     fun uninstall() = runShellCommand("pm uninstall --user $userId $packageName")
43 
44     fun clearData() = runShellCommand("pm clear --user $userId $packageName")
45 
46     fun addToHoldersOfRole(role: String) =
47             runShellCommand("cmd role add-role-holder --user $userId $role $packageName")
48 
49     fun removeFromHoldersOfRole(role: String) =
50             runShellCommand("cmd role remove-role-holder --user $userId $role $packageName")
51 
52     fun withRole(role: String, block: () -> Unit) {
53         addToHoldersOfRole(role)
54         try {
55             block()
56         } finally {
57             removeFromHoldersOfRole(role)
58         }
59     }
60 
runShellCommandnull61     private fun runShellCommand(cmd: String) = instrumentation.runShellCommand(cmd)
62 }