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 22 /** Utility class for interacting with applications via Shell */ 23 class AppHelper( 24 private val instrumentation: Instrumentation, 25 val userId: Int, 26 val packageName: String, 27 private val apkPath: String? = null 28 ) { associatenull29 fun associate(macAddress: MacAddress, role: String = "") = 30 runShellCommand("cmd companiondevice associate $userId $packageName $macAddress $role") 31 32 fun disassociate(macAddress: MacAddress) = 33 runShellCommand("cmd companiondevice disassociate $userId $packageName $macAddress") 34 35 fun disassociateAll() = 36 runShellCommand("cmd companiondevice disassociate-all $userId $packageName") 37 38 fun isInstalled(): Boolean = 39 runShellCommand("pm list packages --user $userId $packageName").isNotBlank() 40 41 fun install() = apkPath?.let { runShellCommand("pm install --user $userId $apkPath") } 42 ?: throw UnsupportedOperationException("APK path is not provided.") 43 uninstallnull44 fun uninstall() = runShellCommand("pm uninstall --user $userId $packageName") 45 46 fun clearData() = runShellCommand("pm clear --user $userId $packageName") 47 48 fun isRoleHolder(role: String) = 49 runShellCommand("cmd role get-role-holders --user $userId $role").contains(packageName) 50 51 fun addToHoldersOfRole(role: String) = 52 runShellCommand("cmd role add-role-holder --user $userId $role $packageName") 53 54 fun removeFromHoldersOfRole(role: String) = 55 runShellCommand("cmd role remove-role-holder --user $userId $role $packageName") 56 57 fun withRole(role: String, block: () -> Unit) { 58 addToHoldersOfRole(role) 59 try { 60 block() 61 } finally { 62 removeFromHoldersOfRole(role) 63 } 64 } 65 runShellCommandnull66 private fun runShellCommand(cmd: String) = instrumentation.runShellCommand(cmd) 67 } 68