Appium+python 自動發送郵件(2)
阿新 • • 發佈:2018-12-03
con rtp 正文 郵件 des 圖片 turn () dma
移動端執行完測試case之後,通過郵件自動發送測試報告。大體流程如下:
1、通過unittest框架的discover()發現所有測試用例
2、使用HTMLTestRunner的run()方法運行測試用例,生成HTML測試報告
3、尋找測試報告目錄下的最新測試報告,返回最新測試報告的路徑
4、將最新測試報告路徑傳給send_mail()函數,發送帶HTML格式的郵件
# coding:utf-8 import unittest import time import smtplib import os from email.mime.text import MIMEText from email.header importHeader from email.mime.multipart import MIMEMultipart from HTMLTestRunner import HTMLTestRunner testcase_dir = ‘E:\\python_work\\appium\\test_app\\testcase‘ # 測試用例路徑 testreport_dir = ‘E:\\python_work\\appium\\test_app\\report‘ # 測試報告路徑 # 發送郵件 def sendmail(sendfile): smtpserver = ‘smtp.qq.com‘ user = ‘[email protected] ‘ password = ‘password‘ sender = ‘[email protected]‘ receiver = ‘[email protected]‘ subject = ‘自動化測試報告‘ f = open(sendfile, ‘rb‘) mailbody = f.read() # 讀取測試報告作為郵件正文 f.close() # 編寫HTML類型的郵件正文 msg = MIMEText(mailbody, ‘html‘, ‘utf-8‘) msg["Subject"] = Header(subject, ‘utf-8‘) smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print(‘Email has send out‘) # 查找目錄下最新生成的測試報告,返回最新報告的詳細路徑 def find_Report(reportpath): lists = os.listdir(reportpath) lists.sort(key=lambda fn: os.path.getmtime(reportpath + "\\" + fn)) newfile = os.path.join(reportpath, lists[-1]) print(newfile) return newfile # 運行case,並生成測試報告 def run_case(): discover = unittest.defaultTestLoader.discover(testcase_dir, pattern=‘test*.py‘) now_time = time.strftime("%Y%m%d_%H-%M-%S") fp = open(testreport_dir + ‘\\‘ + now_time + ‘_TestResult.html‘, ‘wb‘) runner = HTMLTestRunner( stream=fp, title=‘測試報告‘, description=‘測試用例執行情況‘, ) runner.run(discover) # 運行case,生成HTML測試報告 fp.close() if __name__ == ‘__main__‘: run_case() new_report = find_Report(testreport_dir) sendmail(new_report)
收到的郵件如下:
Appium+python 自動發送郵件(2)