1. 程式人生 > >以郵件附件的形式傳送測試報告

以郵件附件的形式傳送測試報告

1. 建立 EmailAnnex目錄, 在 EmailAnnex 下建立 bing.py,並編寫

from selenium import webdriver
from time import sleep
import unittest
class Bing(unittest.TestCase):
   """bing 搜尋測試"""
 def setUp(self):
   self.driver = webdriver.Firefox()
   self.driver.implicitly_wait(10)
   self.base_url = "http://cn.bing.com/
" def test_bing_search(self):   driver = self.driver   driver.get(self.base_url)    driver.find_element_by_xpath("//input[@id='sb_form_q']").send_keys("CMBC")   sleep(3)   driver.find_element_by_xpath("//input[@id='sb_form_go']").click() def tearDown(self): self.driver.quit()

2.在 EmailAnnex 建立 send_mail.py 並編寫

from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import smtplib
import unittest
import time
import os
# ===================傳送郵件=============================
def sendReport(file_path):
   """傳送帶附件的郵件"""
   sendfile = open(file_path,"rb").read() #讀取測試報告路徑
   # 如下幾行是為了以附件的形式,傳送郵件
   msg = MIMEText(sendfile,"base64","utf-8")
   msg["Content-Type"] = "application/octet-stream"
   msg["content-Disposition"] = "attachment;filename=result.html"
  #result.html 郵件附件的名字
   msgRoot = MIMEMultipart("related")
   msgRoot.attach(msg)
   msg['Subject'] = Header("自動化測試報告","utf-8")
   msg['From'] = "
[email protected]
" #傳送地址   msg['To'] = "[email protected]" #收件人地址,如果是多個的話,以分號隔開   smtp = smtplib.SMTP('smtp.126.com')   smtp.login("[email protected]","Abcd123") #郵箱的賬戶和密碼   smtp.sendmail(msg['From'],msg['To'].split(';'),msg.as_string())   smtp.quit()   print("Test Result has send out!!!") # =================查詢測試報告目錄,找到最新的測試報告檔案======== def newReport(testReport):   lists = os.listdir(testReport) #返回測試報告所在的目錄下所有資料夾   lists2 = sorted(lists) # 獲得升序排列後端測試報告列表   file_new = os.path.join(testReport,lists2[-1]) #獲得最新一條測試報告的地址   print(file_new)   return file_new # ==================執行=================================== if __name__ == '__main__':   test_dir = "D:\\python\\autotest\\EmailAnnex" #測試用例所在的目錄   test_report = "D:\\python\\autotest\\EmailAnnex\\result" #測試報告所在目錄   discover =unittest.defaultTestLoader.discover(test_dir,pattern="bing.py")   now = time.strftime("%Y-%m-%d %H%M%S") #獲取當前時間   filename = test_report + '\\' + now + 'result.html' #拼接出測試報告名   fp = open(filename,"wb")   runner = HTMLTestRunner(stream=fp,title="測試報告",description="測試用例執行情況")   runner.run(discover)   fp.close()   new_report = newReport(test_report) #獲取最新的測試報告   print(new_report)   sendReport(new_report) #傳送測試報告郵件