上一小节我们学习了发送钉钉测试报告通知的方法,本小节我们讲解一下发送html邮件测试报告的方法。
1、自动化用例执行完后,使用pytest_terminal_summary钩子函数收集测试结果,存入本地status.txt文件中,供Jenkins调用
#conftest.py
def pytest_terminal_summary(terminalreporter, exitstatus, config):
"""收集测试报告summary,并存入status.txt文件中,供Jenkins调用"""
print("pytest_terminal_summary")
passed_num = len([i for i in terminalreporter.stats.get('passed', []) if i.when != 'teardown'])
failed_num = len([i for i in terminalreporter.stats.get('failed', []) if i.when != 'teardown'])
error_num = len([i for i in terminalreporter.stats.get('error', []) if i.when != 'teardown'])
skipped_num = len([i for i in terminalreporter.stats.get('skipped', []) if i.when != 'teardown'])
total_num = passed_num + failed_num + error_num + skipped_num
test_result = '测试通过' if total_num == passed_num + skipped_num else '测试失败'
duration = round((time.time() - terminalreporter._sessionstarttime), 2)
# 定义目录路径
directory_path = './reports/'
# 确保文件所在的目录存在
os.makedirs(os.path.dirname(directory_path), exist_ok=True)
# 定义文件路径
file_path = os.path.join(directory_path, 'status.txt')
with open(file_path, 'w', encoding='utf-8') as f:
f.write(f'TEST_TOTAL={total_num}\n')
f.write(f'TEST_PASSED={passed_num}\n')
f.write(f'TEST_FAILED={failed_num}\n')
f.write(f'TEST_ERROR={error_num}\n')
f.write(f'TEST_SKIPPED={skipped_num}\n')
f.write(f'TEST_DURATION={duration}\n')
f.write(f'TEST_RESULT={test_result}\n')
本地文件status.txt中收集测试结果示例:
2、Jenkins中安装Environment Injector 和description setter 插件
Environment Injector插件用于注入环境变量
自动化测试任务配置中,添加构建步骤
填写测试结果收集文件status.txt的路径
description setter用于构建后设置任务描述
将status.txt中的的测试结果字段映射到任务描述中
执行任务构建后,任务描述中会有显示构建的测试结果,如下
3、安装python-jenkins 库,读取自动化测试任务构建后的测试结果描述信息
pip install python-jenkins
代码如下
# email_remind.py
import json
from datetime import datetime
import jenkins
import requests
import jmespath
host = "http://localhost:8080/"
username = 'admin'
password = 'xxxxxxxxxx'
webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f4444444444-c1d3-47f2-be78-098f80c2d194"
env = "test"
stage = "回归测试"
job = "auto_api_test"
maintainer = "米兔1号"
server = jenkins.Jenkins(host, username=username, password=password)
last_build_number = server.get_job_info(job)['lastCompletedBuild']['number']
build_info = server.get_build_info(job, last_build_number)
console_url = build_info['url'] + "console"
report_url = build_info['url'] + 'allure'
# report_url = ip_host + report_url.split(":")[-1]
test_status = json.loads(build_info['description'])
print("构建测试结果描述信息:", test_status)
total = test_status["total"]
passed = test_status["passed"]
passed_ratio = round(passed / total, 4) * 100
failed = test_status["failed"]
failed_ratio = round((100 - passed_ratio), 2)
error = test_status["error"]
skipped = test_status["skipped"]
duration = test_status["duration"]
build_time = datetime.fromtimestamp(build_info['timestamp'] / 1000).strftime('%Y-%m-%d %H:%M:%S')
success = total == (passed + skipped) if passed != 0 else False
执行上述代码,可以看出,已经获取到jenkins任务的测试结果信息了
4、上一步获取到的测试结果信息,包装成消息体,调用python 发送邮件的相关方法,发送邮箱消息
import json
import html
from datetime import datetime
import jenkins
import smtplib
from email.mime.text import MIMEText
from bs4 import BeautifulSoup, NavigableString
host = "http://localhost:8080/"
username = 'admin'
password = 'xxxxxxxxxxxx'
webhook = "https://oapi.dingtalk.com/robot/send?access_token=bffb1003f5b0ac9d9be5f8c863a38e2d646a69cd231147524829ffbba10e0fa3"
env = "test"
stage = "回归测试"
job = "auto_api_test"
maintainer = "米兔1号"
server = jenkins.Jenkins(host, username=username, password=password)
last_build_number = server.get_job_info(job)['lastCompletedBuild']['number']
build_info = server.get_build_info(job, last_build_number)
print("构建信息:", build_info)
console_url = build_info['url'] + "console"
print("console:", console_url)
report_url = build_info['url'] + 'allure'
print("report_url:", report_url)
test_status = json.loads(build_info['description'])
print("测试结果:", test_status)
total = test_status["total"]
passed = test_status["passed"]
passed_ratio = round(passed / total, 4) * 100
print("passed_ratio", passed_ratio)
failed = test_status["failed"]
failed_ratio = round((100 - passed_ratio),2)
print("failed:", failed_ratio)
error = test_status["error"]
skipped = test_status["skipped"]
duration = test_status["duration"]
build_time = datetime.fromtimestamp(build_info['timestamp'] / 1000).strftime('%Y-%m-%d %H:%M:%S')
success = total == (passed + skipped) if passed != 0 else False
sender = user = '1450xxxxxxx@qq.com' # 发送方的邮箱账号
passwd = 'y222222xpbjkrdupxugcbg' # 授权码
receiver = '19345678901@139.com' # 接收方的邮箱账号,不一定是QQ邮箱
# 读入 html 文件的内容
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>钉钉oapi接口测试报告</title>
</head>
<body>
<h3>钉钉oapi接口测试报告</h3>
<li>【任务名称】:{job}</li>
<li>【测试阶段】:{stage}</li>
<li>【测试结果】:{'通过' if success else '失败'}</li>
<li>【用例总数】:{total}个</li>
<li>【通过数】:{passed}个</li>
<li>【通过率】:{passed_ratio}%</li>
<li>【失败数】:{failed}个</li>
<li>【失败率】:{failed_ratio}%</li>
<li>【错误数】:{error}个</li>
<li>【跳过数】:{skipped}个</li>
<li>【执行人】:{maintainer}</li>
<li>【执行时间】:{build_time}</li>
<li>【执行耗时】:{duration}</li>
<li><a href={report_url}>Allure详细报告,请点击查看</a></li>
<br>
(本邮件由系统自动发出,请勿回复!)
</body>
</html>
"""
print("html_content",html_content)
# with open('1.html', mode='r', encoding='utf-8') as f:
# html_content = f.read()
# 指定类型是 html
msg = MIMEText(html_content, 'html', 'utf-8')
msg['From'] = user
msg['To'] = receiver
msg['Subject'] = '钉钉oapi接口测试任务执行报告通知'
smtp = smtplib.SMTP_SSL('smtp.qq.com', 465)
smtp.login(user, passwd)
smtp.sendmail(user, receiver, msg.as_string())
查看邮件如下:
最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走,希望可以帮助到大家!