Python+unittest發送測試報告


案例將E:\Python_script\unittest\Test_Baidu生成的最新測試報告發送到指定郵箱。

我們將之前的unittest的報告生成和Python自動發送郵件結合在一起,就可以完成自動發送最新報告到指定郵箱的操作。

代碼示例:

runtest_email.py

import unittest
from BSTestRunner import BSTestRunner
import time
import smtplib                         # 發送郵件模塊
from email.mime.text import MIMEText   # 定義郵件內容
from email.header import Header        # 定義郵件標題
import os


def send_mail(latest_report):
    f = open(latest_report, 'rb')
    mail_content = f.read()
    f.close()
    smtpserver = 'smtp.163.com'
    # 發送郵箱用戶名密碼
    user = 'nancyrm2018@163.com'
    password = '輸入自己的密碼'
    # 發送和接收郵箱
    sender = 'nancyrm2018@163.com'
    receivers = ['nancyrm2018@126.com', '88886666@qq.com']
    # 發送郵件主題和內容
    subject = "Web Selenium 自動化測試報告"
    # HTML郵件正文
    msg = MIMEText(mail_content, 'html', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = sender
    msg['To'] = ','.join(receivers)

    smtp = smtplib.SMTP_SSL(smtpserver, 465)
    # HELO 向服務器標識用戶身份
    smtp.helo(smtpserver)
    # 服務器返回結果確認
    smtp.ehlo(smtpserver)
    # 登錄郵箱服務器用戶名和密碼
    smtp.login(user, password)

    print("Send email start...")
    smtp.sendmail(sender, receivers, msg.as_string())
    smtp.quit()
    print("Email send end!")


def latest_report(report_dir):
    lists = os.listdir(report_dir)
    print(lists)
    # 按時間順序對該目錄文件夾下面的文件進行排序
    lists.sort(key=lambda fn: os.path.getatime(report_dir + "\\" + fn))
    print("The latest report is:" + lists[-1])

    file = os.path.join(report_dir, lists[-1])
    print(file)
    return file

if __name__ == '__main__':
    report_dir = './test_report'
    test_dir = './test_case'

    discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')
    now = time.strftime("%Y-%m-%d %H_%M_%S")
    report_name = report_dir + '/' + now + 'result.html'
    with open(report_name, "wb") as f:
        runner = BSTestRunner(stream=f, title='測試報告', description='用例執行情況:')
        runner.run(discover)
        f.close()

    # h獲取最新測試報告
    latest_report = latest_report(report_dir)
    # 發送郵件報告
    send_mail(latest_report)

代碼分析:
可以將代碼分為3個部分來理解:

  1. 通過unittest框架的discovery()找到匹配測試用例,由HTMLTestRunner 的run()方法執行測試用例並生成最新的測試報告
  2. 調用new_report()函數找到測試報告目錄(test_report)下最新生成的測試報告,返回測試報告的路徑
  3. 將得到的最新測試報告的完整路徑傳給send_mail()函數,實現發郵件功能

代碼實現:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM