Python调用adb实现自动化安装Apk

 

# -*- encoding=utf8 -*-
__author__ = "Lee.li"
"""
命名规则:
1.模块尽量使用小写命名,首字母保持小写,尽量不要用下划线(除非多个单词,且数量不多的情况)
2.类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头
3.函数名一律小写,如有多个单词,用下划线隔开,私有函数在函数前加一个下划线_
4.变量名首字母尽量小写, 如有多个单词,用下划线隔开,后续字母大写
5.常量采用全大写,如有多个单词,使用下划线隔开
"""

import inspect
import queue
import threading
from Views.multi_processframe.ProjectTools import common
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from airtest.core.android.adb import ADB
from airtest.utils.apkparser import APK
from Views.paaS import tools
from Views.multi_processframe.ProjectTools.path import CONFIGPATH

index_print = print
adb = ADB().adb_path  # 获取内置adb路径
queue = queue.Queue()  # queue线程通讯


def print(*args, **kwargs):
    index_print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), *args, **kwargs)


class AndroidTools:

    def __init__(self, momentDevices=""):

        self._rootPath = CONFIGPATH  # 获取当前目录根目录
        self._configPath = self._rootPath  # 获取config.ini的路径
        self._discerncode = common.get_value(self._configPath, 'discerncode')[0]  # 获取下载识别码
        self._testCase = common.get_value(self._configPath, 'testCase')  # 获取测试列表
        self._email = common.get_value(self._configPath, 'email')[0]  # 获取邮箱
        self._packageName = common.get_value(self._configPath, 'packageName')[0]  # 获取安装包名称
        self._packagePath = common.get_value(self._configPath, 'packagePath')[0]  # 获取安装包路径
        self._devicesList = common.get_value(self._configPath, 'devicesList')  # 获取配置设备列表
        self._installApk = common.get_value(self._configPath, 'installApk')[0]  # 获取安装测试包开关 1 为打开 0 为关闭
        self._testType = common.get_value(self._configPath, 'testType')[0]  # 获取测试类型开关 1 兼容 0 为分布
        self._performanceType = common.get_value(self._configPath, 'performanceType')[0]  # 获取性能测试开关 1 为打开 0 为关闭
        self._storage_by_exce = common.get_value(self._configPath, "storage_by_exce")[0]  # 获取性能报告方式 1 为excle 0 为json
        self._username = common.get_value(self._configPath, 'username')  # 获取账号
        self._password = common.get_value(self._configPath, 'password')[0]  # 获取密码
        self._uwatype = common.get_value(self._configPath, "uwatype")[0]  # 获取uwa测试判断
        self._testuwacase = common.get_value(self._configPath, "testuwacase")  # 获取uwa测试用例
        self._number = common.get_value(self._configPath, "number")[0]  # 获取uwa测试用例
        self._server = common.get_value(self._configPath, 'server')[0]  # 获取server
        if self._server == "1server":
            self._server = "日补丁qq android一服"
        elif self._server == "2server":
            self._server = "日补丁qq android二服"
        self._momentDevices = momentDevices  # 获取连接的设备
        if ':' in self._momentDevices:
            self._devicesName = self._momentDevices.split(':')[1]
        else:
            self._devicesName = self._momentDevices
        self._activityName = common.get_value(self._configPath, 'activityName')[0]  # 获取测试包的界面活动名
        if self._activityName == '':
            self._activityName = APK(self.get_apkpath()).activities[0]  # 如果活动包名没有填,就通过APK的activities方法,用包的路径获取活动名

    def get_discerncode(self):
        """
        获取下载状态识别码
        :return:
        """
        return self._discerncode

    def get_uwatype(self):
        """
        获取config中的uwatype
        :return:
        """
        return self._uwatype

    def get_number(self):
        """
        获取config中的uwatype
        :return:
        """
        return self._number

    def get_testuwacase(self):
        """
        获取uwa测试脚本
        :return:
        """
        return self._testuwacase

    def get_server(self):
        """
        获取config中的账号名称
        :return:
        """
        return self._server


    def get_password(self):
        """
        获取config中的账号名称
        :return:
        """
        return self._password

    def get_username(self):
        """
        获取config中的账号名称
        :return:
        """
        return self._username

    def get_rootpath(self):
        """
        获取当前路径的根目录绝对路径
        :return:
        """
        return self._rootPath

    def get_configpath(self):
        """
        获取config路径
        :return:
        """
        return self._configPath

    def get_testcase(self):
        """
        获取需要测试的测试用例
        :return:
        """
        return self._testCase

    def get_email(self):
        """
        获取需要测试的测试用例
        :return:
        """
        return self._email

    def get_packagename(self):
        """
        获得config配置中的包名
        :return:
        """
        return self._packageName

    def get_apkpath(self):
        """
        获取apk的本地路径
        :return:
        """
        return self._packagePath

    def get_deviceslist(self):
        """
        获得config配置中的设备列表
        :return:
        """
        return self._devicesList

    def get_installapk(self):
        """
        获取是否需要安装开关
        :return:
        """
        return self._installApk

    def get_testtype(self):
        """
        获取测试类型开关 1 兼容 0 为分布
        :return:
        """
        return self._testType

    def get_performancetype(self):
        """
        获取性能测试开关 1 为打开 0 为关闭
        :return:
        """
        return self._performanceType

    def get_momentdevices(self):
        """
        获取当前设备
        :return:
        """
        return self._momentDevices

    def get_devicesname(self):
        """
        获取当前设备的ID
        :return:
        """
        return self._devicesName

    def get_activityname(self):
        """
        获得config配置中的Activity类名
        :return:
        """
        return self._activityName

    def get_storage_by_excel(self):
        """
        获得config配置中的excel配置 1 使用exlce 0 使用json
        :return:
        """
        return self._storage_by_exce

    def get_workdevices(self):
        """
        实时读取连接的设备
        :return:
        """
        deviceslist = []
        for devices in os.popen(adb + " devices"):
            if "\t" in devices:
                if devices.find("emulator") < 0:
                    if devices.split("\t")[1] == "deviceconnect\n":
                        deviceslist.append(devices.split("\t")[0])
        return deviceslist

    def thread_installapk(self):
        """
        采用多线程进行安装包操作
        :return:
        """
        installapk = self.get_installapk()
        if installapk == 'False':
            return 'Skip'
        device = self.get_momentdevices()
        try:
            installthread = threading.Thread(target=self.install, args=(self,))
            installthread.start()
            installresult = queue.get()
            authorization = threading.Thread(target=self.authorization, args=(self,))
            authorization.start()
            installthread.join()
            authorization.join()
            if installresult == "Install Success":
                return "Success"
            else:
                return "Fail"
        except Exception as e:
            print(e)
        pass

    def install(self):
        """
        实现测试包安装
        :return:
        """
        devices = self.get_momentdevices()
        packname = self.get_packagename()
        apkpath = self.get_apkpath()
        if not os.path.isfile(apkpath):
            print("apk不存在,需要apk文件")
            tools.rewrite_config("installApk", "False")
            return 'Skip'
        installapk = self.get_installapk()
        if installapk == 'False':
            return 'Skip'
        try:
            # if self.check_install():
            #     uninstallcommand = adb + " -s " + str(devices) + " uninstall " + packname
            #     print(f"正在卸载{devices}上的游戏.................")
            #     os.popen(uninstallcommand)
            time.sleep(3)
            print(apkpath)
            print(f"正在给{devices}安装apk.................")
            time1 = time.time()
            # ADB(devices).install_app(apkpath, replace=True, install_options=["-g"])
            print(time.time()-time1)
            # time.sleep(150)
            if self.check_install():
                print(f'{devices}上安装成功')
                return "Success"
            else:
                print(f'{devices}上安装失败')
                return "Fail"
        except Exception as e:
            print(f'{devices}上安装异常,{e}')
            return "Fail"

    # def install(self):
    #     """
    #     实现测试包安装
    #     :return:
    #     """
    #     devices = self.get_momentdevices()
    #     apkpath = self.get_apkpath()
    #     packname = self.get_packagename()
    #     installapk = self.get_installapk()
    #     if installapk == 'False':
    #         return 'Skip'
    #     try:
    #         if self.check_install():
    #             uninstallcommand = adb + " -s " + str(devices) + " uninstall " + packname
    #             print(f"正在卸载{devices}上的游戏.................")
    #             os.popen(uninstallcommand)
    #         time.sleep(7)
    #         installcommand = adb + " -s " + str(devices) + " install -r " + apkpath
    #         print(f"正在给{devices}安装游戏.................")
    #         os.popen(installcommand)
    #         time.sleep(15)
    #         if self.check_install():
    #             print(f'{devices}上安装成功')
    #             queue.put("Install Success")
    #             return True
    #         else:
    #             print(f'{devices}上安装失败')
    #             queue.put("Install Fail")
    #             return False
    #     except Exception as e:
    #         print(f'{devices}上安装异常,{e}')
    #         queue.put("Install Fail")

    def check_install(self):
        """
        检查设备否安装测试包
        :return:
        """
        devices = self.get_momentdevices()
        testpackage = self.get_packagename()
        command = adb + f" -s {devices} shell pm list packages"
        print(command)
        temp = os.popen(command)
        for packagename in temp:
            if testpackage in packagename and testpackage != '':
                print(f"设备{devices}已经安装了游戏")
                return True
        print(f"设备{devices}没有安装{testpackage}")
        return False

    def authorization(self):
        """
        安卓手机权限点击
        TODO 此方法暂未完成,后续需要根据设备型号来编写授权操作
        :return:
        """
        devices = self.get_momentdevices()
        pocoandroid = AndroidUiautomationPoco(device=devices, use_airtest_input=True, screenshot_each_action=False)
        times = 5
        if devices == "127.0.0.1:62001":
            count = 0
            # 找n次或找到对象以后跳出,否则等5秒重试。
            while True:
                print(devices, "安装点击,循环第", count, "次")
                if count >= times:
                    break
                if pocoandroid("vivo:id/vivo_adb_install_ok_button").exists():
                    pocoandroid("vivo:id/vivo_adb_install_ok_button").click()
                    time.sleep(2)
                    if pocoandroid("android.widget.FrameLayout").offspring("android:id/buttonPanel").offspring(
                            "android:id/button1").exists():
                        pocoandroid("android.widget.FrameLayout").offspring("android:id/buttonPanel").offspring(
                            "android:id/button1").click()
                    break
                else:
                    time.sleep(5)
                count += 1
        elif devices == "127.0.0.1:62025":
            count = 0
            while True:
                print(devices, "安装点击,循环第", count, "次")
                if count >= times:
                    break
                if pocoandroid("com.android.packageinstaller:id/continue_button").exists():
                    pocoandroid("com.android.packageinstaller:id/continue_button").click()
                else:
                    time.sleep(5)
                count += 1

    def get_androidversion(self):
        """
        获取安卓版本号
        :return: 返回安卓大版本号转换为int类型
        """
        command = adb + f' -s {self.get_momentdevices()} shell getprop ro.build.version.release'
        version = os.popen(command).read()[0]
        return int(version)

    def get_allocated_memory(self):
        """
        判断给定设备运行指定apk时的内存占用
        :return:返回内存数据,当程序退出返回N/a
        """
        command = adb + f' -s {self.get_momentdevices()} shell dumpsys meminfo {self.get_packagename()}'
        tempmemory = os.popen(command)
        for line in tempmemory:
            memorylist = line.strip().split(' ')
            if memorylist[0] == 'TOTAL':
                while '' in memorylist:
                    memorylist.remove('')
                packagememory = format(int(memorylist[1]) / 1024, ".2f")
                queue.put(packagememory)
                return packagememory
        queue.put('N/a')
        return 'N/a'

    def get_totalmemory(self):
        """
        设备运行内存总占用
        :return:
        """
        command = adb + f' -s {self.get_momentdevices()} shell dumpsys meminfo'
        tempmemory = os.popen(command)
        totalram = 0
        for line in tempmemory:
            memorylist = line.strip().split(':')
            if memorylist[0] == 'Total RAM':
                if self.get_androidversion() <= 6:
                    totalram = format(int(memorylist[1].split(" ")[1]) / 1024, '.2f')
                else:
                    totalram = format(int(memorylist[1].split("K")[0].replace(',', '')) / 1024, '.2f')
                break
        queue.put(totalram)
        return totalram

    def get_freememory(self):
        """
        设备运行空闲内存
        :return:
        """
        command = adb + f' -s {self.get_momentdevices()} shell dumpsys meminfo'
        tempmemory = os.popen(command)
        freeram = 0
        for line in tempmemory:
            memorylist = line.strip().split(':')
            if memorylist[0] == 'Free RAM':
                if self.get_androidversion() <= 6:
                    freeram = format(int(memorylist[1].split(" ")[1]) / 1024, '.2f')
                else:
                    freeram = format(int(memorylist[1].split("K")[0].replace(',', '')) / 1024, '.2f')
                break
        queue.put(freeram)
        return freeram

    def get_usedmemory(self):
        """
        设备运行总使用内存
        :return:
        """
        command = adb + f' -s {self.get_momentdevices()} shell dumpsys meminfo'
        tempmemory = os.popen(command)
        usedram = 0
        for line in tempmemory:
            memorylist = line.strip().split(':')
            if memorylist[0] == 'Used RAM':
                if self.get_androidversion() <= 6:
                    usedram = format(int(memorylist[1].split(" ")[1]) / 1024, '.2f')
                else:
                    usedram = format(int(memorylist[1].split("K")[0].replace(',', '')) / 1024, '.2f')
                break
        queue.put(usedram)
        return usedram

    def get_memoryinfo(self):
        """
        一次dump获取Total/Free/Used内存
        :return:
        """
        command = adb + f' -s {self.get_momentdevices()} shell dumpsys meminfo'
        tempmemory = os.popen(command)
        androidversion = self.get_androidversion()
        for line in tempmemory:
            memorylist = line.strip().split(':')
            if memorylist[0] == 'Total RAM':
                if androidversion <= 6:
                    totalram = format(int(memorylist[1].split(" ")[1]) / 1024, '.2f')
                else:
                    totalram = format(int(memorylist[1].split("K")[0].replace(',', '')) / 1024, '.2f')
            elif memorylist[0] == 'Free RAM':
                if androidversion <= 6:
                    freeram = format(int(memorylist[1].split(" ")[1]) / 1024, '.2f')
                else:
                    freeram = format(int(memorylist[1].split("K")[0].replace(',', '')) / 1024, '.2f')
            elif memorylist[0] == 'Used RAM':
                if androidversion <= 6:
                    usedram = format(int(memorylist[1].split(" ")[1]) / 1024, '.2f')
                else:
                    usedram = format(int(memorylist[1].split("K")[0].replace(',', '')) / 1024, '.2f')
        queue.put(totalram, freeram, usedram)
        return totalram, freeram, usedram

    def get_totalcpu(self):
        """
        CPU总占用,os8以上CPU不一定是100%,
        :return:
        """
        command = adb + f' -s {self.get_momentdevices()} shell top -n 1'
        tempcpu = os.popen(command)
        totalcpu = ''
        maxcpu = ''
        for line in tempcpu:
            temp = line.strip().split(' ')
            while '' in temp:
                temp.remove('')
            if len(temp) > 8:
                if '%cpu' in temp[0]:
                    maxcpu = temp[0]
                    totalcpu = f"{int(temp[0].replace('%cpu', '')) - int(temp[4].replace('%idle', ''))}%"
                    break
        queue.put(totalcpu, maxcpu)
        return totalcpu, maxcpu

    def get_allocated_cpu(self):
        """
        获取运行的测试包占用的cpu
        :return:
        """
        packname = self.get_packagename()[0:15]
        if common.get_system() == 'Windows':
            command = adb + f' -s {self.get_momentdevices()} shell top -n 1 |findstr {packname}'
        else:
            command = adb + f' -s {self.get_momentdevices()} shell top -n 1 |grep {packname}'
        tempcpu = os.popen(command).read()
        cpu = ''
        if tempcpu == '':
            queue.put('N/a')
            return 'N/a'
        else:
            tempcpu = tempcpu.split(' ')
            while '' in tempcpu:
                tempcpu.remove('')
            if tempcpu.count(f'{packname}') == 2:
                tempcpu = tempcpu[(tempcpu.index(f'{packname}\n')) + 1:]
                cpu = f'{tempcpu[8]}%'
            else:
                cpu = f'{tempcpu[8]}%'
            queue.put(cpu)
            return cpu

    def get_fps(self):
        device = self.get_momentdevices()
        package = self.get_packagename()
        activity = self.get_activityname()
        androidversion = self.get_androidversion()
        command = ""
        if androidversion < 7:
            command = adb + " -s {} shell dumpsys SurfaceFlinger --latency 'SurfaceView'".format(device)
        elif androidversion == 7:
            command = adb + " -s {} shell \"dumpsys SurfaceFlinger --latency 'SurfaceView - {}/{}'\"".format(device,
                                                                                                             package,
                                                                                                             activity)
        elif androidversion > 7:
            command = adb + " -s {} shell \"dumpsys SurfaceFlinger --latency 'SurfaceView - {}/{}#0'\"".format(device,
                                                                                                               package,
                                                                                                               activity)
        tempdata = os.popen(command)
        if not tempdata:
            print("nothing")
            return (None, None)
        timestamps = []
        nanoseconds_per_second = 1e9  # 定义纳秒
        refresh_period = 16666666 / nanoseconds_per_second  # 定义刷新间隔
        pending_fence_timestamp = (1 << 63) - 1  # 定义挂起时间戳
        for line in tempdata:
            temp = line.strip().split("\t")
            if len(temp) != 3:  # 剔除非数据列
                continue
            timestamp = float(temp[1])  # 取中间一列数据
            if timestamp == pending_fence_timestamp:  # 当时间戳等于挂起时间戳时,舍弃
                continue
            timestamp /= nanoseconds_per_second
            if timestamp != 0:  # 安卓7的adbdump提供255行数据,127行0以及128行真实数据,所以需要将0行剔除
                timestamps.append(timestamp)
        frame_count = len(timestamps)  # 获得总帧数
        frame_lengths, normalized_frame_lengths = self.GetNormalizedDeltas(timestamps, refresh_period,
                                                                           0.5)  # 获取帧列表总长、规范化帧列表总长
        if len(frame_lengths) < frame_count - 1:
            print('Skipping frame lengths that are too short.')
        frame_count = len(frame_lengths) + 1
        # 数据不足时,返回None
        if not refresh_period or not len(timestamps) >= 3 or len(frame_lengths) == 0:
            print("未收集到有效数据")
            return "N/a"
        # 总秒数为时间戳序列最后一位减第一位
        seconds = timestamps[-1] - timestamps[0]
        fps = int(round((frame_count - 1) / seconds))
        return fps

    def GetNormalizedDeltas(self, data, refresh_period, min_normalized_delta=None):
        deltas = [t2 - t1 for t1, t2 in zip(data, data[1:])]
        if min_normalized_delta != None:
            deltas = filter(lambda d: d / refresh_period >= min_normalized_delta, deltas)
        return (list(deltas), [delta / refresh_period for delta in deltas])


