monkey自动化测试脚本

13 篇文章 0 订阅
import subprocess,re,os,random,time



def get_device():
    #adb devices 可显示的设备有
    import subprocess,os
    # :return: devices_list 设备列表  device_num  设备数量
    devices_result=subprocess.getoutput("adb devices")
    devices_list=devices_result.replace("no permissions","").replace("device","").replace("\t","").split("\n")[1:-1]
    device_num=len(devices_list)
    unauthorized_devices_list=[]
    for i in devices_list:
        if "unauthorized" in i :
            devices_list.remove(i)
            unauthorized_devices_list.append(i.replace("unauthorized",""))
    return devices_list


def get_device_info(device):
    #捕获手机型号是:vivo NEX    android版本: 8.1.0    屏幕分辨率为:1080x2316
    android_version=subprocess.getoutput("adb -s %s shell getprop ro.build.version.release"%device)
    # product_version=subprocess.getoutput('adb  -s %s shell getprop | grep product.version'%device).split(":")[1].replace('[',"").replace("]","").replace(" ",'')
    product_model_result=subprocess.getoutput('adb  -s %s shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"'%device)
    product_model=re.search(r"\[ro.product.model\]: \[(.*)\]",product_model_result)
    phone_product=(product_model.group().replace("[ro.product.model]: ",'').replace("[","").replace("]",''))
    screen_size=subprocess.getoutput('adb -s %s shell "dumpsys window | grep mUnrestrictedScreen"'%device).replace("mUnrestrictedScreen=(0,0)",'').replace(" ",'')
    # print("手机型号是:%s" % phone_product)
    # # print("软件版本号:%s"%product_version)
    # print("android版本:", android_version)
    # print("屏幕分辨率为:%s"%screen_size)
    return  phone_product,android_version,screen_size



def get_package_name(app):
    #捕获app package包名
    result=subprocess.getoutput('aapt dump badging  %s  | grep "package: name="'%(app))
    package=str(result.split(" ")[1]).replace("name=","").replace("'","")
    print("package_name:%s"%package)
    return package


def install_app(device,app):
    #安装app
    os.system('adb -s %s install %s'%(device,app))
    subprocess.getoutput('adb -s %s install %s'%(device,app))


def monkey_test(device,package_name,monkey_report):
    #执行 monkey
    seed = random.randint(10, 1000)
    injected_num0 = 2000
    # 执行monkey
    test_monkey_command = "adb -s %s shell monkey -p %s -s %s -v -v -v  --throttle %s %s >>%s" % (
        device, package_name, seed, 5, injected_num0, monkey_report)

    os.system(test_monkey_command)


def  get_cpuinfu(device,package_name,cpuinfo_file):
    '''cpu mem'''
    # adb -s %s shell  nohup  top -n  1 |  grep com.meelive.ingkee >> cpu.txt
    import subprocess
    cpu_command="adb -s %s shell top  -n 10 |grep %s   >> %s"%(device,package_name,cpuinfo_file)
    subprocess.getoutput(cpu_command)
    print(cpu_command)
def avg(num):
    nsum = 0
    for i in range(len(num)):
        nsum += num[i]
    return nsum / len(num)

def read_cpu_mem_info_data(file=None):
    import re
    import math
    from decimal import Decimal
    # file="/opt/liming_dir/ldx_project/cpu_dir/215bc0d_laidianxiu_cpuinfo.txt"
    with open(file,"r")as f:
        readlines=f.readlines()
        cpu_list=[]
        mem_list=[]
        cpu_list2=[]
        mem_list2=[]
        data=re.findall(r".*?S  ([\d\.]*)   ([\d\.]*)   .*?",str(readlines),flags=re.M)
        for i in data:
            cpu_list.append(i[0])
            mem_list.append(i[1])
        for i in cpu_list:
            cpu_list2.append(float(i.replace("'",'')))
        for i in mem_list:
            mem_list2.append(float(i.replace("'",'')))
        avg_cpu=(round(avg(cpu_list2),2))
        avg_mem=(round(avg(mem_list2),2))

        max_cpu=Decimal(max(cpu_list)).quantize(Decimal('0.00'))
        max_mem=Decimal(max(mem_list)).quantize(Decimal('0.00'))
        # print(format(avg_cpu*0.01,".0%"))
        AvgCpu="%.2f%%"%(avg_cpu)
        AvgMem = "%.2f%%" % (avg_mem)
        MaxCpu="%.2f%%" % (max_cpu)
        MaxMem="%.2f%%" % (max_mem)
        # print(AvgCpu)
        # print(AvgMem)
        # print(MaxCpu)
        # print(MaxMem)
    return  AvgCpu,AvgMem,MaxCpu,MaxMem

