Пример #1
0
def main_run_cases(testset_path):
    """
    批量运行测试用例方法,包含异步,同步运行方式
    :param testset_path: 测试用例本地地址
    :return: summary (dict运行结果)
    """
    runner = HttpRunner()
    runner.with_variables({})  #清楚原runner中的缓存variables
    test_dic, error_requests, sum_temps = [], [], []
    account_list = testset_path.split(separator)[-1].split('&')
    user_account = account_list[0] if len(account_list) > 1 else ""
    getAllYml(testset_path, test_dic)
    start_time = time.time()
    for test_case_dir in test_dic:
        logger.info("当前运行的用例文件为:{}".format(test_case_dir))
        try:
            runner.run_path(test_case_dir)
        except Exception as e:
            fail_request_datas = dump_yaml_to_dict(test_case_dir)
            fail_data = fail_request_handle(fail_request_datas, str(e))
            error_requests += fail_data
            logger.info("%s 接口处理报错: %s" %
                        (fail_request_datas['config']['name'], str(e)))
        sum_temp = runner.get_summary()
        if sum_temp.success:
            sum_temp = timestamp_to_datetime(sum_temp)
            sum_temps += sum_temp
        #logger.info("{} 文件执行完之后生成的结果为:{}".format(test_case_dir, sum_temp))
    end_time = time.time()
    duration = end_time - start_time
    shutil.rmtree(testset_path)
    summary = {
        'name': '出入口',
        'success': True,
        'time': {
            'start_at': start_time,
            'start_at_iso_format': start_time,
            'end_time': end_time,
            'duration': duration
        },
        'step_datas': []
    }

    summary['step_datas'] += sum_temps
    summary['step_datas'] += error_requests

    summary = timestamp_to_datetime(summary, type=False)
    summary['case_id'] = str(len(summary['step_datas']))
    hrun_version = __version__
    python_version = str(version_info.major) + "." + str(
        version_info.minor) + "." + str(version_info.micro)
    summary['platform'] = {
        'httprunner_version': hrun_version,
        'python_version': python_version
    }
    summary['user_account'] = user_account
    logger.info("生成报告前的summary:{}".format(summary))
    return summary
Пример #2
0
def admin_test(request):
    try:
        base_url = tools.get(request,'env_name')
        name = tools.get(request,'name')
    except Exception:
        return JsonResponse({"status":2000,"message":"parameter 'base_url' or 'name' is Missing"})
    else:
        id = TestCaseInfo.objects.get(name=name).id
        kwargs = {"failfast": False,}
        runner = HttpRunner(**kwargs)
        testcase_dir_path = os.path.join(os.getcwd(), "suite")
        testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())
        type = request.POST.get('type', 'test')

        run_test_by_type(id, base_url, testcase_dir_path, type)
        runner.run(testcase_dir_path)
        shutil.rmtree(testcase_dir_path)
        runner.summary = timestamp_to_datetime(runner.summary, type=False)
        report_name = kwargs.get('report_name', None)
        reports_url = add_test_reports(runner, report_name=report_name)

        timeStamp = tools.getRe(reports_url,r"\\(\d+?)\.")
        name = tools.getTime(int(timeStamp))
        id = TestReports.objects.get(report_name=name).id
        reports_url = "http://192.168.80.86:8000/admin/view_report/%d/" %(id)

        status = runner.summary.get('success')
        successes = runner.summary.get('stat').get('successes')
        testsRun = runner.summary.get('stat').get('testsRun')

        response_data = {'status':status,'success':successes,'testsRun':testsRun,'reports_url':reports_url}
        return JsonResponse(response_data)
Пример #3
0
def project_hrun(name, base_url, project, receiver):
    """
    异步运行整个项目
    :param env_name: str: 环境地址
    :param project: str
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    id = ProjectInfo.objects.get(project_name=project).id

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    run_by_project(id, base_url, testcase_dir_path)

    # runner.run(testcase_dir_path)
    runner.summary = runner.run(testcase_dir_path)
    shutil.rmtree(testcase_dir_path)

    runner.summary = timestamp_to_datetime(runner.summary)
    report_path = add_test_reports(runner, report_name=name)[0]

    if receiver != '':
        send_email_reports(receiver, report_path, name=name)
    os.remove(report_path)
Пример #4
0
def suite_hrun(name, base_url, suite, receiver):
    """
    异步运行模块
    :param env_name: str: 环境地址
    :param project: str:项目所属模块
    :param module: str:模块名称
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    suite = list(suite)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    try:
        for value in suite:
            run_by_suite(value[0], base_url, testcase_dir_path)
    except ObjectDoesNotExist:
        return '找不到Suite信息'


    runner.run(testcase_dir_path)

    shutil.rmtree(testcase_dir_path)
    runner.summary = timestamp_to_datetime(runner.summary)
    add_test_reports(report_name=name, **runner.summary)

    if receiver != '':
        send_html_reports(receiver, runner)

    return runner.summary
