pytest 测试框架 - 定制推送到企业微信的测试报告内容

本贴最后更新于 359 天前,其中的信息可能已经沧海桑田

1、获取企业微信群的机器人webhook

image.png

image1.png

2、获取pytest的用例执行结果,并按指定格式组织内容。

编写case_counts.py,定义一个Count类来记录不同状态的测试用例。

case_counts.py

class Count:
    all_cases = 0
    success_cases = 0
    failed_cases = 0
    error_cases = 0
    skip_cases = 0

conftest.py文件

import time
import requests
import pytest
from case_counts import Count

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
"""获取测试结果、生成测试报告"""
print('------------------------------------')
    out = yield
    report = out.get_result()
    if report.when =='call':
# print(f"测试报告:{report}")
        # print(f"步骤:{report.when}")
print(f"用例id:{report.nodeid}")
        print(f"用例描述:{str(item.function.__doc__)}")
        print(f"运行结果:{report.outcome}")
        Count.all_cases += 1
        if report.outcome =="passed":
            Count.success_cases += 1
        elif report.outcome =="failed":
            Count.failed_cases += 1
        elif report.outcome =="error":
            Count.error_cases += 1
        elif report.outcome =="skipped":
            Count.skip_cases += 1

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """汇总测试结果、并发送给企业微信群机器人通知"""
    run_time = round((time.time() - terminalreporter._sessionstarttime), 2)
    passrate = (Count.success_cases / Count.all_cases) * 100
    print("******用例执行结果统计******")
    print(f"总用例数:{Count.all_cases}条")
    print(f"通过:{Count.success_cases}条")
    print(f"失败:{Count.failed_cases}条")
    print(f"跳过:{Count.skip_cases}条")
    print(f"报错:{Count.error_cases}条")
    print(f"用例通过率:{passrate}%")
    print(f"用时:{run_time}s")
    desc ="""
本次执行情况如下:
        总用例数为:{}
通过用例数:<font color=\\"info\\">{}条</font>
失败用例数:<font color=\\"warning\\">{}条</font>
错误用例数:{}
跳过用例数:{}
通过率为:{} %
用时:{}s
        """.format(Count.all_cases, Count.success_cases, Count.failed_cases, Count.error_cases, Count.skip_cases, passrate, run_time)
 
 # 发送企业微信通知 - markdown格式
 **requests.request("post",
                     url="<https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=37bdd3d1-a885-4ab9-94e1-58b57f37117e>",
                     json={"msgtype":"markdown",
"markdown":{"content": desc}})**

3、调用企业微信webhook地址,发送组织好的内容。

企业微信开发者接口文档 :

群机器人配置说明 - 接口文档 - 企业微信开发者中心

参考此文件中,调用接口发送请求。

image2.png

回帖
请输入回帖内容 ...