1、导入各功能模块
from HTMLTestRunner import HTMLTestRunner from email.mime.text import MIMEText #发送邮件正文 from email.mime.multipart import MIMEMultipart #发送邮件附件 from email.header import Header import smtplib import unittest import time import os
2、定义发送邮件(QQ邮箱)
#============定义发送邮件============ def send_mail(file_new): smtpserver = "smtp.qq.com" #发件服务器 port = 465 #端口 sender = "[email protected]" #发送端 psw = "jnl**********bef" #密码/授权码 receiver = "[email protected]" #接收端 #=========编辑邮件内容========= f = open(file_new, ‘rb‘) mail_body = f.read() f.close() msg = MIMEMultipart() msg["from"] = sender #发件人 msg["to"] = receiver #收件人 msg["subject"] = "自动化测试报告" #主题 #正文 body = MIMEText(mail_body, "html", "utf-8") msg.attach(body) #挂起 #附件 att = MIMEText(mail_body, "base64", "utf-8") att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = ‘attachment; filename="test_report.html"‘ #定义附件名称 msg.attach(att) #挂起 #=========发送邮件========= smtp = smtplib.SMTP_SSL(smtpserver, port) smtp.login(sender, psw) smtp.sendmail(sender, receiver, msg.as_string()) #发送 smtp.quit() #关闭
3、查找测试报告目录,找到最新生成的测试报告文件
#============查找测试报告目录,找到最新生成的测试报告文件============ def new_report(testreport): lists = os.listdir(testreport) lists.sort(key=lambda fn:os.path.getatime(testreport + fn)) file_new = os.path.join(testreport, lists[-1]) print(file_new) return file_new
4、测试运行以上各代码模块
if __name__ == ‘__main__‘: test_dir = ‘./test_case/‘ #测试用例所在目录 test_report = ‘./report/‘ #测试报告所在目录 discover = unittest.defaultTestLoader.discover(test_dir,pattern=‘test_*.py‘) #匹配目录下以"test_"开头的测试用例文件 #定义实时测试报告文件,方便查看区分 now = time.strftime("%Y-%m-%d %H_%M_%S") filename = test_report + now + ‘ result.html‘ fp = open(filename, ‘wb‘) runner = HTMLTestRunner(stream=fp, title=‘测试报告‘, description=‘用例执行情况:‘) runner.run(discover) fp.close() new_report = new_report(test_report) send_mail(new_report) #发送测试报告
5、测试成功
6、下载打开 test_report.html 测试报告附件
原文地址:https://www.cnblogs.com/test-postman/p/10126374.html
时间: 2024-10-06 23:24:24