【分享】通过企业微信推送测试用例结果

自动化测试执行完成之后,都会发送一个报告,以便查看测试情况,常用消息推送有企业微信,钉钉,邮件等。目前采用企业微信完成消息推送。

经查阅文档,在pytest 框架里面有一个Hooks函数 pytest_terminal_summary 可以获取到执行报告数据。经简单的处理,就可以得到一个简易的测试报告消息,代码如下:

步骤1:

在 conftest.py文件写入以下内容

# conftest.py文件
import time 
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    total_case = terminalreporter._numcollected
    pass_case = len([i for i in terminalreporter.stats.get('passed', [])])
    fail_case = len([i for i in terminalreporter.stats.get('failed', [])])
    error_case = len([i for i in terminalreporter.stats.get('error', [])])
    skip_case = len([i for i in terminalreporter.stats.get('skipped', [])])
    pass_rate = round(pass_case / total_case * 100, 2)

    desc = f"""{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())} 构建
本次执行情况如下:
总用例数为:{total_case}
通过用例数:{pass_case}
失败用例数:{fail_case}
错误用例数:{error_case}
跳过用例数:{skip_case}
通过率为:{pass_rate}%"""
    
    # 此处可以调用微信、钉钉、邮件相应方法推送消息
    WxSendMsg().sendmsg(desc)  # 调用tools.py文件下的 WxSendMsg类。

pytest文档:
https://docs.pytest.org/en/6.2.x/reference.html#_pytest.hookspec.pytest_terminal_summary

步骤2:

写相应的推送消息方法,以下是企业微信的推送

# tools.py
class WxSendMsg:
    CORPID = "此处填写企业ID" 
    CORPSECRET = "此处填写应用的凭证密钥" 

      def __init__(self):
        self.token = self.get_token()


    def get_token(self):
        """获取 token """
        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.CORPID}&corpsecret={self.CORPSECRET}"
        r = requests.get(url)
        print(r.status_code)
        print(r.text)
        return r.json().get("access_token")

    def sendmsg(self, sendmsg):
       '''发送消息,具体查阅文档 https://work.weixin.qq.com/api/doc/90000/90135/90236'''
        html = requests.post(
            f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={self.token}',
            json={
                "touser": "your useid",
                "toparty": "1",
                "msgtype": "text",
                "agentid": 'your agentid',
                "text": {
                    "content": sendmsg
                },
                "safe": 0,
                "enable_id_trans": 0,
                "enable_duplicate_check": 0,
                "duplicate_check_interval": 1800
            }

        )
        print(html.url)
        print(html.status_code)
        print(html.text)
    

运行结果:

image

1 个赞

赞一个,我公司现在用的是群机器人也挺好用的,markdown格式贼香