以郵件的形式傳送測試報告
阿新 • • 發佈:2018-12-11
1.建立一個Email 目錄(資料夾),在 Email 中建立 bing.py測試用例
from selenium import webdriver from time import sleep import unittest # driver.find_element_by_xpath("//input[@id='sb_form_q']").send_keys("CMBC") # driver.find_element_by_xpath("//input[@id='sb_form_go']").click() 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.在 Email 資料夾下,建立並編寫 send_mail.py 實現傳送郵件、測試報告檔案排序、執行
from HTMLTestRunner import HTMLTestRunner from email.mime.text import MIMEText from email.header import Header import smtplib import unittest import time import os # ===================傳送郵件============================= def sendReport(file_new): with open(file_new,"rb") as f: mail_body = f.read() msg = MIMEText(mail_body,"html","utf-8") #構造 MIMEText 物件作為郵件先似乎內容並附加到根容器 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\\Email" #測試用例所在的目錄 test_report = "D:\\python\\autotest\\Email\\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) #傳送測試報告郵件