if __name__ == "__main__":
    device = "2d9096f3"
    common.deviceconnect(device)
    P = AndroidTools(device)
    print(P.get_testuwacase())
    # P.get_uwatype()
    # P.get_performancetype()
    # print(install)  # 启动app
    # p = Performance()
    # p.check_install()
    # device = "127.0.0.1:62001"
    # p = Performance()
    # while 1 == 1:
    #     print(p.get_allocated_cpu(device))
    #     print(p.get_totalcpu(device))
    # p.get_workdevices()
    # p.get_storage_by_excel()
    # print(p.get_workdevices())
    # print(p.get_storage_by_excel())

# -*- coding: utf-8 -*-

"""
@Time    : 2021/1/28 15:11
@Author   : Liam
@File    : adbutil.py
@Description : 文件说明
"""

import sys

sys.path.append(sys.path[0] + '/../..')
from airtest.core.android.adb import ADB
import threading
import os
import re
import time
import traceback
import platform
from airtest.core.error import AdbShellError, AdbError


class AdbClient(ADB):
    """adb client object class"""

    _instances = []
    status_device = "device"
    status_offline = "offline"
    SHELL_ENCODING = "utf-8"

    def __init__(self, serialno=None, adb_path=None, server_addr=None, display_id=None, input_event=None):
        super().__init__(serialno=None, adb_path=None, server_addr=None, display_id=None, input_event=None)
        self.serialno = serialno
        self.adb_path = adb_path or self.builtin_adb_path()
        self.display_id = display_id
        self.input_event = input_event
        self._set_cmd_options(server_addr)
        self.connect()
        self._sdk_version = None
        self._line_breaker = None
        self._display_info = {}
        self._display_info_lock = threading.Lock()
        self._forward_local_using = []
        self.__class__._instances.append(self)

    def remove_tcp(self):
        """干掉新开的tcp"""
        forward = self.cmd(f'forward --list')
        for i in forward.split("\n"):
            if "5001" in i:
                remove = i.split(" ")[1].split(":")[1]
                try:
                    self.cmd(f'forward --remove tcp:{remove}')
                except AdbShellError:
                    pass
                    print(f"tcp:{remove}端口不存在")
                except AdbError:
                    pass
                    # print(f"没有找到tcp:{remove}")

    def unlock(self):
        """
        通过adb解锁
        """
        self.shell('input keyevent MENU')
        self.shell('input keyevent BACK')

    def power_key(self):
        self.shell('input keyevent POWER')

    def up_unlock(self):
        """上滑解锁"""
        for i in range(2):
            self.swipe((500, 1800), (500, 500), duration=300)
        self.shell('input keyevent HOME')

    def right_unlock(self):
        """右滑解锁"""
        for i in range(2):
            self.swipe((250, 1800), (800, 1800), duration=300)
        self.shell('input keyevent HOME')

    def activate_screen(self):
        """解锁-判断屏幕是否亮屏,执行解锁操作"""
        if not self.is_screenon():
            self.power_key()
            self.up_unlock()
        else:
            self.up_unlock()

    def get_device_name(self):
        """
        封装获取设备名称
        :return: 通过蓝牙返回设备名称
        """
        device_name_tmp = self.shell(f'dumpsys bluetooth_manager | grep name')
        device_name = device_name_tmp.split(":")[1].split("\n")[0].split(" ")[1]
        return device_name

    def os_version(self):
        """
        获取安卓版本号
        :return: 返回安卓大版本号转换为int类型
        """
        tmp_version = self.getprop('ro.build.version.release')
        version = re.findall(r'\d+', tmp_version)[0]
        return int(version)

    def get_devices_list(self):
        """
        封装获取adb列表
        :return:获取当前连接的全部设备
        """
        devices_list = os.popen(self.adb_path + ' devices')
        return devices_list

    # def get_apk_versionName(self, package_name):
    #     """
    #     封装获取apk版本号防范
    #     @return: apk版本号
    #
    #     tmp = list(adb.get_apk_versionName(package))
    #     tmp.insert(-2, '.')
    #     apk_versionName = ''.join(tmp)
    #     """
    #     tmp_apk_versionName = self.shell(f'dumpsys package {package_name} | grep versionName')
    #     tmp_apk_versionName = list(tmp_apk_versionName.split('=')[1].replace("\n", '').replace("\r", ''))
    #     tmp_apk_versionName.insert(-1, '.')
    #     apk_versionName = ''.join(tmp_apk_versionName)
    #     return apk_versionName

    def get_apk_versionName(self, package_name):
        """
        封装获取apk版本号防范
        @return: apk版本号
        """
        cmd = f'dumpsys package {package_name} | grep versionName'
        tmp_apk_versionName = self.shell(cmd)
        tmp_apk_versionName = list(tmp_apk_versionName.split('=')[1].replace("\n", '').replace("\r", ''))
        tmp_apk_versionName.insert(-1, '.')
        apk_versionName = ''.join(tmp_apk_versionName)
        return apk_versionName

    def get_firstInstallTime(self, package_name):
        """
        封装获取apk第一次安装时间方法
        @return: apk安装时间
        """
        tmp_apk_firstInstallTime = self.shell(f'dumpsys package {package_name}  | grep firstInstallTime')
        apk_firstInstallTime = tmp_apk_firstInstallTime.split('=')[1].replace("\n", '')
        return apk_firstInstallTime

    def install_app_project(self, package_name, apk_path):
        try:
            if self.check_install(package_name):
                print(f'{self.serialno} Exist Old Package, Doing Uninstall')
                self.uninstall_app(package_name)
                print(f'{self.serialno} Uninstall Done')
            start_time = time.time()
            print(f'{self.serialno} Being Installed')
            self.install_app(apk_path, replace=True, install_options=["-g"])
            print(f'Install time: {round(time.time() - start_time, 2)}S')
            if self.check_install(package_name):
                return True
            else:
                return False
        except Exception as e:
            print(f'{self.serialno} Install Error {traceback.format_exc(), e}')
            return False

    def check_install(self, package_name):
        output = self.shell(['dumpsys', 'package', package_name])
        pattern = r'Package\s+\[' + str(package_name) + '\]'
        match = re.search(pattern, output)
        if match is None:
            return False
        return True

    # def get_allocated_memory(self):
    #     """
    #     判断给定设备运行指定apk时的内存占用
    #     :return:返回内存数据,当程序退出返回N/a
    #     """
    #     try:
    #         tem_memory = self.shell(f'dumpsys meminfo {self.package_name} |grep TOTAL:')
    #         package_memory_data = re.findall(r'\d+', tem_memory)[0]
    #         package_memory = format(int(package_memory_data) / 1024, ".2f")
    #         return package_memory
    #     except Exception as e:
    #         print(e)
    #         return 'N/a'
    #
    # def get_total_memory(self):
    #     """
    #     设备运行内存总占用
    #     :return:
    #     """
    #     tmp_memory_data = self.shell('dumpsys meminfo | grep Total')
    #     tmp_memory = re.findall(r'\d+', tmp_memory_data)
    #     memory_list = ''
    #     for i in range(len(tmp_memory)):
    #         memory_list = memory_list+tmp_memory[i]
    #     total_ram = format(int(memory_list) / 1024, '.2f')
    #     return total_ram
    #
    # def get_free_memory(self):
    #     """
    #     设备运行空闲内存
    #     :return:
    #     """
    #     tmp_memory_data = self.shell('dumpsys meminfo | grep Free')
    #     if 'kB' in tmp_memory_data:
    #         tmp_memory = re.findall(r'\d+', tmp_memory_data.split('kB')[0])
    #     else:
    #         tmp_memory = re.findall(r'\d+', tmp_memory_data.split('K')[0])
    #     memory_list = ''
    #     for i in range(len(tmp_memory)):
    #         memory_list = memory_list + tmp_memory[i]
    #
    #     free_ram = format(int(memory_list) / 1024, '.2f')
    #     return free_ram
    #
    # def get_used_memory(self):
    #     """
    #     设备运行总使用内存
    #     :return:
    #     """
    #     tmp_memory_data = self.shell('dumpsys meminfo | grep Used')
    #     if 'kB' in tmp_memory_data:
    #         tmp_memory = re.findall(r'\d+', tmp_memory_data.split('kB')[0])
    #     else:
    #         tmp_memory = re.findall(r'\d+', tmp_memory_data.split('K')[0])
    #     memory_list = ''
    #     for i in range(len(tmp_memory)):
    #         memory_list = memory_list + tmp_memory[i]
    #
    #     use_dram = format(int(memory_list) / 1024, '.2f')
    #     return use_dram
    #
    # def get_memory_info(self):
    #     """
    #     一次dump获取Total/Free/Used内存
    #     :return:
    #     """
    #     global total_ram, free_ram, use_dram
    #     command = f'adb -s {self.serialno} shell dumpsys meminfo'
    #     tep_memory = os.popen(command)
    #     for line in tep_memory:
    #         memory_list = line.strip().split(':')
    #         if memory_list[0] == 'Total RAM':
    #             if self.os_version() <= 6:
    #                 total_ram = format(int(memory_list[1].split(" ")[1]) / 1024, '.2f')
    #             else:
    #                 total_ram = format(int(memory_list[1].split("K")[0].replace(',', '')) / 1024, '.2f')
    #         elif memory_list[0] == 'Free RAM':
    #             if self.os_version() <= 6:
    #                 free_ram = format(int(memory_list[1].split(" ")[1]) / 1024, '.2f')
    #             else:
    #                 free_ram = format(int(memory_list[1].split("K")[0].replace(',', '')) / 1024, '.2f')
    #         elif memory_list[0] == 'Used RAM':
    #             if self.os_version() <= 6:
    #                 use_dram = format(int(memory_list[1].split(" ")[1]) / 1024, '.2f')
    #             else:
    #                 use_dram = format(int(memory_list[1].split("K")[0].replace(',', '')) / 1024, '.2f')
    #     return total_ram, free_ram, use_dram
    #
    # def get_total_cpu(self):
    #     """
    #     CPU总占用,os8以上CPU不一定是100%,
    #     :return:
    #     """
    #     command = f'adb -s {self.serialno} shell top -n 1'
    #     tempcpu = os.popen(command)
    #     totalcpu = ''
    #     maxcpu = ''
    #     for line in tempcpu:
    #         print(line)
    #         temp = line.strip().split(' ')
    #         while '' in temp:
    #             temp.remove('')
    #         if len(temp) > 8:
    #             if '%cpu' in temp[0]:
    #                 maxcpu = temp[0]
    #                 totalcpu = f"{int(temp[0].replace('%cpu', '')) - int(temp[4].replace('%idle', ''))}%"
    #                 break
    #     return totalcpu, maxcpu
    #
    # def get_allocated_cpu(self):
    #     """
    #     获取运行的测试包占用的cpu
    #     :return:
    #     """
    #     packname = self.package_name()[0:15]
    #     temp_cpu = self.shell(f'top -n 1 |grep {packname}')
    #     if temp_cpu == '':
    #         return 'N/a'
    #     else:
    #         temp_cpu = temp_cpu.split(' ')
    #         while '' in temp_cpu:
    #             temp_cpu.remove('')
    #         if temp_cpu.count(f'{packname}') == 2:
    #             temp_cpu = temp_cpu[(temp_cpu.index(f'{packname}\n')) + 1:]
    #             cpu = f'{temp_cpu[8]}%'
    #         else:
    #             cpu = f'{temp_cpu[8]}%'
    #         return cpu
    #
    # def get_fps(self):
    #     device = self.serialno()
    #     package = self.package_name()
    #     activity = self.get_activityname()
    #     androidversion = self.get_androidversion()
    #     command = ""
    #     if androidversion < 7:
    #         command = adb + " -s {} shell dumpsys SurfaceFlinger --latency 'SurfaceView'".format(device)
    #     elif androidversion == 7:
    #         command = adb + " -s {} shell \"dumpsys SurfaceFlinger --latency 'SurfaceView - {}/{}'\"".format(device,
    #                                                                                                          package,
    #                                                                                                          activity)
    #     elif androidversion > 7:
    #         command = adb + " -s {} shell \"dumpsys SurfaceFlinger --latency 'SurfaceView - {}/{}#0'\"".format(device,
    #                                                                                                            package,
    #                                                                                                            activity)
    #     tempdata = os.popen(command)
    #     if not tempdata:
    #         print("nothing")
    #         return (None, None)
    #     timestamps = []
    #     nanoseconds_per_second = 1e9  # 定义纳秒
    #     refresh_period = 16666666 / nanoseconds_per_second  # 定义刷新间隔
    #     pending_fence_timestamp = (1 << 63) - 1  # 定义挂起时间戳
    #     for line in tempdata:
    #         temp = line.strip().split("\t")
    #         if len(temp) != 3:  # 剔除非数据列
    #             continue
    #         timestamp = float(temp[1])  # 取中间一列数据
    #         if timestamp == pending_fence_timestamp:  # 当时间戳等于挂起时间戳时,舍弃
    #             continue
    #         timestamp /= nanoseconds_per_second
    #         if timestamp != 0:  # 安卓7的adbdump提供255行数据,127行0以及128行真实数据,所以需要将0行剔除
    #             timestamps.append(timestamp)
    #     frame_count = len(timestamps)  # 获得总帧数
    #     frame_lengths, normalized_frame_lengths = self.GetNormalizedDeltas(timestamps, refresh_period,
    #                                                                        0.5)  # 获取帧列表总长、规范化帧列表总长
    #     if len(frame_lengths) < frame_count - 1:
    #         print('Skipping frame lengths that are too short.')
    #     frame_count = len(frame_lengths) + 1
    #     # 数据不足时,返回None
    #     if not refresh_period or not len(timestamps) >= 3 or len(frame_lengths) == 0:
    #         print("未收集到有效数据")
    #         return "N/a"
    #     # 总秒数为时间戳序列最后一位减第一位
    #     seconds = timestamps[-1] - timestamps[0]
    #     fps = int(round((frame_count - 1) / seconds))
    #     return fps
    #
    # def GetNormalizedDeltas(self, data, refresh_period, min_normalized_delta=None):
    #     deltas = [t2 - t1 for t1, t2 in zip(data, data[1:])]
    #     if min_normalized_delta != None:
    #         deltas = filter(lambda d: d / refresh_period >= min_normalized_delta, deltas)
    #     return (list(deltas), [delta / refresh_period for delta in deltas])
    #


if __name__ == '__main__':
    """is_screenon是否亮屏幕"""
    package = "com.mobile.legends"
    path = r'C:\Users\Administrator\Downloads\MobileLegends-1.5.84.640.1-intest-202105240033-gp-enc-v7a.apk'
    # adb = AdbClient(serialno="fd7ff5b2")
    # print(adb.install_app_project(package, path))
    # device = '1cd0f016'
    # device_low = '2a23d35'
    dev = ["11c5ac02",
           "14b1f383",
           "1940ab93",
           "68b504c7",
           "9f7d30a1",
           "ae527b10",
           "ba29288b",
           "c9993153",
           "d928aeb5",
           "e2cb6a1e"
           ]
    for i in dev:
        print(i)
        adb = AdbClient(serialno=i)
        print(adb.install_app_project(package, path))
    # adb.install_app_project(package, path)
    # print(adb.check_install(package))
    # print(adb.get_device_name())
    # print(adb.get_apk_versionName(package))
    # print(adb.install_app_project(package))

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值