Exemplo n.º 1
0
def run_batch_test(request, Webhook=None):
    """
    批量运行用例
    :param request:
    :return:
    """
    if Webhook is None:
        if request.session.get('login_status'):
            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',
                                          runner.summary)
        else:
            return HttpResponseRedirect("/api/login/")
    elif Webhook == 'Webhook':
        testcase_dir_path = os.path.join(os.getcwd(), "suite")
        testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())
        test_list = request.pop('id')
        base_url = request.pop('env_name')
        type = request.pop('type')
        report_name = request.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('用例执行中,请稍后查看报告即可,默认时间戳命名报告')
Exemplo n.º 2
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)
Exemplo n.º 3
0
def module_hrun(name, base_url, module, receiver, config=None):
    """
    异步运行模块
    :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, config)
    except ObjectDoesNotExist:
        return '找不到模块信息'
    run_time = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(time.time()))
    runner.run(testcase_dir_path)

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

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

    return runner.summary
Exemplo n.º 4
0
def run_batch_test(request):
    """
    批量运行用例
    :param request:
    :return:
    """


    testcase_dir_path = os.path.join(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]), "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'))
        logger.info("前台传入参数:{}".format(kwargs))
        test_list = kwargs.pop('id')
        base_url = kwargs.pop('env_name')
        type = kwargs.pop('type')
        logger.info("当前运行的用例类型为:{}".format(type))
        logger.info("-" * 30)
        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)

        summary = main_run_cases(testcase_dir_path)
        return render_to_response('report_template.html', summary)
Exemplo n.º 5
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)
Exemplo n.º 6
0
def project_hrun(name, base_url, project, receiver, config=None):
    """
    异步运行整个项目
    :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, config)

    run_time = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(time.time()))
    runner.run(testcase_dir_path)

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

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

    return runner.summary
Exemplo n.º 7
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
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
0
def suite_hrun(name, base_url, suite, receiver):
    """
    异步运行模块
    :param env_name: str: 环境地址
    :param project: str:项目所属模块
    :param module: str:模块名称
    :return:
    """
    logger.info("异步运行套件")

    suite = list(suite)

    testcase_dir_path = os.path.join(
        os.path.dirname(os.path.split(os.path.realpath(__file__))[0]), "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信息'

    summary = main_run_cases(testcase_dir_path)
    report_path = add_test_reports(summary, report_name=name)

    if receiver != '':
        send_email_reports(receiver, report_path)
    os.remove(report_path)
Exemplo n.º 12
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)
Exemplo n.º 13
0
def run_test(request):
    """
    运行用例
    :param request:
    :return:
    """

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

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

    account = request.session["now_account"]
    if request.is_ajax():
        kwargs = json.loads(request.body.decode('utf-8'))
        id = kwargs.pop('id')
        suite_name = TestSuite.objects.get(id=id).suite_name
        cfg_id = kwargs.pop('cfg_id')
        base_url = kwargs.pop('env_name')
        type = kwargs.pop('type')
        run_test_by_type(id, base_url, testcase_dir_path, type, cfg_id)
        report_name = kwargs.get('report_name', None)
        request.session["base_url"] = base_url
        request.session["cfg_id"] = cfg_id
        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')
        cfg_id = request.POST.get('cfg_id')
        request.session["base_url"] = base_url
        request.session["cfg_id"] = cfg_id
        run_test_by_type(id, base_url, testcase_dir_path, type, cfg_id)
        if type == "suite":
            suite_name = TestSuite.objects.get(id=id).suite_name
            runner.run(
                os.path.join(testcase_dir_path, "{}.yml".format(suite_name)))
        else:
            runner.run(testcase_dir_path)
        #删除yml文件,异常的时候不删除,可以用来debug
        shutil.rmtree(testcase_dir_path)
        runner._summary = timestamp_to_datetime(runner.summary, type=False)
        #data = request.body.decode('utf-8')
        # kwargs = json.loads(request.body.decode('utf-8'))
        #report_name = kwargs.get('report_name', None)
        report_name = get_test_name(id, type)
        report_id = add_test_reports(runner, account, report_name)
        if request.POST.get('account') == "Jenkins":
            result = download_report(request, report_id)
            return result
        else:
            runner.summary.setdefault("report_id", report_id)
            return render_to_response('report_template.html', runner.summary)
Exemplo n.º 14
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)
Exemplo n.º 15
0
def run_test(request):
    """
    运行用例
    :param request:
    :return:
    """
    if request.session.get('login_status'):
        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('信息解析异常,请重试')
            id = kwargs.pop('id')
            base_url = kwargs.pop('env_name')
            type = kwargs.pop('type')
            config = request.POST.get(
                'config') if request.POST.get('config') != "" else None
            run_by_module(id, base_url, testcase_dir_path, config) if type == 'module' \
                else run_by_project(id, base_url, testcase_dir_path, config)
            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')
            config = request.POST.get(
                'config') if request.POST.get('config') != "" else None
            type = request.POST.get('type', None)
            if type:
                run_by_module(id, base_url, testcase_dir_path, config) if type == 'module' \
                    else run_by_project(id, base_url, testcase_dir_path, config)
            else:
                run_by_single(id, base_url, testcase_dir_path, config)

            runner.run(testcase_dir_path)

            shutil.rmtree(testcase_dir_path)
            return render_to_response('report_template.html', runner.summary)
    else:
        return HttpResponseRedirect("/api/login/")
Exemplo n.º 16
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)
Exemplo n.º 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')
        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:
        #
        #obj = json.loads(request.GET.get('obj', None))
        obj = request.POST.dict()
        type = obj.pop('type')
        base_url = obj.pop('env_name')
        test_list = list(obj.values())
        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)
        runner.summary = timestamp_to_datetime(runner.summary, type=False)

        return render_to_response('report_template.html', runner.summary)
Exemplo n.º 18
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
Exemplo n.º 19
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)
Exemplo n.º 20
0
def project_hrun(name, base_url, project, receiver):
    """
    异步运行整个项目
    :param env_name: str: 环境地址
    :param project: str
    :return:
    """
    logger.info("异步运行整个项目")
    id = ProjectInfo.objects.get(project_name=project).id

    testcase_dir_path = os.path.join(
        os.path.dirname(os.path.split(os.path.realpath(__file__))[0]), "suite")
    testcase_dir_path = os.path.join(testcase_dir_path, get_time_stamp())

    run_by_project(id, base_url, testcase_dir_path)

    # 运行测试用例
    summary = main_run_cases(testcase_dir_path)
    report_path = add_test_reports(summary, report_name=name)

    if receiver != '':
        send_email_reports(receiver, report_path)
    os.remove(report_path)
Exemplo n.º 21
0
def run_test(request):
    """
    运行用例
    :param request:
    :return:
    """

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

    testcase_dir_path = os.path.join(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]), "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')
        logger.info("当前运行的用例类型为:{}".format(type))
        logger.info("当前运行试用的类为:run_test")
        logger.info(">>" * 30)
        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)
        #获取文件夹下所有的yml测试文件
        summary = main_run_cases(testcase_dir_path)
        return render_to_response('report_template.html', summary)
Exemplo n.º 22
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
Exemplo n.º 23
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)
Exemplo n.º 24
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)
Exemplo n.º 25
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)