import subprocess,re,os,random,timedef 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_listdef get_device_info(device):#捕获手机型号是:vivo NEX android版本: 8.1.0 屏幕分辨率为:1080x2316android_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_sizedef 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 packagedef install_app(device,app):#安装appos.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):#执行 monkeyseed = random.randint(10, 1000)injected_num0 = 2000# 执行monkeytest_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.txtimport subprocesscpu_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 = 0for i in range(len(num)):nsum += num[i]return nsum / len(num)def read_cpu_mem_info_data(file=None):import reimport mathfrom 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,MaxMemdef Read_monkey_report(monkey_report,monkey_report_path=None):#读取monkey 报告import timedt = 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=0for num in Event_percentages_list:persent=float(num.replace("'","").replace("%",""))sum+=persentif 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,resultdef run(device,app):# for device in get_device:import timedate = 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"%devicecpuinfo_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_productwith open (report,"w")as f :#捕获手机型号是:vivo NEX android版本: 8.1.0 屏幕分辨率为:1080x2316f.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 threadingapp="/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+'''# dd60ac04product:PD1728 model:vivo_X21 device:PD1728# 215bc0d product:whyred model:Redmi_Note_5 device:whyred#46e8e43fproduct:nitrogen model:MI_MAX_3 device:nitrogen# 1797912fproduct:PBAM00 model:PBAM00 device:PBAM00 transport_id:3 OPPO A5# 44c7f374product:PD1806 model:vivo_NEX device:PD1806 transport_id:5
300字范文,内容丰富有趣,生活中的好帮手!