廢話不多說,直接上代碼:
import unittest import time import os import smtplib from HTMLTestRunner import HTMLTestRunner from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from models import driver def new_report(report_dir): ''' :param report_dir:報告路徑 :return:返回最新的文件 ''' #獲取路徑下的文件 lists = os.listdir(report_dir) #按照時間順序排序 lists.sort(key=lambda fn: os.path.getmtime(report_dir + fn)) #獲取最近時間的 new_report = os.path.join(report_dir,lists[-1]) return new_report def send_mail(new_report,new_report_fail,now): ''' :param new_report:獲取最新的文件 :param new_report_fail:獲取最新的文件的路徑 :param now:當前生成報告的時間 :return: ''' senduser = 'xxx@126.com' sendpswd = 'xxx' receuser = 'xxx@xxx.com.cn' #獲取報告文件:'related'43行 f = open(new_report,'rb') body_main = f.read() msg = MIMEMultipart() # 郵件標題 msg['Subject'] = Header('TCS系統自動化測試報告','utf-8') msg['From'] = senduser msg['To'] = receuser #郵件內容 text = MIMEText(body_main,'html','utf-8') msg.attach(text) #發送附件 att = MIMEApplication(open(new_report_fail, 'rb').read()) # att = MIMEText(sendfile, 'base64', 'utf-8') att['Content-Type'] = 'application/octet-stream' att.add_header('Content-Disposition', 'attachment', filename=('utf-8', '',now + "_report.html")) msg.attach(att) smtp = smtplib.SMTP() smtp.connect('smtp.126.com') smtp.login(senduser,sendpswd) smtp.sendmail(senduser,receuser,msg.as_string()) if __name__ == '__main__': startime = time.strftime('%H:%M:%S') print("開始時間為:%s" % startime) #測試路徑 test_dir = './tcs/test_case' #報告路徑 report_dir = './tcs/report/' now = time.strftime('%Y-%m-%d_%H-%M-%S') # 創建完整報告文件 new_report_fail = report_dir + now + '_result.html' fp = open(new_report_fail,'wb') runner = HTMLTestRunner(stream=fp, title="大標題:測試報告", description='執行測試用例如下:') # 查找測試文件 discover = unittest.defaultTestLoader.discover(test_dir,pattern='*_sta.py') runner.run(discover) fp.close() #②搜索最新生成的文件 new_report = new_report(report_dir) #③發送郵件 send_mail(new_report,new_report_fail,now) #展示測試報告html driver = driver.browser() driver.get("F:/PyProject/project/tcs/report/"+ now +"_result.html") stoptime = time.strftime('%H:%M:%S') print("結束時間為:%s" %stoptime)