pytest 用例收集钩子并发送飞书
当我们pytest用例运行完成后,想要知道运行多少个,成功还是失败,分别是多少,直接通知领导或者发到群里
conftest.pyimport requests
def pytest_terminal_summary(terminalreporter, exitstatus, config): # noqa"""收集测试结果"""total = terminalreporter._numcollected # noqaif total > 0: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'])if terminalreporter._numcollected - skipped == 0: # noqasuccessful = 0else:successful = len(terminalreporter.stats.get('passed', [])) / terminalreporter._numcollected * 100 # noqaduration = time.time() - terminalreporter._sessionstarttime # noqa# 发送飞书消息send_feishu(total, passed, failed, error, skipped, successful)print(f'测试用例总数:{total},成功:{passed},失败:{failed},错误:{error},跳过:{skipped},成功率:{successful}%,耗时:{duration:.2f}s')def send_feishu(total, passed, failed, error, skipped, successful):# 设置飞书群机器人的 Webhook URLwebhook_url = '' # 替换为你的 Webhook URL# 设置消息内容data = {"msg_type": "post","content": {"post": {"zh_cn": {"title": "车控自动化测试","content": [[{"tag": "text","text": f"执行人: O_zhenhua.zhang\n"},{"tag": "text","text": f"执行结果: 测试用例总数:{total}\n"},{"tag": "text","text": f"成功:{passed}\n"},{"tag": "text","text": f"失败:{failed}\n"},{"tag": "text","text": f"错误:{error}\n"},{"tag": "text","text": f"跳过:{skipped}\n"},{"tag": "text","text": f"成功率:{successful}%\n"},{"tag": "a","text": "请点击这里查看\n","href": "报告地址\n"},{"tag": "at","user_id": "all"}]]}}}}# 发送消息到飞书群机器人headers = {'Content-Type': 'application/json'} # 设置请求头为 JSON 类型response = requests.post(webhook_url, headers=headers, json=data)# 检查响应状态码,如果是 200 则表示发送成功if response.status_code == 200:print("报告发送成功!")else:print(f"报告发送失败,状态码:{response.status_code},错误信息:{response.text}")