def run(root_path, test_case, device, log_date): script = os.path.join(root_path, test_case["module"], test_case["case"]) log = os.path.join(root_path, 'log', test_case["module"], log_date, test_case["case"].replace('.air', '')) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + 'is created') output_file = os.path.join(log, 'log.html') args = Namespace(device=device, log=log, compress=None, recording=True, script=script) try: run_script(args, AirtestCase) is_success = True except: is_success = False return { "is_success": is_success, "output_file": output_file, "script": script, "log": log }
def run_airtest( script, log_root, device="", compress=75, ): """ 執行單個指令碼,並生成測試報告,返回執行結果 :param script: *.air, 要執行的指令碼 :param device: 裝置字串 :param log_root: 指令碼日誌存放目錄 """ if os.path.isdir(log_root): print('once again on same time') # shutil.rmtree(log_root) else: os.makedirs(log_root) print(str(log_root) + '>>> is created') # 組裝執行引數 args = Namespace( device=device, # 裝置字串 log=log_root, # log目錄 recording=None, # 禁止錄屏 script=script, # *.air compress=compress, ) run_script(args, McCustomAirtestCase)
def run_air(self, root_dir, device): # 聚合结果 results = [] # 获取所有用例集 root_log = root_dir + '\\' + 'log' if os.path.isdir(root_log): shutil.rmtree(root_log) else: os.makedirs(root_log) print(str(root_log) + 'is created') for f in os.listdir(root_dir): if f.endswith(".air"): # f为.air案例名称:手机银行.airK airName = f script = os.path.join(root_dir, f) # airName_path为.air的全路径:D:\tools\airtestCase\案例集\log\手机银行 print(script) # 日志存放路径和名称:D:\tools\airtestCase\案例集\log\手机银行1 log = os.path.join(root_dir, 'log' + '\\' + airName.replace('.air', '')) log_1 = script + '\\' + 'log' print(log) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + 'is created') output_file = log + '\\' + 'log.html' args = Namespace(device=device, log=log_1, recording=None, script=script) try: run_script(args, AirtestCase) except: pass finally: # rpt = report.LogToHtml(script, log) rpt = report.LogToHtml(script, log_1, script_name=f.replace( ".air", ".py")) rpt.report("log_template.html", output_file=output_file) result = {} result["name"] = airName.replace('.air', '') result["result"] = rpt.test_result results.append(result) # 生成聚合报告 env = jinja2.Environment(loader=jinja2.FileSystemLoader(root_dir), extensions=(), autoescape=True) 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)
def main(argv=None): ap = get_parser() args = ap.parse_args(argv) if args.action == "info": from airtest.cli.info import get_script_info print(get_script_info(args.script)) elif args.action == "report": from airtest.report.report import main as report_main report_main(args) elif args.action == "run": from airtest.cli.runner import run_script run_script(args)
def main(argv=None): ap = get_parser() args = ap.parse_args(argv) if args.action == "info": from airtest.cli.info import get_script_info print(get_script_info(args.script)) elif args.action == "report": from airtest.report.report import main as report_main report_main(args) elif args.action == "run": from airtest.cli.runner import run_script run_script(args) elif args.action == "version": from airtest.utils.version import show_version show_version() else: ap.print_help()
def run_airtest(self): try: args = Namespace() args.device = f"Android:///{self.stf_device.device_name}" args.log = self.log args.script = DefaultConfig.SCRIPT_MAIN_PATH if not self.script else self.script args.compress = 10 args.recording = None args.action = 'run' try: run_script(args) except Exception as e: print(e) traceback.print_exc() except Exception as ee: print(ee) traceback.print_exc()
def run(self): # 准备文件夹 log_root, log, snapshot = self.run_before() self.log_root = log_root self.log = log self.snapshot = snapshot args = argparse.Namespace(device=self.device, log=log, snapshot=snapshot, recording=None, script=self.script) try: print(args) run_script(args, CustomAirtestCase) except: pass self.run_after(log_root, log)
def run_air(self, root_dir, device,logpath): dirs = os.listdir(root_dir)#获取root_dir路径下的文件 print("run_air, dirs:" + str(dirs)) for f in dirs: # 循环查找air所在的目录 if f.endswith( ".air" ): # 以air结尾的文件 airName = f script = os.path.join( root_dir, f ) # 脚本目录 logging.info( script ) deviceLogPath = utils.getDeviceLogPath() log = os.path.join(deviceLogPath + '\\' + airName.replace( '.air', str(utils.getCurrentTime()) ) ) # 日志目录 logging.info( log ) if os.path.isdir( log ): shutil.rmtree( log ) # 清空日志目录文件 else: os.makedirs( log )#创建日志目录 args = Namespace( device=device, log=log, recording=None, script=script ) # 初始化父类AirtestCase所需要的参数 try: run_script( args, AirtestCase ) # 执行air脚本文件 except AssertionError: logging.info( "案例执行失败" )
def run(root_dir, test_case, air_device): # 日志按照日期格式生成 log_date = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") script = os.path.join(root_dir, test_case["module"], test_case["case"]) log = os.path.join(root_dir, 'log', test_case["module"], log_date, test_case["case"].replace('.air', '')) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + ' is created') output_file = os.path.join(log, 'log.html') args = Namespace(device=air_device, log=log, compress=None, recording=True, script=script) # 用例开始执行日期 st_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 用例开始执行时间 s_time = datetime.now().strftime("%H:%M:%S") try: run_script(args, AirtestCase) is_success = True except: is_success = False end_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 用例结束执行时间 e_time = datetime.now().strftime("%H:%M:%S") # 用例耗时时间 sum_time = get_case_total_time(s_time, e_time) # 生成测试用例的详情报告 rpt = report.LogToHtml(script, log) rpt.report("log_template.html", output_file=output_file) # 记录测试结果 result = {"name": test_case["case"].replace(".air", ""), "result": is_success, "start_date": st_date, "end_date": end_date, "sum_time": sum_time, "log_date": log_date, "module": test_case["module"]} Runner3Common.set_result_json(result) if not is_success: print("存在失败用例") print(test_case)
language="zh") elif deviceType.upper() == "APP": args = Namespace(device=device, log=air_log, recording=airDirName + ".mp4", script=script, language="zh") else: args = Namespace(device=device, log=air_log, recording=None, script=script, language="zh") try: #run_script(Namespace(device=device, log = air_log_start,recording='CommonStart.mp4',script=os.path.join(air_dir,'CommonStart.air'),language="zh"),AirtestCase) run_script(args, AirtestCase) #setMsg("吴国君_胡彪","BV测试",airDirName+'_UI自动化脚本执行成功') except: setMsg("吴国君", "BV测试", airDirName + '_UI自动化脚本执行失败') run_script( Namespace(device=device, log=air_log_end, recording='CommonEnd.mp4', script=os.path.join(air_dir, 'Common\CommonEnd.air'), language="zh"), AirtestCase) finally: rpt = report.LogToHtml(script, air_log) rpt.report("log_template.html", output_file=html) result = {} result["name"] = air_log.split("\\")[-1]
def run_air(self, root_dir=None, device=[]): ''' start to run all xxx.air files which in the root_dir. root_dir: the root path of project device: the device parameter, we can find this parameter in the AirtestIDE, such as for the windows programs: 'windows:///123456' ''' # 测试用例结果集 results = [] # 创建日志根目录 root_log = root_dir + '\\' + 'logs' if os.path.isdir(root_log): shutil.rmtree(root_log) else: os.makedirs(root_log) # print(str(root_log) + 'is created') # 遍历当前testcasts目录下的所有.air测试用例 for f in os.listdir(os.path.join(root_dir, "testcases")): if f.endswith(".air"): print(f) # 当前测试用例名称, xxx.air airName = f # 当前测试用例的绝对路径 script = os.path.join(os.path.join(root_dir, "testcases"), f) # 当前用例log日志保存根目录 log = os.path.join(root_dir, 'logs' + '\\' + airName.replace('.air', '')) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + ' is created') # 当前测试用例log文件命名 output_file = log + '\\' + 'log.html' args = Namespace(device=device, log=log, recording=None, script=script) try: run_script(args, AirtestCase) except: pass finally: rpt = report.LogToHtml(script, log) rpt.report("log_template.html", output_file=output_file) result = {} result["name"] = airName.replace('.air', '') result["result"] = rpt.test_result results.append(result) # 生成聚合报告 env = jinja2.Environment(loader=jinja2.FileSystemLoader(root_dir), extensions=(), autoescape=True) template = env.get_template("reports_template.html", root_dir) # os.path.join(root_dir, "templates") html = template.render({"results": results}) # 当前日期时间 nowtime = time.strftime("%Y-%m-%d %H_%M_%S") # 聚合报告名称 reportname = "summary_report_" + nowtime + '.html' # 聚合报告保存路径 reportpath = os.path.join(root_dir, "reports") # 写入聚合报告 output_file = os.path.join(reportpath, reportname) with io.open(output_file, 'w', encoding="utf-8") as f: f.write(html) print(output_file)
# -*- coding: utf-8 -*- # Created by #chuyong, on 2019/11/13. # Copyright (c) 2019 3KWan. # Description : from airtest.cli.parser import runner_parser from airtest.cli.runner import AirtestCase, run_script class CustomTestCase(AirtestCase): def setUp(self): super().setUp() def tearDown(self): super().tearDown() if __name__ == '__main__': ap = runner_parser() args = ap.parse_args() run_script(args, CustomTestCase)
def run_air(self,root_script,log_root,CaseList,device,prefObj = None,runPref = False,resetpath = False): # param root_dir 脚本集合根目录 # param device 设备列表 #结果集合 results = [] #日志目录 #root_log = root_dir+'\\'+'log' root_log = log_root if os.path.exists(root_log): if os.path.isdir(root_log): shutil.rmtree(root_log) # else: # os.makedirs(root_log) # print(str(root_log) + 'is created') # # os.makedirs(root_log) # print(str(root_log) + 'is created') mark = {} mark["AllPass"] = True mark["LastCase"] = "" args = None indx = 0 for case in CaseList: caseName = case['caseName'] if '/' in caseName: caseName = caseName.split('/')[1] if '.air' in caseName: caseName = caseName.replace('.air','') mark["LastCase"] = caseName print("CaseName: ",caseName) f,UpModel = getModelAir(caseName,root_script) if runPref and prefObj: prefObj.setlabel(caseName) airName = f airPath = f if UpModel != None: airPath = os.path.join(UpModel,f) script = os.path.join(root_script,airPath) log = os.path.join(log_root,airName.replace('.air','')) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + ' is created') if args == None: args = Namespace(device=device,log = log,recording=None,script=script,compress =10) else: args = Namespace(device=None, log=log, recording=None, script=script, compress=10) try: run_script(args,AirtestCase) except: pass finally: mylog = myLogAnalysis(script,log,"log.txt",caseName,resetpath) datas = mylog.makeData() result = {} if UpModel != None: result['Modelname'] = UpModel result['Casename'] = airName.replace('.air','') result['result'] = datas['test_result'] result['infos'] = datas result['mustPass'] = case['mustPass'] results.append(result) print("Result : ",result['result']) indx = indx + 1 if case['mustPass'] == True and result['result'] == False : print("当前用例 【%s】 未通过 后续用例不执行" % caseName) mark["AllPass"] = False print("UnrunCase list :") unrun = self.makeUnrunData(self.getUnrunCase(indx, CaseList)) mark["unrun"] = unrun data = {} data["mark"] = mark data["results"] = results return data,True; print("UnrunCase list :") unrun = self.makeUnrunData(self.getUnrunCase(indx, CaseList)) mark["unrun"] = unrun data = {} data["mark"] = mark data["results"] = results return data,False;
# -*- encoding=utf8 -*- __author__ = "tianle" from airtest.core.api import * from airtest.cli.runner import AirtestCase, run_script from airtest.cli.parser import runner_parser class AirTestDemo(AirtestCase): def setUp(self): print("custom setup") super(AirTestDemo, self).setUp() def tearDown(self): print("custom tearDown") super(AirTestDemo, self).setUp() if __name__ == '__main__': ap = runner_parser() args = ap.parse_args() run_script(args, AirTestDemo)
text(subject_name) poco("提交").click() poco("android:id/content").child( "android.widget.RelativeLayout").child( "android.widget.LinearLayout").offspring( "com.linklab:id/project_grid_menu").child( "android.widget.LinearLayout")[3].child( "com.linklab:id/menu_child_logo").click() try: if poco(text=subject_name).exists: print(subject_name) print('新建案例成功') else: print('新建案例失败') except: print('新建案例失败') poco("com.linklab:id/head_back").click() def tearDown(self): loginoff() @classmethod def tearDownClass(cls): stop_app("com.linklab") if __name__ == '__main__': ap = runner_parser() args = ap.parse_args() run_script(args, CreatSubject)
def run_air(self, root_dir='C:\\Users\\AUSU\\Desktop\\airtestRuAuto\\suite', device=['Android://127.0.0.1:5037/FIFIMFFEPVAIWCU8']): # 聚合结果 results = [] # 获取所有用例集 root_log = root_dir + '\\' + 'log' # os.path.isdir():用于判断对象是否为一个目录 if os.path.isdir(root_log): # 递归删除文件夹下的所有子文件夹和子文件 shutil.rmtree(root_log) else: # 没有就新建log文件夹 os.makedirs(root_log) print(str(root_log) + 'is created') # os.listdir:返回指定文件夹包含的文件或文件夹的名字的列表 for f in os.listdir(root_dir): # f是否是以.air为后缀结束 if f.endswith(".air"): # f为.air案例名称:test1.air airName = f # 拼接(运行脚本路径),airName_path为.air的全路径:C:\Users\Administrator\Desktop\airtestRuAuto\suite\test1.air script = os.path.join(root_dir, f) print(script) # replace:旧换新 # 日志存放路径:C:\Users\Administrator\Desktop\airtestRuAuto\suite\log\test1 log = os.path.join(root_dir, 'log' + '\\' + airName.replace('.air', '')) # 日志存放名称:C:\Users\Administrator\Desktop\airtestRuAuto\suite\test1.air\log log_1 = script + '\\' + 'log' print(log) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + 'is created') # 报告的存放路径 output_file = log + '\\' + 'log.html' args = Namespace(device=device, log=log_1, recording=None, script=script, compress=10, no_image=None) try: run_script(args, AirtestCase) except: pass finally: # rpt = report.LogToHtml(script, log) # 脚本路径、log路径、脚本名称 rpt = report.LogToHtml(script, log_1, script_name=f.replace( ".air", ".py")) rpt.report("log_template.html", output_file=output_file) result = {} # 脚本名字 result["name"] = airName.replace('.air', '') # 运行结果 result["result"] = rpt.test_result # 拼接,生成聚合报告 results.append(result) # 生成聚合报告 env = jinja2.Environment(loader=jinja2.FileSystemLoader(root_dir), extensions=(), autoescape=True) 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)
def run_air(self, root_dir='', device=[], scriptname='air_case'): # 用例目录 script_path = root_dir + "/" + scriptname # 聚合结果 results = [] # 创建log文件 root_log = root_dir + '/' + 'log' if os.path.isdir(root_log): shutil.rmtree(root_log) else: os.makedirs(root_log) print(str(root_log) + ' is created') # 创建export_log文件 export_log = root_dir + '/' + 'export_log' if os.path.isdir(export_log): shutil.rmtree(export_log) else: os.makedirs(export_log) print(str(export_log) + ' is created') for f in os.listdir(script_path): if f.endswith(".air"): # f为.air案例名称:login.air airName = f script = os.path.join(script_path, f) # airName_path为.air的全路径/Users/zhangxue/Documents/study/airtest_fppui/air_case/login.air print("当前运行脚本路径:" + str(script)) # 日志存放路径和名称:/Users/zhangxue/Documents/study/airtest_fppui/log/login/log.html log = os.path.join(root_dir, 'log' + '/' + airName.replace('.air', '')) print("log路径:" + str(log)) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + ' is created') # global args args = Namespace(device=device, log=log, recording=None, script=script, compress=1) try: run_script(args, AirtestCase) except: pass finally: export_output_file = os.path.join(export_log + "/" + airName.replace('.air', '.log') + '/log.html') rpt = report.LogToHtml(script_root=script, log_root=log, export_dir=export_log) rpt.report("log_template.html", output_file=export_output_file) result = {} result["name"] = airName.replace('.air', '') result["result"] = rpt.test_result results.append(result) # 生成聚合报告 env = jinja2.Environment( loader=jinja2.FileSystemLoader(root_dir), extensions=(), autoescape=True ) template = env.get_template("summary_template.html", root_dir) html = template.render({"results": results}) output_file = os.path.join(export_log, "summary.html") with io.open(output_file, 'w', encoding="utf-8") as f: f.write(html) print(output_file)
def run_air( self, root_dir='C:\\Users\\dbk\\AppData\\Local\\Programs\\Python\\Python35\\airtestCase\\case', device=['android://127.0.0.1:5037/127.0.0.1:7555']): # 聚合结果 results = [] # 获取所有用例集 root_log = root_dir + '\\' + 'log' if os.path.isdir(root_log): shutil.rmtree(root_log) else: os.makedirs(root_log) print(str(root_log) + 'is created') for f in os.listdir(root_dir): if f.endswith(".air"): airName = f script = os.path.join(root_dir, f) print(script) now = datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S-') log = os.path.join(root_dir, 'log' + '\\' + airName.replace('.air', '')) print(log) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + 'is created') output_file = log + '\\' + now + '-log.html' args = Namespace(device=device, log=log, recording=None, script=script) try: run_script(args, AirtestCase) except: pass finally: rpt = report.LogToHtml(script, log) rpt.report("log_template.html", output_file=output_file) result = {} result["name"] = airName.replace('.air', '') result["result"] = rpt.test_result results.append(result) # 生成聚合报告 env = jinja2.Environment(loader=jinja2.FileSystemLoader(root_dir), extensions=(), autoescape=True) File_Path = root_dir + "\\" + "report" if not os.path.exists(File_Path): # 目录不存在,进行创建操作 os.makedirs(File_Path) template = env.get_template("summary_template.html", root_dir) html = template.render({"results": results}) output_file = os.path.join(File_Path, now + "-summary.html") with io.open(output_file, 'w', encoding="utf-8") as f: f.write(html) print(output_file)
def run_air(self, root_dir='', device=''): # 聚合结果 results = [] # 获取所有用例集 root_log = root_dir + '\\' + 'log' if os.path.isdir(root_log): shutil.rmtree(root_log) else: os.makedirs(root_log) print(str(root_log) + 'is created') for f in os.listdir(root_dir): if f.endswith(".air"): # f为.air案例名称:手机银行.air airName = f script = os.path.join(root_dir, f) # airName_path为.air的全路径:D:\tools\airtestCase\案例集\log\手机银行 print(script) # 日志存放路径和名称:D:\tools\airtestCase\案例集\log\手机银行1 log = os.path.join(root_dir, 'log' + '\\' + airName.replace('.air', '')) print(log) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(str(log) + 'is created') output_file = log + '\\' + 'log.html' # global args args = Namespace(device=device, log=log, recording=None, script=script) try: run_script(args, AirtestCase) except: pass finally: rpt = report.LogToHtml(script, log) rpt.report("log_template.html", output_file=output_file) result = {} result["name"] = airName.replace('.air', '') result["result"] = rpt.test_result results.append(result) total_case = len(results) pass_case = len([i for i in results if i["result"] == 'success']) fail_case = len([i for i in results if i["result"] == 'fail']) pass_rate = '%.1f' % (pass_case / total_case * 100) # 生成聚合报告 env = jinja2.Environment( # loader=jinja2.FileSystemLoader(root_dir), loader=jinja2.FileSystemLoader( os.path.dirname(os.path.realpath(__file__))), extensions=(), autoescape=True) # template = # env.get_template("summary_template.html", root_dir) print("1111" + os.getcwd()) template = env.get_template("summary_template.html") html = template.render({ "results": results, 'total_case': total_case, 'pass_case': pass_case, 'fail_case': fail_case, 'pass_rate': pass_rate }) output_file = os.path.join(root_dir, "summary_{}.html".format(device[11:])) with io.open(output_file, 'w', encoding="utf-8") as f: f.write(html) print(output_file)
class CustomAirtestCase(AirtestCase): PROJECT_ROOT = "G:\\airtestCase\\" def setUp(self): print("custom setup") # add var/function/class/.. to globals # 将自定义变量添加到self.scope里,脚本代码中就能够直接使用这些变量 self.scope["hunter"] = "i am hunter" self.scope["add"] = lambda x: x + 1 # 将默认配置的图像识别准确率阈值改为了0.75 ST.THRESHOLD = 0.75 # exec setup script # 假设该setup.air脚本存放在PROJECT_ROOT目录下,调用时无需填写绝对路径,可以直接写相对路径 self.exec_other_script("setup.air") super(CustomAirtestCase, self).setUp() def tearDown(self): print("custom tearDown") # exec teardown script self.exec_other_script("teardown.air") super(CustomAirtestCase, self).setUp() if __name__ == '__main__': ap = runner_parser() args = ap.parse_args() run_script(args, CustomAirtestCase)
def run_air(air_dir, device): start_time = datetime.datetime.now() start_time_fmt = start_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] # 聚合结果 results = [] # 获取所有用例集 if os.path.isdir(log_path): shutil.rmtree(log_path) else: os.makedirs(log_path) for file in os.listdir(air_dir): if file.endswith('.air'): # f为.air测试用例名称:test1.air airName = file airDirName = file.replace('.air', '') # script为.air的全路径:D:\test\airtest_V7\test_case\test1.air script = os.path.join(air_dir, file) # air_log为日志存放路径和名称 air_log = log_path + "\\" + airDirName # 判断case日志在不在,在,则删除目录中的内容,否则,新建每个脚本log目录 if os.path.isdir(air_log): print(air_log) shutil.rmtree(air_log) else: os.makedirs(air_log) # 日志输出文件log:D:\test\airtest_V7\test_case\log\test1\log.html output_file1 = air_log + '\\' + 'log.html' # 命令行参数,解析获得后的数据格式Namespace(device=device, log=log, recording=None, script=script) # args = Namespace(device=device, log=log, recording=None, script=script) args = Namespace(device=device, log=air_log, recording=None, script=script, compress=10) try: run_script(args, AirtestCase) except AssertionError: pass finally: rpt = report.LogToHtml(script, air_log) # 结果模板渲染,“log_template.html”自带的模板,output_file日志存放路径 rpt.report("log_template.html", output_file=output_file1) # 结果保存在result对象中 # result = {} result = dict() result['name'] = airName.replace('.air', '') result['result'] = rpt.test_result results.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 # 根据summary_template.html模板,生成聚合报告 env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_path), extensions=(), autoescape=True) template = env.get_template(template_name, template_path) success = 0 fail = 0 for res in results: if res['result']: success += 1 else: fail += 1 report_name = 'report' + end_time.strftime("%Y%m%d%H%M%S") + ".html" html = template.render({ "results": results, 'device': phone, "stime": start_time_fmt, 'etime': end_time_fmt, 'duration': duration, "project": project_name, "success": success, "fail": fail }) output_file2 = os.path.join(report_path, report_name) with io.open(output_file2, 'w', encoding='utf-8') as f: f.write(html)
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 = [] root_log = log_path # 判断该路径是否为目录 if os.path.isdir(root_log): # shutil.rmtree() 表示递归删除文件夹下的所有子文件夹和子文件 shutil.rmtree(root_log) else: # os.makedirs() 方法用于递归创建目录。 os.makedirs(root_log) # 返回指定目录下的所有文件和目录名,通过file进行循环 for file in os.listdir(air_path): # 如果file中结尾带了“.air” if file.endswith(".air"): airName = file # 把“.air”换成空格,因为airtest自动生成的文件名带.air airDirName = file.replace(".air", "") # root\air\xxx.air,每个用例的脚本路径 script = os.path.join(air_dir, file) # root\log\\xxx,每个用例的测试报告 air_log = os.path.join(root_path, "log\\" + airDirName) # 如果air_log是目录,删除其目录下的子目录及文件夹 if os.path.isdir(air_log): # print(air_log) shutil.rmtree(air_log) else: os.makedirs(air_log) # html每个用例测试报告(html文件)存放的路径,root\log\\xxx\log.html html = os.path.join(air_log, "log.html") if deviceType.upper() == "WEB": args = Namespace(device=[], log=air_log, recording=None, script=script, language="zh", compress=0) elif deviceType.upper() == "APP": args = Namespace(device=device, log=air_log, recording=airDirName + ".mp4", script=script, language="zh", compress=0) else: args = Namespace(device=device, log=air_log, recording=None, script=script, language="zh", compress=0) try: run_script(args, AirtestCase) # airtest的run方法 except AssertionError as e: pass finally: # 将脚本路径和测试报告(截图)路径用report.py的LogToHtml生成html文件 rpt = report.LogToHtml(script, air_log) # "log_template.html"报告名称,输出文件是HTML文件 rpt.report("log_template.html", output_file=html) result = {} result["name"] = airName.replace('.air', '') result["result"] = rpt.test_result results.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 # jinja2是python的模板引擎(语法),loader模板加载器,FileSystemLoader从文件目录中获取模板 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 = 0 fail = 0 for res in results: if res['result']: success += 1 else: fail += 1 report_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 }) output_file = os.path.join(root_path, "report", report_name) with io.open(output_file, 'w', encoding="utf-8") as f: f.write(html)
"""Custom setup logic here.""" print("custom setup") # # add var/function/class/.. to globals: # self.scope["add"] = lambda x: x+1 # # exec setup test script: # self.exec_other_script("setup.air") # # set custom parameter in Settings: # ST.THRESHOLD = 0.75 super(CustomCase, self).setUp() def tearDown(self): """Custom tear down logic here.""" print("custom tearDown") # # exec teardown script: # self.exec_other_script("teardown.air") super(CustomCase, self).tearDown() if __name__ == '__main__': ap = runner_parser() args = ap.parse_args() print('custom args: ', args) args.devices = [ "Android:///", ] run_script(args, CustomCase)
def run_air(self, root_dir='D:\\tools\\airtestCase\\案例集', device=['android://127.0.0.1:5037/99.12.74.40:7281']): # 聚合结果 results = [] case_count = 0 case_count_success = 0 case_count_fail = 0 # 获取所有用例集 root_log = root_dir + '\\' + 'log' if os.path.isdir(root_log): shutil.rmtree(root_log) else: os.makedirs(root_log) logger.info('log文件夹位置=' + str(root_log)) for f in alltestnames: case_count = case_count + 1 logger.info("case_count=" + str(case_count)) if f.endswith(".air"): # f为.air案例名称:手机银行.air airName = f script = os.path.join(root_dir, f) # airName_path为.air的全路径:D:\tools\airtestCase\案例集\log\手机银行 logger.info('执行用例全路径=' + script) # 日志存放路径和名称:D:\tools\airtestCase\案例集\log\手机银行1 log = os.path.join(root_dir, 'log' + '\\' + airName.replace('.air', '')) logger.info('用例log保存文件夹=' + log) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) logger.info('log保存路径=' + str(root_log)) output_file = log + '\\' + 'log.html' args = Namespace(device=device, log=log, recording=None, script=script) try: run_script(args, AirtestCase) except: pass finally: rpt = report.LogToHtml(script, log) try: rpt.report("log_template.html", output_file=output_file) except Exception as e: # 创建一个日志器logger logger.exception(str(e)) pass result = {} result["name"] = airName.replace('.air', '') result["result"] = rpt.test_result print("===============" + str(rpt.test_result)) if str(rpt.test_result) == 'True': case_count_success = case_count_success + 1 else: case_count_fail = case_count_fail + 1 result["conf_root_dir"] = conf_root_dir results.append(result) # 生成聚合报告 # root_dir_summary = conf_root_dir + 'summary-log' root_dir_summary = '../summary-log' logger.info(root_dir) env = jinja2.Environment( loader=jinja2.FileSystemLoader(root_dir_summary), extensions=(), autoescape=True) now = time.strftime("%Y%m%d-%H%M%S", time.localtime(time.time())) summary_name = now + "summary.html" template = env.get_template("summary_template.html", root_dir_summary) html = template.render({"results": results}, case_count=case_count, case_count_success=case_count_success, case_count_fail=case_count_fail) output_file = os.path.join(root_dir_summary, summary_name) logger.info('summary全路径=' + output_file) with io.open(output_file, 'w', encoding="utf-8") as f: f.write(html)
def run_air(self, root_dir, device): #聚合报告 results = [] #日志路径和用例路径 root_log = root_dir + '\\testresults' + '\\log' case_dir = root_dir + '\\testcases' if os.path.isdir(root_log): #判断是否是一个目录 shutil.rmtree(root_log) #递归删除root_log目录(包括自身目录) else: os.makedirs( root_log) #os.makedirs 与os.mkdir(最后一级,如果前面没有则报错)的区别在于目录创建方式 print(root_log, 'is created') for f in os.listdir(case_dir): #.air为脚本文件 if f.endswith(".air"): if f == '打开小程序': continue else: airname = f #脚本存放路径和名称 script = os.path.join(case_dir, airname) print(script) #日志存放路径和名称 log = os.path.join(root_log, airname.replace('.air', '')) print(log) if os.path.isdir(log): shutil.rmtree(log) else: os.makedirs(log) print(log, 'is created') output_file = os.path.join(log, 'log.html') print(output_file) args = Namespace(device=device, log=log, recording=None, script=script, compress=False) try: run_script(args, AirtestCase) except: pass finally: rpt = report.LogToHtml(script, log) rpt.report('log_template.html', output_file=output_file) result = {} result['name'] = airname.replace('.air', '') result['result'] = rpt.test_result results.append(result) #生成聚合报告 env = jinja2.Environment( \ loader=jinja2.FileSystemLoader(os.path.join(root_dir,'testresults')), \ extensions=(), \ autoescape=True \ ) #template = env.get_template('summary_template.html',root_dir) template = env.get_template('summary_template.html', os.path.join(root_dir, 'testresults')) html1 = template.render({"results": results}) output_file = os.path.join(os.path.join(root_dir, 'testresults'), 'summary.html') with io.open(output_file, 'w', encoding='utf-8') as f: f.write(html1) print(output_file)