Python3+HTMLTestRunner+SMTP生成測試報告後發送郵件

 

在前一篇https://www.cnblogs.com/zhengyihan1216/p/11549820.html 中記錄瞭如何生成html格式的報告,html

這篇記錄下怎麼將測試報告經過郵件發出測試

 

一、對test_add_dele.py文件進行修改及完善ui

  註釋:email庫定義郵件裏的內容,smtplib庫進行郵件發送spa

 1 #coding=utf-8
 2 from HTMLTestRunner import HTMLTestRunner  3 from email.mime.text import MIMEText  4 from email.header import Header  5 import smtplib  6 import unittest  7 import add_dele  8 import time  9 import os 10 
11 #在測試報告目錄下找到最新的報告文件,打印且返回最新報告的名稱
12 def find_new_report(report_dirc): 13     lists = os.listdir(report_dirc) 14     lists.sort(key=lambda fn:os.path.getmtime(report_dirc+"\\"+fn)) 15     new_report = os.path.join(report_dirc,lists[-1]) 16     print(new_report) 17     return new_report 18 
19 def send_mail(new_report): 20     #讀取報告
21     f = open(new_report,'rb') 22     mail_body = f.read() 23  f.close() 24     #定義郵件正文,報告以正文的形式發送
25     msg = MIMEText(mail_body,'html','utf-8') 26 
27     #定義郵件標題
28     msg['Subject'] = Header("自動化測試報告","utf-8") 29     mail_server = "mail.xxxxx.com"
30     user_name = "username1@xxxxx.com"
31     pwd = "xxxxx"
32     from_add = "username1@xxxxx.com"
33     to_add = "username2@xxxxx.com"
34 
35     smtp = smtplib.SMTP() 36  smtp.connect(mail_server) 37  smtp.login(user_name,pwd) 38  smtp.sendmail(from_add,to_add,msg.as_string()) 39  smtp.quit() 40     print("emial has send out") 41 
42 if __name__ =="__main__": 43     #構建測試集
44     suit = unittest.TestSuite() 45     #測試集加入add_dele文件中被調用的方法。格式suit.addTest(文件名.類名("方法名"))
46     suit.addTest(add_dele.Test_test("test_shuzi")) 47     suit.addTest(add_dele.Test_test("test_liangmethod")) 48     #定義存放測試報告的路徑及文件名
49     #我定義的路徑是:當前路徑+存放報告的專有目錄Report+文件名(文件名是當前時間+report.html)
50     curent_dirc=os.path.dirname(os.path.realpath(__file__)) 51     report_dirc = curent_dirc + "\Report"
52     now = time.strftime("%Y%m%d-%H%M%S") 53     report_name = report_dirc+"\\"+now+"report.html"
54     fp = open(report_name,"wb") 55     runner = HTMLTestRunner(stream=fp, 56                             title="測試一下報告生成", 57                             description="用兩個數字的相加減來練習") 58  runner.run(suit) 59  fp.close() 60     #發送郵件
61     send_mail(find_new_report(report_dirc))

 

二、username2@xxxxx.com 該郵箱中收到的報告以下截圖所示:

 三、注意問題code

  若是發出的測試報告裏測試用例沒有展開,則將.....Python35\Lib\HTMLTestRunner.py文件中的改行刪除:  .hiddenRow  { display: none; }server

  因爲你們用的HTMLTestRunner.py文件版本不一樣,因此該文件具體在第幾行不一樣,能夠根據文字進行搜索後刪除。htm

  

相關文章
相關標籤/搜索