目錄結構
1、導入各功能模塊 — runtest.py
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 = "540XXXXXX@qq.com" #發送端 psw = "jnl**********bef" #密碼/授權碼 receiver = "810XXXXXX@qq.com" #接收端 #=========編輯郵件內容========= 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 測試報告附件