def Read_monkey_report(monkey_report,monkey_report_path=None):
    #读取monkey 报告
    import time
    dt = time.strftime("%Y-%m-%d-%H-%M-%S")
    report_data=[]
    flag=""
    with open(monkey_report,"r") as f:
        result=f.readlines()
        # apk_name=result[0]
        try:
                        # #seed=result[1].split(" ")[1]
        #
        # status_result = status.group(1)

            seed=re.search(r"seed=([0-9]+)+",str(result))
            count = re.search(r"count=([0-9]+)+", str(result))
            Sleeping=re.search(r"Sleeping for ([0-9]+)+ milliseconds", str(result))
            AllowPackage=re.search(r"AllowPackage: ([A-Za-z0-9\.]+)", str(result))
            Dropped_num_group=re.search(r":Dropped: keys=(\d+) pointers=(\d+) trackballs=(\d+) flips=(\d+)",str(result))
            elapsed_time = re.search(r"elapsed time=(\d+ms)", str(result))

            Event_percentages_list=[]
            Event_percentages=re.search(r"'// Event percentages:\\n'\, '//   0: ([-\d\.]*%)\\n', '//   1: ([-\d\.]*%)\\n', '//   2: ([-\d\.]*%)\\n', '//   3: ([-\d\.]*%)\\n', '//   4: ([-\d\.]*%)\\n', '//   5: ([-\d\.]*%)\\n', '//   6: ([-\d\.]*%)\\n', '//   7: ([-\d\.]*%)\\n', '//   8: ([-\d\.]*%)\\n', '//   9: ([-\d\.]*%)\\n', '//   10: ([-\d\.]*%)\\n', '//   11: ([-\d\.]*%)\\n'", str(result))#//

            # keys = Dropped_num_group.group(1)
            # pointers = Dropped_num_group.group(2)
            # seed_ = seed.group(1)
            count_ = count.group(1)
            # Sleeping_ = Sleeping.group(1)
            AllowPackage_ = AllowPackage.group(1)
            if Event_percentages:
                for i in range(1,13):
                    Event_percentages_list.append(Event_percentages.group(i))
                sum=0
                for num in  Event_percentages_list:
                    persent=float(num.replace("'","").replace("%",""))
                    sum+=persent
                    if sum==100.0:
                        print("")
                report_data.append("monkey事件百分比:%s\\r\\n"% Event_percentages_list)

            # report_data.append({"apk_name":apk_name.replace("\n","")})
            report_data.append("测试包名:%s\\r\\n" %AllowPackage_)
            report_data.append("点击次数:%s\\r\\n"% count_)

            #
            # report_data.append({"seed": seed_})
            #
            # report_data.append({"Sleeping": Sleeping_})

            if elapsed_time:
                elapsed_time_ = elapsed_time.group(1)
                report_data.append("monkey测试时间:%s\\r\\n"%elapsed_time_)

            # report_data.append({"keys": keys})
            # report_data.append({"pointers": pointers})
            injected_num = re.findall(r"Events injected: (\d+)", str(result), flags=re.M)
            if injected_num:
                #report_data.append({"monkey执行事件数:": injected_num})
                report_data.append("")
            status = re.search(r"// Monkey (finished)", str(result))
            status_aborted = re.search(r"// Monkey (aborted)", str(result))
            if status:
                status_result = status.group(1)
                result="success"
                report_data.append("monkey执行结果:%s\\r\\n"%result)
                flag="finished"

            elif  status_aborted:

                status_result = status.group(1)
                result="failed"
                report_data.append("monkey执行结果:%s\\r\\n" % result)
                flag = "error"
            else:
                result = "failed"
                report_data.append("monkey执行结果:%s\\r\\n" % result)
                flag = "error"
            try:
                if injected_num[0]!=count_:# and status.group(1)=="finished" :
                    report_data.append("monkey测试出现错误,点击次数和monkey执行事件数不等,事件没有全部运行完成,请查看对应monkey报告及检查apk是否出现问题")
            except IndexError as e:
                print ("injected_num[0]",e)

        except AttributeError as e:
            print("in  Read_monkey_report %s"%e)


    return report_data,flag,injected_num,result


