python+selenium+unittest測試框架3-項目構建和發送郵件


 項目構建和發送郵件

 

一、項目構建

1、建立項目chen

打開pycharm左上角File>New Project,在Location輸入testing項目所在文件夾D:\chen,創建后選擇Opin in current window。

2、創建子文件夾

PS:創建文件夾,一定要選Python Package的方式創建。

3、創建測試腳本

 

4、創建runalltest.py

 PS:在runalltest.py這個腳本里面寫主函數,控制執行所有的用例。

5、下載生成測試報告的源碼

import HTMLTestRunner
import unittest
import os
#測試用例存放路徑
casepath = os.path.join(os.getcwd(),"case")
#測試報告存放路徑
reportpath = os.path.join(os.getcwd(),"report")
def allcase():
    '''加載測試用例'''
    discover = unittest.defaultTestLoader.discover(casepath,
                                                   pattern="case*.py",
                                                   top_level_dir=None)
    return discover
def runcase():
    '''執行測試用例,生成測試報告'''
    htmlreportpath = os.path.join(reportpath,"result.html")
    fp = open(htmlreportpath,"wb")
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           title=u"自動化測試報告",
                                           description=u"測試用例執行情況")
    # 調用allcase函數返回值
    runner.run(allcase())
    fp.close()

if __name__ == "__main__":
    runcase()    

 

二、發送郵件

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_mail(sender, psw, receiver, smtpserver,reportfile, port=465):
    '''發送最新的測試報告內容'''
    #打開測試報告
    with open(reportfile, "rb") as f:
        mail_body = f.read()
    # 定義郵件內容
    msg = MIMEMultipart()
    body = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    msg['Subject'] = u"自動化測試報告"
    msg["from"] = sender
    msg["to"] = receiver
    msg.attach(body)
    # 添加附件
    att = MIMEText(open(reportfile, "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename= "report.html"'
    msg.attach(att)
    try:
        smtp = smtplib.SMTP_SSL(smtpserver, port)
    except:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver,port)
    # 用戶名密碼
    smtp.login(sender, psw)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()

if __name__ == '__main__':
    reportfile = u"F:\\python36\\test\\report\\result.html"#測試報告路徑
    smtpserver = "smtp.qq.com"  #  郵箱服務器
    sender = "139271007@qq.com" # 自己的賬號
    psw = "password" #自己的密碼
    receiver = "386421542@qq.com" #對方的賬號
    send_mail(sender, psw, receiver, smtpserver,reportfile)

 


免責聲明!

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



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