Skip to content

Commit

Permalink
add automatic device serial setter
Browse files Browse the repository at this point in the history
  • Loading branch information
XixianLiang committed Dec 5, 2024
1 parent ec4eec2 commit 7662507
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 36 deletions.
2 changes: 1 addition & 1 deletion kea/app_hm.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def _package_init(self, package_name):
@property
def _dumpsys_package_info(self):
from .adapter.hdc import HDC_EXEC
cmd = [HDC_EXEC, "shell", "bm", "dump", "-n", self.package_name]
cmd = [HDC_EXEC, "-t", self.settings.device_serial, "shell", "bm", "dump", "-n", self.package_name]
r = subprocess.check_output(cmd, text=True)
package_info_str = r.split("\n", maxsplit=1)[-1]
import json
Expand Down
2 changes: 1 addition & 1 deletion kea/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
@dataclass
class Setting:
apk_path: str
device_serial: str ="emulator-5554"
device_serial: str = None
output_dir:str ="output"
is_emulator: bool =True #True for emulator, false for real device.
policy_name: str =input_manager.DEFAULT_POLICY
Expand Down
37 changes: 4 additions & 33 deletions kea/start.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .input_manager import DEFAULT_DEVICE_SERIAL, DEFAULT_POLICY, DEFAULT_TIMEOUT
from .input_manager import DEFAULT_POLICY, DEFAULT_TIMEOUT
from .core import Kea, Setting, start_kea
from .utils import get_yml_config
from .utils import get_yml_config, checkconfig, automatic_set_device_serial

import importlib
import os
Expand All @@ -13,7 +13,7 @@ def parse_args():
parser = argparse.ArgumentParser(description="Start kea to test app.",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-f",nargs="+", action="store",dest="files", help="The python files to be tested.")
parser.add_argument("-d", "--device_serial", action="store", dest="device_serial", default=DEFAULT_DEVICE_SERIAL,
parser.add_argument("-d", "--device_serial", action="store", dest="device_serial", default=None,
help="The serial number of target device (use `adb devices` to find)")
parser.add_argument("-a","--apk", action="store", dest="apk_path",
help="The file path to target APK")
Expand Down Expand Up @@ -112,43 +112,14 @@ def get_mobile_driver(settings:"Setting"):
from kea.pdl_hm import PDL
return PDL(serial=settings.device_serial)

def checkconfig(options):
if not options.apk_path:
raise AttributeError("No target app. Use -a to specify the app")
if not str(options.apk_path).endswith((".apk", ".hap")):
COLOR_YELLOW = "\033[93m"
COLOR_RESET = "\033[0m"
print(f"{COLOR_YELLOW}Warning: {options.apk_path} is not a package file, trying to start with a package name{COLOR_RESET}")
check_package_existance(options)
options.is_package = True
else:
options.is_package = False
if not options.files:
raise AttributeError("No property. Use -f to specify the proeprty")
if not options.output_dir:
raise AttributeError("No output directory. Use -o to specify the output directory.")

def check_package_existance(options):
if not options.is_harmonyos:
cmd = ["adb", "-s", options.serial, "shell", "pm", "list", "package"] if options.serial else ["adb", "shell", "pm", "list", "package"]
dump_packages = subprocess.check_output(cmd, text=True)
package_list = [_.split(":")[-1] for _ in dump_packages.split()]
if not options.package_name in package_list:
raise AttributeError(f"No pacakge named {options.package_name} installed on device.")
else:
from .adapter.hdc import HDC_EXEC
cmd = [HDC_EXEC, "-t", options.device_serial, "shell", "bm", "dump", "-a"] if options.device_serial else [HDC_EXEC, "shell", "bm", "dump", "-a"]
dump_packages = subprocess.check_output(cmd, text=True)
package_list = dump_packages.split()
if not (package_name := options.apk_path) in package_list:
raise AttributeError(f"No pacakge named {package_name} installed on device.")



def main():
options = parse_args()
if options.load_config:
options = parse_ymal_args(options)
automatic_set_device_serial(options=options)
checkconfig(options)
settings = Setting(apk_path=options.apk_path,
device_serial=options.device_serial,
Expand Down
67 changes: 66 additions & 1 deletion kea/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
import warnings
import pkg_resources
import yaml

from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .core import Setting

# logcat regex, which will match the log message generated by `adb logcat -v threadtime`
LOGCAT_THREADTIME_RE = re.compile(
'^(?P<date>\S+)\s+(?P<time>\S+)\s+(?P<pid>[0-9]+)\s+(?P<tid>[0-9]+)\s+'
Expand Down Expand Up @@ -255,4 +260,64 @@ def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
return cls._instances[cls]

def check_package_existance(options):
import subprocess
if not options.is_harmonyos:
cmd = ["adb", "-s", options.device_serial, "shell", "pm", "list", "package"]
dump_packages = subprocess.check_output(cmd, text=True)
package_list = [_.split(":")[-1] for _ in dump_packages.split()]
if not options.package_name in package_list:
raise AttributeError(f"No pacakge named {options.package_name} installed on device.")
else:
from .adapter.hdc import HDC_EXEC
cmd = [HDC_EXEC, "-t", options.device_serial, "shell", "bm", "dump", "-a"]
dump_packages = subprocess.check_output(cmd, text=True)
package_list = dump_packages.split()
if not (package_name := options.apk_path) in package_list:
raise AttributeError(f"No pacakge named {package_name} installed on device.")

def checkconfig(options):
if not options.apk_path:
raise AttributeError("No target app. Use -a to specify the app")
if not str(options.apk_path).endswith((".apk", ".hap")):
COLOR_YELLOW = "\033[93m"
COLOR_RESET = "\033[0m"
print(f"{COLOR_YELLOW}Warning: {options.apk_path} is not a package file, trying to start with a package name{COLOR_RESET}")
check_package_existance(options)
options.is_package = True
else:
options.is_package = False
if not options.files:
raise AttributeError("No property. Use -f to specify the proeprty")
if not options.output_dir:
raise AttributeError("No output directory. Use -o to specify the output directory.")

def automatic_set_device_serial(options):
if options.device_serial is not None:
return

import subprocess
if not options.is_harmonyos:
cmd = ["adb", "devices"]
r = subprocess.check_output(cmd, text=True)
device_list = []
for line in r.splitlines():
if line and line.strip() != "List of devices attached":
device_list.append(line.split()[0])
if len(device_list) == 0:
raise AttributeError("No connected device")
if len(device_list) > 1:
raise AttributeError("Too many attached device, please target it with a device serial")
options.device_serial = device_list[0].strip()
else:
from .adapter.hdc import HDC_EXEC
cmd = [HDC_EXEC, "list", "targets"]
r = subprocess.check_output(cmd, text=True)
device_list = [_.strip() for _ in r.splitlines()]
if len(device_list) == 0:
raise AttributeError("No connected device")
if len(device_list) > 1:
raise AttributeError("Too many attached device, please target it with a device serial")
options.device_serial = device_list[0].strip()

0 comments on commit 7662507

Please sign in to comment.