Exemplo n.º 1
0
def main(args):
    # script filepath
    path = decode_path(args.script)
    record_list = args.record or []
    log_root = decode_path(args.log_root) or path
    static_root = args.static_root or STATIC_DIR
    static_root = decode_path(static_root)
    export = decode_path(args.export) if args.export else None
    lang = args.lang if args.lang in ['zh', 'en'] else 'zh'
    plugins = args.plugins

    # gen html report
    rpt = R.LogToHtml(path,
                      log_root,
                      static_root,
                      export_dir=export,
                      lang=lang,
                      plugins=plugins)
    # override methods
    rpt._make_export_dir = types.MethodType(_make_export_dir, rpt)
    rpt.report = types.MethodType(report, rpt)
    rpt.get_result = types.MethodType(get_result, rpt)

    rpt.report(HTML_TPL, output_file=args.outfile, record_list=record_list)

    return rpt.get_result()
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
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)
Exemplo n.º 4
0
def generate_report(script, *, log_root, export_root, report_time):
    """
    生成測試報告
    :param script:  執行名稱
    :param log_root:  指令碼log目錄
    :return: export_root  測試報告輸出目錄
    """
    if not os.path.isdir(export_root):
        os.makedirs(export_root)
        print(str(export_root) + '>>> is created')
    # 生成測試報告
    rpt = report.LogToHtml(
        script_root=script,  # *.air
        log_root=log_root,  # log目錄
        export_dir=export_root,  # 設定此引數後,生成的報告內資源引用均使用相對路徑
        lang='zh',  # 設定語言, 預設"en"
        script_name=exe_script.replace(".air", ".py"),  # *.air/*.py
        static_root=AUTOLINE_HOST +
        '/static',  # 設定此引數後,打包後的資源目錄中不會包含樣式資源 http://192.168.188.145:5297/static/
        plugins=["airtest_selenium.report"]  # 使報告支援poco語句
    )
    rpt.report("log_template.html")
    # 提取指令碼執行結果
    # result = rpt.test_result  # True or False
    result = {}
    result['owner'] = exe_owner
    result["name"] = exe_script.replace('.air', '')
    script_dict = Exe_Cfg.SCRIPT_DICT
    desc_dict = Exe_Cfg.DESCRIPTION_DICT
    result["ch_name"] = script_dict[exe_script.split('_')[0].replace(
        '.air', '')]
    result['desc'] = desc_dict[exe_script.split('_')[0].replace('.air', '')]
    result["time"] = report_time
    result["result"] = rpt.test_result

    return result
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
 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)
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
    def run_air(self, device, data):
        root_log = os.path.join(data["root_path"], "log")
        if os.path.isdir(root_log):
            # shutil.rmtree(root_log)
            pass
        else:
            os.makedirs(root_log)
        get_data_list = get_test_case(data)
        if not get_data_list:
            print("无可用用例")
            return
        # 整个用例开始执行时间
        start_time = datetime.now().strftime("%H:%M:%S")
        modules = []
        # 日志按照日期格式生成
        log_date = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        for j in get_data_list:
            # 日志按照日期格式生成
            # log_date = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
            # 用例开始执行日期
            st_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            # 用例开始执行时间
            s_time = datetime.now().strftime("%H:%M:%S")
            # 循环运行用例
            get_run = run(data["root_path"], j, device, log_date)
            # 用例结束执行日期
            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(get_run["script"], get_run["log"])
            rpt.report("log_template.html", output_file=get_run["output_file"])
            # 记录测试结果
            result = {
                "name": j["case"].replace(".air", ""),
                "result": get_run["is_success"],
                "start_date": st_date,
                "end_date": end_date,
                "sum_time": sum_time,
                "module": j["module"],
                "log_date": log_date
            }
            modules.append(j["module"])
            self.results["data"].append(result)
            # 记录失败用例
            if not get_run["is_success"]:
                self.fail_data.append({
                    "module": j["module"],
                    "case": j["case"]
                })
        # 整个用例结束执行时间
        end_time = datetime.now().strftime("%H:%M:%S")
        # 以小时,分钟,秒钟的方式记录所有用例耗时时间
        total_time = get_case_total_time(start_time, end_time)
        self.results["total_time"] = total_time
        # 记录测试模块
        self.results["modules"] = get_test_modules(modules)
        # 记录设备名字
        self.results["phone"] = data["phone"]
        # 打印失败用例
        if self.fail_data:
            print("存在失败用例")
            print(self.fail_data)

        # 生成测试报告
        env = jinja2.Environment(loader=jinja2.FileSystemLoader(
            data["root_path"]),
                                 extensions=(),
                                 autoescape=True)
        print("用例结果为:%s" % self.results)
        template = env.get_template("summary_template.html", data["root_path"])
        html = template.render({"results": self.results})
        output_file = os.path.join(
            data["root_path"],
            "summary_%s.html" % datetime.now().strftime("%Y-%m-%d-%H-%M-%S"))
        with io.open(output_file, 'w', encoding="utf-8") as f:
            f.write(html)
        print(output_file)