def run(device,app):
    # for device in get_device:
        import time
        date = str(time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time())))
       # print("===================%s================================"%device)
        phone_product, android_version, screen_size=get_device_info(device) #
        package_name=get_package_name(app)  #com.cookie.testapp  com.cookie.test+  16位
        monkey_report = "/opt/liming_dir/ldx_project/monkey_dir/" +"%s_laidianxiu_monkey.txt"%device
        cpuinfo_file="/opt/liming_dir/ldx_project/cpu_dir/"+"%s_laidianxiu_cpuinfo.txt"%device
        # 安装应用
        # install_app(device, app)

        get_cpuinfu(device, "com.cookie.test+", cpuinfo_file)
        monkey_test(device, package_name, monkey_report)


        report_data, flag, injected_num, result = Read_monkey_report(monkey_report, monkey_report_path=None)


        AvgCpu, AvgMem, MaxCpu, MaxMem=read_cpu_mem_info_data(cpuinfo_file)
        print(date)
        print(phone_product,android_version,screen_size)
        print(package_name)
        print(AvgCpu,AvgMem,MaxCpu,MaxMem)
        print(report_data, flag, injected_num, result)
        report="/opt/liming_dir/ldx_project/display_report/来电秀_%s_兼容性测试报告.log"%phone_product
        with open (report,"w")as f :#捕获手机型号是:vivo NEX    android版本: 8.1.0    屏幕分辨率为:1080x2316
            f.write("项目名称:来电秀app\r\n"+"日期:%s\r\n"%date+"手机型号:%s\r\n"%phone_product+"屏幕分辨率为:%s\r\n"%screen_size+
                    "安装结果:成功\r\n"+"应用消耗平均cpu:%s\r\n"%AvgCpu+"应用占用平均内存:%s\r\n"%AvgMem+"应用消耗最大cpu:%s\r\n"%MaxCpu+"应用占用最大内存:%s\r\n"%MaxMem+"monkey测试结果:%s\r\n"%str(report_data))






if __name__ == '__main__':
    import threading
    app="/opt/liming_dir/ldx_project/laidianxiu.apk "
    path=os.path.split(os.getcwd())[0]
    th_list=[]
    get_device=["dd60ac04","215bc0d","46e8e43f","1797912f","44c7f374"]#["1797912f"]#
    for device in get_device:
        # run(device, app)
        run_th=threading.Thread(target=run,args=(device, app))
        th_list.append(run_th)
    for th in th_list:
        th.start()
    for th in th_list:
        th.join()


'''
 adb -s 44c7f374 shell top -n 10 |grep  com.cookie.test+

'''









# dd60ac04                product:PD1728 model:vivo_X21 device:PD1728
# 215bc0d                 product:whyred model:Redmi_Note_5 device:whyred
#46e8e43f                product:nitrogen model:MI_MAX_3 device:nitrogen
# 1797912f               product:PBAM00 model:PBAM00 device:PBAM00 transport_id:3  OPPO A5
# 44c7f374                product:PD1806 model:vivo_NEX device:PD1806 transport_id:5


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值