批量运行Airtest脚本
本文是在ttphoon大佬的https://blog.csdn.net/ttphoon/article/details/102910119基础上进行了调整,适配了airtest1.2.3版本,并且修复了部分bug。
话不多说,直接上代码!!
需要全部代码的伙伴可以到Gitee下载:https://gitee.com/zhaim/airtest-runner-single.git
runCase.py
#!/usr/python3import logging
import shutil,os,jinja2,datetimefrom argparse import *
from conf.settings import *
from airtest.report.report import LogToHtml
from airtest.core.api import connect_device
from airtest.cli.runner import AirtestCase,run_script# 只在终端输出error级别的及以上的log
logger = logging.getLogger()
logger.setLevel(logging.ERROR)class Air_Case_Handler(AirtestCase):def __init__(self,dev_id):super(Air_Case_Handler, self).__init__()if deviceType.upper() == "WEB":passelse:# 如果deviceType非“Web”,说明需要连接手机,则调用airtest的connect_device方法self.dev = connect_device(dev_id)def setUp(self):super(Air_Case_Handler, self).setUp()def tearDown(self):super(Air_Case_Handler,self).tearDown()def run_air(self,air_dir,device):start_time = datetime.datetime.now()start_time_fmt = start_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]results = [] # {name:项目名,result:运行结果True/False}root_log = log_path# 如果没有log和report目录则创建,有则删除后再创建if os.path.exists(root_log):if cover_report:shutil.rmtree(root_log)os.makedirs(root_log)else:os.makedirs(root_log)if os.path.exists(report_path):if cover_report:shutil.rmtree(report_path)os.makedirs(report_path)else:os.makedirs(report_path)for file in os.listdir(air_path):# 找到air目录下所有后缀是.air的脚本if file.endswith(".air"):airName = file# 把文件路径的后缀删掉,就变成了文件路径了。后面用来做脚本同名的log日志文件夹airDirName = file.replace(".air","") #/Users/zhaohaiming/Desktop/TestDev/Airtest_Runner/air/air_scriptscript = os.path.join(air_dir,file) #/Users/zhaohaiming/Desktop/TestDev/Airtest_Runner/air/air_script.air# log的路径air_log = os.path.join(root_path,"log/" + airDirName + str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))#/Users/zhaohaiming/Desktop/TestDev/Airtest_Runner/log/飞凡APP登录2022-02-05 21:51:10.002758# 创建log的目录os.makedirs(air_log)html = os.path.join(air_log,"log.html") #/Users/zhaohaiming/Desktop/TestDev/Airtest_Runner/log/air_script/log.htmlif deviceType.upper() == "WEB":# 直接向argparse的namespace添加命令行参数args = Namespace(device=None,log = air_log, recording=None, script=script,compress=compress,no_image=no_image,language="zh")elif deviceType.upper() == "APP":args = Namespace(device=device, log = air_log, recording=None, script=script,language="zh",compress=compress,no_image=no_image)else:args = Namespace(device=device, log=air_log, recording=None, script=script,language="zh")try:run_script(args)except AssertionError as e:passfinally:if deviceType.upper() == "WEB":rpt = LogToHtml(script, air_log, plugins=["airtest_selenium.report"])else:rpt = LogToHtml(script, air_log)rpt.report(output_file=html)result = {}result["name"] = airName.replace('.air', '')result["result"] = rpt.test_resultresult["log_air"] = air_logresults.append(result)end_time = datetime.datetime.now()end_time_fmt = end_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]duration = (end_time - start_time).seconds# 创建一个文件系统加载器对象env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_path),extensions=(),autoescape=True)# 获取一个模板文件template = env.get_template(template_name, template_path)project_name = root_path.split("/")[-1]success = 0fail = 0# 根据results的值,统计success和fail的总数for res in results:if res['result']:success += 1else:fail += 1report_name = "report_"+end_time.strftime("%Y%m%d%H%M%S")+".html"# 渲染html = template.render({"results": results,"device":device,"stime":start_time_fmt,'etime':end_time_fmt,'duration':duration,"project":project_name,"success":success,"fail":fail})# 把渲染后的html写到指定的报告中output_file = os.path.join(root_path,"report" ,report_name)with open(output_file, 'w', encoding="utf-8") as f:f.write(html)if __name__ == "__main__":for device in devices:test = Air_Case_Handler(device)test.run_air(air_path,device)
settings.py
运行配置,这里面主要需要设置的内容
- deviceType:app/web
- devices:这里是个列表,如果deviceType选择了app则这里需要输入设备连接信息
- cover_report:是否需要覆盖测试报告和log日志
- no_image:False在测试过程中会截图,报告会展示;True则在测试过程中不会截图
- compress:截图的压缩精度,1-99,越大越清晰
#coding = utf-8
#author:chenjq
import os
#设备类别:app、win和web
deviceType = "web"#测试报告模板名称
template_name ="summary_template.html"# 是否覆盖测试报告,True:运行时会删除之前所有的报告和log记录。False:不会删除
cover_report = False# 是否要截图
no_image = False# 截图压缩精度 1-99 越大越清晰
compress = 75# 设备信息,只有当deviceType为app是有效
devices = ['android://127.0.0.1:5037/SNU0221202001769']#工程根目录
root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#脚本目录
air_path = os.path.join(root_path,'air')#日志目录
log_path =os.path.join(root_path,'log')#测试报告模板目录
template_path=os.path.join(root_path,'template')#测试报告路径
report_path=os.path.join(root_path,'report')#测试数据目录
data_path = os.path.join(root_path, 'data')
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