def run_air_batch_mode(tc_folder, device):
    # 聚合结果
    report_dir = os.sep.join([BASE_DIR, 'reports'])
    case_dir = os.sep.join([BASE_DIR, tc_folder])
    
    results = []
    # 获取所有用例集
    if os.path.isdir(report_dir):
        print('report folder is exist')
        report_subs = os.listdir(report_dir) 
        print('report folder > files: ',report_subs)
        if len(report_subs):
            def is_dir(item):
                item_path=os.sep.join([report_dir,item])
                return os.path.isdir(item_path)
            
            folder_lists=list(filter(is_dir,report_subs))
            print('report folder > folders: ',folder_lists)
            folder_lists.sort(key=lambda fn:os.path.getctime(os.sep.join([report_dir,fn])))
            # getmtime ? getctime
            final_num=folder_lists[-1]
            report_num=int(final_num)+1
        else:
            report_num=0
    else:
        os.makedirs(report_dir)
        print('report folder is created')
        report_num=0
        
    report_dir_num = os.sep.join([BASE_DIR,'reports',str(report_num)])
    print('report_dir_num: ',report_dir_num)
    os.makedirs(report_dir_num)
    
    
    for f in os.listdir(case_dir):
        print('case_dir > f:',f)
        if f.endswith(".air"):
            # f为.air案例名称
            print('   (.air)test file:',f)
            airName = f
            script = os.path.join(case_dir, f)
            # airName_path为.air的全路径:BASE_DIR\案例集\testcase.air
            print('   script:',script)
            # 日志存放路径和名称:BASE_DIR\reports\案例集\testcase\
            tc_report_dir = os.path.join(report_dir_num, airName.replace('.air', ''))
            print('tc_report_dir:',tc_report_dir)
            if os.path.isdir(tc_report_dir):
                print('tc_report_dir exist ')
            else:
                os.makedirs(tc_report_dir)
                print('tc_report_dir is created')
            
            log_file=os.path.join(tc_report_dir, 'log.txt')
            
            if not os.path.exists(log_file):
                log_content = open(log_file,'w')
                print('create log file: ',log_content)
                log_content.close()
            else:
                print(log_file + " already existed.")
            output_file = os.path.join(tc_report_dir, 'log.html')
            args = Namespace(device=device, log=tc_report_dir, recording=None, script=script)
            try:
                print('运行脚本开始')
                
                #start_app("com.yiwang.fangkuaiyi")
            
                run_script(args, AirtestCase)
                
                print('运行脚本结束')
            except Exception as e:
                print('运行失败,',e)
            finally:
                #stop_app("com.yiwang.fangkuaiyi")
                
                try:
                    print('生成报告')
                    rpt = report.LogToHtml(script_root=case_dir, log_root=tc_report_dir, script_name=script)
                    print('output_file:',output_file)
                    rpt.report("log_template.html", output_file=output_file)
                    result = {}
                    result["name"] = airName.replace('.air', '')
                    result["result"] = rpt.test_result
                    results.append(result)
                except Exception as e:
                    print('运行失败,暂时不抛异常,',e)
                
    
    print('生成聚合报告')
    # 生成聚合报告
    static_dir=os.sep.join([BASE_DIR,'statics'])
    print('static_dir: ',static_dir)
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(static_dir),
        extensions=(),
        autoescape=True
    )
    template = env.get_template("summary_template.html", static_dir)
    print('template: ',template)
    html = template.render({"results": results,"report_num":report_num})
    summary_file = os.path.join(report_dir_num, "summary.html")
    with io.open(summary_file, 'w', encoding="utf-8") as f:
        f.write(html)
    print('summary_file:',summary_file)
Exemplo n.º 10
0
    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)
Exemplo n.º 11
0
                                     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]
                    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

        env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_path),
                                 extensions=(),
                                 autoescape=True)
Exemplo n.º 12
0
    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)
Exemplo n.º 13
0
     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)
Exemplo n.º 14
0
    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)
Exemplo n.º 15
0
    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)
Exemplo n.º 16
0
    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)