1. 程式人生 > >Python unittest框架全域性控制檔案run_all_test

Python unittest框架全域性控制檔案run_all_test

# user/bin/python3
# coding:utf-8


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


# 查詢測試報告目錄,找到最新生成的測試報告檔案
def new_report(test_report):
    lists = os.listdir(test_report)
    lists.sort(key=lambda fn: os.path.getatime(test_report + "\\" + fn))
    file_new = os.path.join(test_report,lists[-1])
    print(file_new)
    return file_new
def send_mail(file_new):
    f = open(file_new,'rb')
    mail_body = f.read()
    f.close()
    stmpserver = 'smtp.qq.com'
    user = "
[email protected]
" password = " " # 這裡填郵箱的授權碼 subject = '自動化測試報告' # 構造MIMEMultipart物件做為根容器 msgRoot = MIMEMultipart() text_msg = MIMEText(mail_body, 'html', 'utf-8') msgRoot.attach(text_msg) file_msg = MIMEText(mail_body, 'base64', 'utf-8') file_msg["Content-Type"] = 'application/octet-stream' # 設定附件頭 basename = os.path.basename(file_new) print(basename) file_msg["Content-Disposition"] = 'attachment; filename=''' + basename + '' msgRoot.attach(file_msg) # 設定根容器屬性 msgRoot['Subject'] = Header(subject, 'utf-8') msgRoot['From'] = '
[email protected]
' msgRoot['To'] = '[email protected]' # 連線傳送郵件 smtp = smtplib.SMTP() smtp.connect(stmpserver) smtp.login(user, password) smtp.sendmail(msgRoot['From'], msgRoot['To'], msgRoot.as_string()) smtp.quit() print('測試報告附件郵件已傳送!') if __name__ == "__main__": test_dir = "C:/Users/foresee/.PyCharm2017.3/Test_UI/testcase" test_report = "C:/Users/foresee/.PyCharm2017.3/Test_UI/report" discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py') now = time.strftime("%Y-%m-%d %H-%M-%S") filename = 'C:/Users/foresee/.PyCharm2017.3/Test_UI/report/' + now + 'result.html' fp = open(filename, 'wb') runner = unittest.TextTestRunner(verbosity=2) runner = HTMLTestRunner(stream=fp, title='用例測試報告', description='用例執行情況:') runner.run(discover) fp.close() new_report = new_report(test_report) send_mail(new_report)