from airtest.cli.runner importAirtestCase, run_scriptfrom argparse import *
importairtest.report.report as reportimportjinja2importshutilimportosimportioclassCustomAirtestCase(AirtestCase):defsetUp(self):#执行脚本前的前置环境准备操作
print("custom setup")#add var/function/class/.. to globals
#self.scope["hunter"] = "i am hunter"
#self.scope["add"] = lambda x: x+1
#exec setup script
#self.exec_other_script("setup.owl")
for i in range(100):print("1===================================================================")
super(CustomAirtestCase, self).setUp()deftearDown(self):#执行脚本后的后置环境恢复操作
print("custom tearDown")#exec teardown script
#self.exec_other_script("teardown.owl")
for j in range(100):print("2222222222222222222222222222222222222222222222222222222222222222222222222222")
super(CustomAirtestCase, self).setUp()#root_dir是项目根目录,device是默认连接设备,可以把常用的设备设置成默认的设备
def run_air(self, root_dir='D:\\workspace\\airtest\\suite', device=['android://127.0.0.1:5037/2476a88e']):#聚合结果
results =[]#获取所有用例集
root_log = root_dir + '\\' + 'log'
ifos.path.isdir(root_log):
shutil.rmtree(root_log)else:
os.makedirs(root_log)print(str(root_log) + 'is created')for f inos.listdir(root_dir):if f.endswith(".air"):#f为.air案例名称:douyin.air
airName =f
script=os.path.join(root_dir, f)#script为.air的全路径:D:\workspace\airtest\suite\douyin.air
print(script)#log为日志存放路径和名称:D:\workspace\airtest\suite\log\douyin
log = os.path.join(root_dir, 'log' + '\\' + airName.replace('.air', ''))print(log)#判断case日志在不在,在,则删除目录中的内容,否则,新建每个脚本log目录
ifos.path.isdir(log):
shutil.rmtree(log)else:
os.makedirs(log)print(str(log) + 'is created')#日志的输出文件log:D:\workspace\airtest\suite\log\douyin\log.html
output_file = log + '\\' + 'log.html'
#命令行参数,解析获得后的数据格式Namespace(device=device, log=log, recording=None, script=script)
#python -m airtest run D:\workspace\airtest\dy.air --device Android://127.0.0.1:5037/B2T5T16C06000021 --log "D:\workspace\airtest\douyin.air\2"
args = Namespace(device=device, log=log, recording=None, script=script)try:
run_script(args, AirtestCase)except:pass
finally:
rpt=report.LogToHtml(script, log)#结果模板渲染,"log_template.html"自带的模板,output_file日志存放路径
rpt.report("log_template.html", output_file=output_file)#结果保存在result对象中
result ={}
result["name"] = airName.replace('.air', '')
result["result"] =rpt.test_result
results.append(result)#根据summary_template.html模板,生成聚合报告
env =jinja2.Environment(
loader=jinja2.FileSystemLoader(root_dir),
extensions=(),
autoescape=True
)#summary_template.html相对路径
template = env.get_template("summary_template.html", root_dir)
html= template.render({"results": results})
output_file= os.path.join(root_dir, "summary.html")
with io.open(output_file,'w', encoding="utf-8") as f:
f.write(html)print(output_file)if __name__ == '__main__':
test=CustomAirtestCase()#连接的设备
device = ['android://127.0.0.1:5037/2476a88e']#项目根目录
test.run_air('D:\\workspace\\airtest\\suite', device)