1. 程式人生 > >selenium測試報告生成、找到測試報告路徑、實現發郵件(整合)

selenium測試報告生成、找到測試報告路徑、實現發郵件(整合)

文件 base pat inf chm 一個 ret pan rep

有這樣的一個場景:

假設生成的測試報告與多人相關,每個人都去測試服務器査看就會比較麻煩,如果把這種主動的且不及時的査看變成被動且及時的査收,就方便多了。

整個程序的執行過程可以分為三個步驟:

① 通過unittest框架的discover()找到匹配測試用例,由HTMLTestRunner的run()方法執行測試用例並生成最新的測試報告。

② 調用new_report()函數找到測試報告目錄(test_case)下最新生成的測試報告,返回測試報告的路徑。

③ 將得到的最新測試報告的完整路徑傳給send_mail()函數,實現發郵件功能。

實例代碼如下:

import unittest

import time
import os
import smtplib
from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

#定義發送郵件
def send_mail(file_new):
f=open(file_new,‘rb‘)
mail_body=f.read()
f.close()
#構造附件
att = MIMEText(mail_body, ‘base64‘, ‘utf-8‘)

att["Content-Type"] = ‘application/octet-stream‘
att["Content-Disposition"] = ‘attachment;filename="latestResult.html"‘
msg = MIMEMultipart(‘related‘)
msg[‘subject‘] = Header("自動化測試報告", ‘utf-8‘)
msg.attach(att)
#加郵件頭
#加郵件頭
msg[‘From‘] = ‘[email protected] <[email protected]>‘

msg[‘To‘] = ‘[email protected]
smtp=smtplib.SMTP()
smtp.connect("smtp.sina.com",25)
smtp.login("[email protected]","lili123456")
smtp.sendmail(‘[email protected]‘,‘[email protected]‘,msg.as_string())
smtp.quit()
print("email has send out!")

#查找測試報告目錄,找到最新生成的測試報告文件,並發送
def new_report(test_report):
lists=os.listdir(test_report)
lists.sort(key=lambda fn :os.path.getmtime(test_report+‘\\‘+fn))
print((‘最新的文件為:‘+lists[-1]))
file_new=os.path.join(test_report,lists[-1])
print(file_new)
return file_new
if __name__==‘__main__‘:
test_dir = r‘E:\selenium+puthon+pycharm學習\test_project\test_case‘
discover = unittest.defaultTestLoader.discover(test_dir, pattern=‘test_*.py‘)
now = time.strftime("%Y-%m-%d %H-%M-%S")
filename = test_dir + ‘//‘ + now + ‘result.html‘
fp = open(filename, ‘wb‘)
runner = HTMLTestRunner(stream=fp, title=‘測試報告‘, description=‘用例測試執行情況:‘)
runner.run(discover)
fp.close()
newReport = new_report(test_dir)
send_mail(newReport)

登錄126郵件可以查看到:

技術分享圖片

生成的測試報告通過郵件附件打開可以看到:

技術分享圖片

selenium測試報告生成、找到測試報告路徑、實現發郵件(整合)