1# Copyright 2024 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""Utility functions to interact with devices for Multidevice test."""
15
16
17import os
18import subprocess
19
20
21def run(cmd):
22  """Replacement for os.system, with hiding of stdout+stderr messages.
23
24  Args:
25    cmd: Command to be executed in string format.
26  """
27  with open(os.devnull, 'wb') as devnull:
28    subprocess.call(cmd.split(), stdout=devnull, stderr=subprocess.STDOUT)
29
30
31def install_apk(device_id, package_name):
32  """Installs an APK on a given device.
33
34  Args:
35    device_id: str; ID of the device.
36    package_name: str; name of the package to be installed.
37  """
38  run(f'adb -s {device_id} install -r -g {package_name}')
39
40
41def check_apk_installed(device_id, package_name):
42  """Verifies that an APK is installed on a given device.
43
44  Args:
45    device_id: str; ID of the device.
46    package_name: str; name of the package that should be installed.
47  """
48  verify_cts_cmd = (
49      f'adb -s {device_id} shell pm list packages | '
50      f'grep {package_name}'
51  )
52  bytes_output = subprocess.check_output(
53      verify_cts_cmd, stderr=subprocess.STDOUT, shell=True
54  )
55  output = str(bytes_output.decode('utf-8')).strip()
56  if package_name not in output:
57    raise AssertionError(
58        f'{package_name} not installed on device {device_id}!'
59    )
60