Пример #5
0
def run_logic_test(request):
    account = request.session["now_account"]

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner_ext(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        request_data = json.loads(request.body.decode('utf-8'))
        # report_name = kwargs.get('report_name', None)
        main_hrun.delay(testcase_dir_path, account, request_data)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        id = request.POST.get('id')
        base_url = request.POST.get('env_name')
        type = request.POST.get('type', 'test')

        report_name = run_by_logic_test(id, base_url, testcase_dir_path)
        runner.run3(testcase_dir_path)
        shutil.rmtree(testcase_dir_path)
        runner.summary = timestamp_to_datetime(runner.summary, type=False)

        add_test_reports(runner, report_name=report_name, report_type=type, executor=account)

        return render_to_response('report_template.html', runner.summary)
Пример #6
0
def module_hrun(name, base_url, module, receiver):
    """
    异步运行模块
    :param env_name: str: 环境地址
    :param project: str:项目所属模块
    :param module: str:模块名称
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    module = list(module)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    try:
        for value in module:
            run_by_module(value[0], base_url, testcase_dir_path)
    except ObjectDoesNotExist:
        return '找不到模块信息'

    # runner.run(testcase_dir_path)
    runner.summary = runner.run(testcase_dir_path)

    shutil.rmtree(testcase_dir_path)
    runner.summary = timestamp_to_datetime(runner.summary)
    report_path = add_test_reports(runner, report_name=name)[0]

    if receiver != '':
        send_email_reports(receiver, report_path, name=name)
    os.remove(report_path)
Пример #7
0
def run_test(request):
    """
    运行用例
    :param request:
    :return:
    """

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        id = kwargs.pop('id')
        base_url = kwargs.pop('env_name')
        type = kwargs.pop('type')
        run_test_by_type(id, base_url, testcase_dir_path, type)
        report_name = kwargs.get('report_name', None)
        main_hrun.delay(testcase_dir_path, report_name)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        id = request.POST.get('id')
        base_url = request.POST.get('env_name')
        type = request.POST.get('type', 'test')

        run_test_by_type(id, base_url, testcase_dir_path, type)
        runner.run(testcase_dir_path)
        shutil.rmtree(testcase_dir_path)
        runner.summary = timestamp_to_datetime(runner.summary, type=False)

        return render_to_response('report_template.html', runner.summary)
Пример #8
0
def run_test(request):
    """
    运行用例
    :param request:
    :return:
    """

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        id = kwargs.pop('id')
        base_id = kwargs.get('env_name')
        type = kwargs.pop('type')
        # print('id1:', request.POST.get('id'))
        env_values = EnvInfo.objects.filter(id=base_id).values()

        base_url = env_values[0].get('base_url')
        env_token = env_values[0].get('env_token')
        env_merchantId = env_values[0].get('env_merchantId')

        run_test_by_type(id, base_url, env_token, env_merchantId,
                         testcase_dir_path, type)

        report_name = kwargs.get('report_name', None)
        main_hrun(testcase_dir_path, report_name, base_id)
        # main_hrun.delay(testcase_dir_path, report_name)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        id = request.POST.get('id')
        type = request.POST.get('type', 'test')

        base_id = request.POST.get('env_name')
        # 修改了前端的value值,通过查询数据库获取 baseu_url

        print('base_id: ', base_id)
        env_values = EnvInfo.objects.filter(id=base_id).values()

        base_url = env_values[0].get('base_url')
        env_token = env_values[0].get('env_token')
        env_merchantId = env_values[0].get('env_merchantId')
        # print('运行的这里id: ', request.POST)
        run_test_by_type(id, base_url, env_token, env_merchantId,
                         testcase_dir_path, type)

        runner.run(testcase_dir_path)
        shutil.rmtree(testcase_dir_path)
        runner.summary = timestamp_to_datetime(runner.summary,
                                               base_id,
                                               type=False)

        return render_to_response('report_template.html', runner.summary)
Пример #9
0
def run_batch_test(request):
    """
    批量运行用例
    :param request:
    :return:
    """

    account = request.session["now_account"]

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        request_data = json.loads(request.body.decode('utf-8'))
        batch_main_hrun.delay(testcase_dir_path, account, request_data)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        type = request.POST.get('type', None)
        base_url = request.POST.get('env_name')
        report_name = request.POST.get('report_name')
        test_list = request.body.decode('utf-8').split('&')
        if type:
            run_by_batch(test_list, base_url, testcase_dir_path, type=type, mode=True)
        else:
            run_by_batch(test_list, base_url, testcase_dir_path)

        runner.run2(testcase_dir_path)

        shutil.rmtree(testcase_dir_path)
        runner.summary = timestamp_to_datetime(runner.summary, type=False)

        if not report_name:
            report_name = '批量执行'
            if type == 'project':
                report_name = report_name + '项目'
            elif type == 'module':
                report_name = report_name + '模块'
            elif type == 'suite':
                report_name = report_name + '套件'
            elif type is None:
                report_name = report_name + '用例'

        if type is None:
            type = 'test'
        add_test_reports(runner, report_name=report_name, report_type=type, executor=account)

        return render_to_response('report_template.html', runner.summary)
Пример #10
0
def main_hrun(testset_path, executor=None, request_data=None):
    """
    用例运行
    :param testset_path: dict or list
    :param report_name: str
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    error_info = {
        'start_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    report_type = 'test'
    report_name = '执行异常'

    try:
        id = request_data.pop('id')
        base_url = request_data.pop('env_name')
        type = request_data.pop('type')
        report_name = request_data.get('report_name', None)
        if type:
            report_type = type

        report_name2 = run_test_by_type(id, base_url, testset_path, type)

        if not report_name:
            report_name = report_name2

        runner.run2(testset_path)
        shutil.rmtree(testset_path)
        runner.summary = timestamp_to_datetime(runner.summary)
        report_path = add_test_reports(runner,
                                       report_name=report_name,
                                       report_type=report_type,
                                       executor=executor)
    except Exception as e:
        logger.log_info("出现异常: {0}".format(e))
        error_info['error_msg'] = "出现异常: {0}".format(e)
        add_error_reports(error_info,
                          report_name=report_name,
                          report_type=report_type,
                          executor=executor)
    except BaseException as e:
        logger.log_info("出现异常: {0}".format(e))
        error_info['error_msg'] = "出现异常: {0}".format(e)
        add_error_reports(error_info,
                          report_name=report_name,
                          report_type=report_type,
                          executor=executor)
Пример #11
0
def run_test(request):
    print("!!!用例开始运行!!!")
    print(request.body)
    print(request.path)
    print(request.encoding)
    print(request.method)
    print(request.META.get("CONTENT_TYPE"))
    print("请求来源:",request.META.get("REMOTE_ADDR"))
    """
    运行用例
    :param request:
    :return:
    """
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        id = kwargs.pop('id')
        base_url = kwargs.pop('env_name')
        type = kwargs.pop('type')
        run_test_by_type(id, base_url, testcase_dir_path, type)
        report_name = kwargs.get('report_name', None)
        main_hrun.delay(testcase_dir_path, report_name)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        id = request.POST.get('id')
        base_url = request.POST.get('env_name')
        type = request.POST.get('type', 'test')
        print(id,base_url,type)

        run_test_by_type(id, base_url, testcase_dir_path, type)
        t1 = runner.run(testcase_dir_path)
        print("用例执行结果",t1.gen_html_report())
        shutil.rmtree(testcase_dir_path)
        runner.summary = timestamp_to_datetime(runner.summary, type=False)

        #修复BUG一,测试完成后report没有落库,可能是没有调用此方法,补充如下:
        report_name = kwargs.get('report_name', None)
        add_test_reports(runner, report_name=report_name)

        return render_to_response('report_template.html', runner.summary)
Пример #12
0
def run_batch_test(request):
    """
    批量运行用例
    :param request:
    :return:
    """

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        try:
            kwargs = json.loads(request.body.decode('utf-8'))
        except ValueError:
            logging.error('待运行用例信息解析异常:{kwargs}'.format(kwargs=kwargs))
            return HttpResponse('信息解析异常,请重试')
        test_list = kwargs.pop('id')
        base_url = kwargs.pop('env_name')
        type = kwargs.pop('type')
        report_name = kwargs.get('report_name', None)
        run_by_batch(test_list, base_url, testcase_dir_path, type=type)
        main_hrun.delay(testcase_dir_path, report_name)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        type = request.POST.get('type', None)
        base_url = request.POST.get('env_name')
        test_list = request.body.decode('utf-8').split('&')
        if type:
            run_by_batch(test_list,
                         base_url,
                         testcase_dir_path,
                         type=type,
                         mode=True)
        else:
            run_by_batch(test_list, base_url, testcase_dir_path)

        runner.run(testcase_dir_path)

        shutil.rmtree(testcase_dir_path)
        return render_to_response('report_template.html',
                                  timestamp_to_datetime(runner.summary))
Пример #13
0
def main_hrun(testset_path, report_name):
    """
    用例运行
    :param testset_path: dict or list
    :param report_name: str
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    runner.run(testset_path)
    shutil.rmtree(testset_path)
    runner.summary = timestamp_to_datetime(runner.summary)
    add_test_reports(report_name=report_name, **runner.summary)
    return runner.summary
Пример #14
0
def run_test_ty_id(case_id):
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    run_by_single3(case_id, '', testcase_dir_path)

    runner.run2(testcase_dir_path)
    shutil.rmtree(testcase_dir_path)

    runner.summary = timestamp_to_datetime(runner.summary, type=False)

    details = runner.summary.get('details')
    return details
Пример #15
0
def run_test(request):
    """
    运行用例
    :param request:
    :return:
    """

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        id = kwargs.pop('id')
        base_url = kwargs.pop('env_name')
        type = kwargs.pop('type')
        run_test_by_type(id, base_url, testcase_dir_path, type)
        report_name = kwargs.get('report_name', None)
        main_hrun.delay(testcase_dir_path, report_name)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        id = request.POST.get('id')
        base_url = request.POST.get('env_name')
        type = request.POST.get('type', 'test')

        testcase_dir_path1 = os.path.join(testcase_dir_path, 'guest项目')
        run_test_by_type(id, base_url, testcase_dir_path, type)
        runner.run(testcase_dir_path1)
        # shutil.rmtree(testcase_dir_path)  # 递归删除所有文件
        runner._summary = timestamp_to_datetime(runner._summary,
                                                base_url,
                                                type=False)
        with open('summary.json', 'w', encoding='utf-8') as f:
            json.dump(runner._summary,
                      f,
                      ensure_ascii=False,
                      sort_keys=True,
                      indent=4)
        return render_to_response('report_template.html', runner._summary)
Пример #16
0
def main_hrun(testset_path, report_name, envId):
    # print('testset_path: ', testset_path)
    """
    用例运行
    :param testset_path: dict or list
    :param report_name: str
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    runner.run(testset_path)
    shutil.rmtree(testset_path)

    runner.summary = timestamp_to_datetime(runner.summary, env_id=envId)
    report_path = add_test_reports(runner, report_name=report_name)
    # print('report_path: ', report_path)
    os.remove(report_path)
Пример #17
0
def run_batch_test(request):
    """
    批量运行用例
    :param request:
    :return:
    """

    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        test_list = kwargs.pop('id')
        type = kwargs.pop('type')
        base_id = kwargs.get('env_name')
        env_values = EnvInfo.objects.filter(id=base_id).values()
        base_url = env_values[0].get('base_url')
        env_token = env_values[0].get('env_token')
        env_merchantId = env_values[0].get('env_merchantId')
        report_name = kwargs.get('report_name', None)
        run_by_batch(test_list,
                     base_url,
                     env_token,
                     env_merchantId,
                     testcase_dir_path,
                     type=type)
        # main_hrun.delay(testcase_dir_path, report_name)
        main_hrun(testcase_dir_path, report_name, base_id)
        return HttpResponse('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
    else:
        type = request.POST.get('type', None)
        test_list = request.body.decode('utf-8').split('&')

        base_id = request.POST.get('env_name')

        env_values = EnvInfo.objects.filter(id=base_id).values()
        base_url = env_values[0].get('base_url')
        env_token = env_values[0].get('env_token')
        env_merchantId = env_values[0].get('env_merchantId')
        if type:
            run_by_batch(test_list,
                         base_url,
                         env_token,
                         env_merchantId,
                         testcase_dir_path,
                         type=type,
                         mode=True)
        else:
            run_by_batch(test_list, base_url, env_token, testcase_dir_path)

        runner.run(testcase_dir_path)

        shutil.rmtree(testcase_dir_path)
        runner.summary = timestamp_to_datetime(runner.summary,
                                               base_id,
                                               type=False)

        # return render_to_response('report_template.html', runner.summary)
        return render_to_response('report_template.html', runner.summary)
Пример #18
0
def debug_case(request):

    try:
        testcase_info = json.loads(request.body.decode('utf-8'))

        case_test = run_request_case(**testcase_info)

        kwargs = {
            "failfast": False,
        }
        runner = HttpRunner(**kwargs)

        testcase_dir_path = os.path.join(os.getcwd(), "suite")
        testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

        base_url = testcase_info.get('test').get('env_name')

        run_by_single2(case_test, base_url, testcase_dir_path)

        runner.run2(testcase_dir_path)
        shutil.rmtree(testcase_dir_path)

        runner.summary = timestamp_to_datetime(runner.summary, type=False)

        details = runner.summary.get('details')

        result = {}

        detail_size = len(details)
        if detail_size > 0:
            detail = details[detail_size - 1]
            records = detail.get('records')
            success = detail.get('success')
            if success:
                records_len = len(records)
                if records_len > 0:
                    result = records[records_len - 1].get('meta_data').get('response').get('json')
                    view_data = str.replace(str(result), ',', ',\n')
                    view_data = str.replace(view_data, '{', '{\n')
                    view_data = str.replace(view_data, '}', '\n}')
            else:
                records_len = len(records)
                if records_len > 0:
                    reason = ''
                    for validate in records[records_len - 1]['meta_data']['validators']:
                        if validate.get('check_result') == 'fail':
                            reason += validate['comparator']+':'+str([validate['expect'],validate['check_value']])+'\n'

                    view_data = '验证异常:异常信息如下: \n\n'
                    # 断言提示
                    if reason:
                        view_data += '断言结果:\n' + str(reason) + '\n\n'
                        view_data += '---------------------------------------------'
                        view_data += '---------------------------------------------------\n'
                    # 返回信息提示
                    result_data = records[records_len - 1].get('meta_data').get('response').get('json')
                    if result_data:
                        result_data = str.replace(str(result_data), ',', ',\n')
                        result_data = str.replace(result_data, '{', '{\n')
                        result_data = str.replace(result_data, '}', '\n}')
                        view_data += '返回信息:\n' + str(result_data) + '\n\n'
                        view_data += '---------------------------------------------'
                        view_data += '---------------------------------------------------\n'

                    result = records[records_len - 1].get('attachment')
                    view_data += str(result)

        # result = json.dumps(runner.summary, cls=MyEncoder)
    except Exception as e:
        result = "调试出现异常,异常信息如下: {0}".format(e)
        view_data = str.replace(str(result), ': ', ': \n')

    result = {
        'data': str(result),
        'view_data': view_data
    }

    return JsonResponse(result)
Пример #19
0
def suite_hrun(name, base_url, suite, receiver):
    """
    异步运行模块
    :param env_name: str: 环境地址
    :param project: str:项目所属模块
    :param module: str:模块名称
    :return:
    """
    logger.setup_logger('INFO')
    kwargs = {
        "failfast": False,
    }
    runner = HttpRunner(**kwargs)
    suite = list(suite)

    testcase_dir_path = os.path.join(os.getcwd(), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    try:
        for value in suite:
            run_by_suite(value[0], base_url, testcase_dir_path)
    except ObjectDoesNotExist:
        return '找不到Suite信息'

    # runner.run(testcase_dir_path)
    runner.summary = runner.run(testcase_dir_path)
    shutil.rmtree(testcase_dir_path)

    runner.summary = timestamp_to_datetime(runner.summary)

    # report_path = add_test_reports(runner, report_name=name)
    report_result = add_test_reports(runner, report_name=name)
    report_path, report_id = report_result[0], report_result[1]

    # 处理报告结果失败,发送失败主题邮件
    if not runner.summary.get('success', None):
        FailName = []
        for i in runner.summary.get('details'):
            if i.get('success') == False:
                FailName.append(i.get('name'))
        # subjects = "定时任务出现错误情况预警通知"
        status = "【 失败 】"
        bodyText = "{}定时任务执行失败用例如下:<br>&emsp; {} <br> 请套件相关维护人员及时确认!!!".format(
            name, '<br> &emsp;'.join(FailName))
        send_email_reports(receiver,
                           report_path,
                           name=name,
                           bodyText=bodyText,
                           status=status)
        os.remove(report_path)
        # 调用dingding机器人发送失败通知
        bodyText = "{}定时任务执行失败用例如下:\n {}\n如需了解更多内容,请关注邮箱中邮件!".format(
            name, '\n '.join(FailName))
        callDingTalkRobot(name, bodyText)
        return ""

    # 处理接口响应时长超时,发送告警邮件
    timeOut_result = statistics_summary_timeOut(runner.summary)
    if timeOut_result:
        status = "【 告警 】"
        bodyText = "{0}定时任务执行接口时长告警用例如下: {1}".format(
            name, write_htmlTable(timeOut_result))
        # 创建bug
        createrZentaoBug(suite[0], timeOut_result, report_id=report_id)
        send_email_reports(receiver,
                           report_path,
                           name=name,
                           bodyText=bodyText,
                           status=status)
    if receiver != '':
        send_email_reports(receiver, report_path, name=name)
    os.remove(report_path)
Пример #20
0
def run_by_service(service_config_id, base_url):
    service_config_details = ServiceConfigDetail.objects.filter(
        service_config_id=service_config_id).all()
    service_config_details = list(service_config_details)

    # 用例ID集合
    test_case_alls = []
    # 套件ID集合
    suite_alls = []
    for service_config_detail in service_config_details:
        type = service_config_detail.relation_type
        relation_id = service_config_detail.relation_id
        if type == 1:
            modules = ModuleInfo.objects.filter(
                belong_project_id=relation_id).values('id').all()
            modules = list(modules)
            for module in modules:
                test_cases = TestCaseInfo.objects.filter(
                    belong_module_id=module.get('id'), type=1,
                    run_type=1).values('id').all()
                test_cases = list(test_cases)
                test_case_alls.extend(test_cases)
        if type == 2:
            test_cases = TestCaseInfo.objects.filter(
                belong_module_id=relation_id, type=1,
                run_type=1).values('id').all()
            test_case_alls.extend(list(test_cases))
        if type == 3:
            suite = {'id': relation_id}
            suite_alls.append(suite)
        if type == 4:
            test_case = {'id': relation_id}
            test_case_alls.append(test_case)
        if type == 5:
            test_cases = TestCaseInfo.objects.filter(
                service_name=relation_id, type=1,
                run_type=1).values('id').all()
            test_case_alls.extend(list(test_cases))

    runners = []
    # 已执行用例id,用于去除重复
    present_ids = []
    if test_case_alls:
        testcase_dir_path = os.path.join(os.getcwd(), "suite")
        testset_path = os.path.join(testcase_dir_path, get_time_stamp())
        # 运行用例
        for test_case in test_case_alls:
            case_id = test_case.get('id')
            if case_id not in present_ids:
                run_by_single(case_id, base_url, testset_path)
                present_ids.append(case_id)

        kwargs = {
            "failfast": False,
        }
        runner = HttpRunner(**kwargs)
        runner.run2(testset_path)
        shutil.rmtree(testset_path)

        runner.summary = timestamp_to_datetime(runner.summary)
        runners.append(runner)

    if suite_alls:
        for suite in suite_alls:
            testcase_dir_path = os.path.join(os.getcwd(), "suite")
            testset_path = os.path.join(testcase_dir_path, get_time_stamp())

            run_by_suite(suite.get('id'), base_url, testset_path)

            kwargs = {
                "failfast": False,
            }
            runner = HttpRunner(**kwargs)
            runner.run2(testset_path)
            shutil.rmtree(testset_path)

            runner.summary = timestamp_to_datetime(runner.summary)
            runners.append(runner)

    # 合并运行结果并生成报告
    report_runner = None
    for runn in runners:
        if report_runner is None:
            report_runner = runn
        else:
            # 合并结果
            report_runner.summary = merge_summary(report_runner.summary,
                                                  runn.summary)
    return report_runner