pytest-常用钩子函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
result = {"total": 0, "passed": 0, "failed": 0, "skipped": 0, "error": 0, "timeout": 0, "times": 0,
          "warnings": 0, "other": 0, "failures_list": [], "errors_list": [], "time_out_list": []}
 
 
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    统计测试结果并发送到钉钉
    :param terminalreporter:
    :param exitstatus:
    :param config:
    :return:
    """
    # print(terminalreporter.stats)
    fail_type = []
    save_data = []
    now = time.time()
    total = terminalreporter._numcollected
    passed = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
    failed = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
    error = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
    skipped = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
    print({"total":total,"failed":failed,"error":error,"skipped":skipped})
    result.update({"total": total})
    result.update({"passed": passed})
    result.update({"failed": failed})
    result.update({"error": error})
    result.update({"skipped": skipped})
    for success in terminalreporter.stats.get('passed', []):
        if success.when != 'teardown':
            try:
                desc_dict = eval(success.description)
                # print("0000000:", desc_dict)
                url = desc_dict["url"]
                path = get_url_path(url)
            except (Exception,):
                path = "/no"
            t = success.duration
            if t >= TIME_OUT/1000:
                suite = success.fspath
                suite_name = suite.split("/")[1]
                if suite_name not in fail_type:
                    fail_type.append(suite_name)
                result["timeout"] += 1
                t_str = {"path": path, "sec": round(t, 2)}
                result["time_out_list"].append(t_str)
            if t >= 5:
                suite = success.fspath
                suite_name = suite.split("/")[1]
                t_str = {"project": suite_name, "path": path, "sec": int(t*1000), "type": 0, "datetime": now}
                save_data.append(t_str)
    for failed in terminalreporter.stats.get('failed', []):
        if failed.when != 'teardown':
            suite = failed.fspath
            suite_name = suite.split("/")[1]
            if suite_name not in fail_type:
                fail_type.append(suite_name)
            try:
                desc_dict = eval(failed.description)
                url = desc_dict["url"]
                path = get_url_path(url)
                code = desc_dict["code"]
                rsp = desc_dict["rsp"]
            except (Exception,):
                path = "/no"
                code = "0"
                rsp = "未知内容"
            f_str = {"project": suite_name, "path": path, "code": code, "rsp": rsp, "type": 1, "datetime": now}
            result["failures_list"].append(f_str)
            save_data.append(f_str)
    duration = time.time() - terminalreporter._sessionstarttime
    result["times"] = round(duration, 2)
    if result["failed"] > 0 or result["error"] > 0 or result["timeout"] > 0:
        title_type = "|".join(fail_type)
        if MSG_SWITCH and platform.system() == "Linux":
            # for token in DING_TOKEN:
            #     push_ding_msg(title_type, token, result, REPORT_PATH)
            for token in WX_TOKEN:
                push_wx_msg(title_type, token, result, REPORT_PATH)
            for token in FS_TOKEN:
                push_fs_msg(title_type, token, result, REPORT_PATH)
    if save_data:
        save_to_mongodb(save_data)
    if PHONE_SWITCH and platform.system() == "Linux":
        res = jude_phone_notice(MAX_ERROR, API_LIST)
        phone_notice(res, DUTY_PHONE, PHONE_DELAY_TIME)<br><br>@pytest.mark.hookwrapper<br>def pytest_runtest_makereport(item):<br>    """<br>    当测试失败的时候,自动截图,展示到html报告中<br>    ** 作者:上海-悠悠 QQ交流群:588402570**<br>    :param item:<br>    """<br>    pytest_html = item.config.pluginmanager.getplugin('html')<br>    outcome = yield<br>    report = outcome.get_result()<br>    extra = getattr(report, 'extra', [])<br><br>    if report.when == 'call' or report.when == "setup":<br>        xfail = hasattr(report, 'wasxfail')<br>        if (report.skipped and xfail) or (report.failed and not xfail):<br>            file_name = report.nodeid.replace("::", "_") + ".png"<br>            screen_img = _capture_screenshot()<br>            if file_name:<br>                html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ' \<br>                       'onclick="window.open(this.src)" align="right"/></div>' % screen_img<br>                extra.append(pytest_html.extras.html(html))<br>        report.extra = extra

  

posted @   我是小菜鸡丫丫  阅读(63)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示