Python3+unitest自動化測試初探(中篇)


本篇隨筆承接:Python3+unitest自動化測試初探(上篇)python

地址:Python3+unitest自動化測試初探(上篇)git

六、生成測試報告

6.一、下載HTMLTestRunner.py

原版下載地址:http://tungwaiyip.info/software/HTMLTestRunner.html 。原版的只支持Python 2.x版本,Python 3.x版本須要作適配。
適配後的下載地址:https://github.com/Slience007/pyunitest/blob/master/untils/HTMLTestRunner.pygithub

6.二、安裝HTMLTestRunner.py

安裝方法比較簡單,將HTMLTestRunner.py放到sys.path路徑下便可。ubuntu下,我放到了以下路徑:/usr/lib/python3.7。web

6.三、生成報告

HTMLTestRunner.py提供HTMLTestRunner()類來代替unittest.TextTestRunner()執行用例,修改後的run.py的代碼以下:ubuntu

#coding:utf-8
import  unittest
#導入HTMLTestRunner
from HTMLTestRunner import  HTMLTestRunner
#從testCase包裏面導入測試類
from testCases.userLoginTest import loginTest
from testCases.userRegTest import regTest

#構造測試套
def suite():
    suite = unittest.TestSuite()
    suite.addTest(loginTest("test_loginsucess_L0"))
    suite.addTest(loginTest("test_pwdwrong_L0"))
    suite.addTest(loginTest("test_statuserr_L1"))
    suite.addTest(regTest("test_pwdlenerr_L1"))
    suite.addTest(regTest("test_regsucess_L0"))
    suite.addTest(regTest("test_regagain_L1"))
    return suite

#運行測試用例
if __name__ == '__main__':
    # runner = unittest.TextTestRunner()
    # #調用test runner的run方法執行用例
    # runner.run(suite())
    #以二進制格式打開TestReport.html用於寫入數據
    with open("./TestReport.html","wb") as f:
        runner = HTMLTestRunner(stream=f,title="Reg And Login Test Report")
        runner.run(suite())

運行run.py後,打開TestReport.html,查看生成的測試報告。
服務器

七、編寫郵件發送工具

在Project下新建包utils用來封裝一些經常使用的工具,在utils下新建Python文件emailUtil.py。定義sendEmail類。這個類主要包含3個方法:app

  1. init():初始化
  2. writeEmail():構造郵件主題,郵件正文,添加郵件附件。
  3. sendEmail():鏈接郵件服務器,認證,發送郵件。我採用的是網易郵件服務器,其地址是smtp.126.com。收件地址爲QQ郵箱。

[ 代碼以下:]emailUtil.py工具

#coding:utf-8
'''
email模塊負責構造郵件內容
smtplib模塊負責發送郵件
'''
from email.mime.text import  MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email.header import Header

class sendEmail():
    #定義全局變量郵件服務器地址,登陸用戶,受權碼
    global MAILHOST,MAILUSER,MAILPWD
    MAILHOST = "smtp.126.com"
    MAILUSER = "××××@126.com"
    MAILPWD = "×××"

    def __init__(self,subject,content,reveiver,attachPath=""):
        self.subject = subject
        self.content = content
        self.receiver = reveiver
        self.attachPath = attachPath
    #寫郵件,返回msg.as_string()
    def writeEmail(self):
        msg = MIMEMultipart()
        #郵件正文
        msg.attach(MIMEText(self.content, 'plain', 'utf8'))
        receiverName = ",".join(self.receiver)
        msg['from'] = Header(MAILUSER,'utf-8')
        #msg['to'] =  Header(",".join(self.receiver)).encode()
        msg['to'] = Header(receiverName).encode()
        #郵件主題
        msg['Subject'] = Header(self.subject,'utf-8').encode()
        #print("msg is:",msg)
        #attachPath不爲空則添加附件到郵件中
        if self.attachPath != "":
            with open(self.attachPath, 'rb') as f:
                attach1  = MIMEText(f.read(), 'base64', 'utf-8')
                attach1["Content-Type"] = 'application/octet-stream'
                #filename能夠隨便寫
                attach1["Content-Disposition"] = 'attachment; filename="Result.html"'
                msg.attach(attach1)

        return msg.as_string()

    #發送郵件
    def sendEmail(self):
        receiver = ";".join(self.receiver)
        try:
            #鏈接郵件服務器
            server = smtplib.SMTP()
            server.connect(MAILHOST,25)
            #打開debug模式能夠看到握手過程
            #server.set_debuglevel(1)
            #登陸,MAILPWD爲網易郵件的受權碼
            server.login(MAILUSER,MAILPWD)
            #發送郵件
            server.sendmail(MAILUSER,receiver,self.writeEmail())
            server.quit()
            print("Email send sucess.")
        except Exception as  e:
            print("Email send fail.")
            print(e)

在編寫郵件工具的時候,碰到了一個錯誤:smtplib.SMTPDataError: (554, b'DT:SPM。緣由多是:郵件被網易郵件服務器當成了垃圾郵件。解決辦法:郵件主題不能包含test,另外msg[from"],msg['to']要和server.sendmail(MAILUSER,receiver,self.writeEmail())中的MAILUSER和receiver保持一致。測試

八、發送郵件

在發送郵件以前,先獲取本次執行用例總數,失敗用例數,成功用例數,跳過的用例數。並計算出用例經過率。

  1. suite().countTestCases():獲取用例總數。
  2. runner.run(suite()).success_count:運行經過的用例數。
  3. runner.run(suite()).failure_count:失敗的用例數。
  4. runner.run(suite()).skipped:返回的是跳過的用例list。

接下來來修改run.py ,須要先從utils模塊導入sendEmail類,構造主題,郵件正文,指定收件人列表,指定測試報告的路徑,以後調用sendEmail方法發送郵件。修改後的run.py代碼以下:

#coding:utf-8
import  unittest
#導入HTMLTestRunner
from HTMLTestRunner import  HTMLTestRunner
#從testCase包裏面導入測試類
from testCases.userLoginTest import loginTest
from testCases.userRegTest import regTest

from utils.emailUtil import sendEmail
#構造測試套
def suite():
    suite = unittest.TestSuite()
    suite.addTest(loginTest("test_loginsucess_L0"))
    suite.addTest(loginTest("test_pwdwrong_L0"))
    suite.addTest(loginTest("test_statuserr_L1"))
    suite.addTest(regTest("test_pwdlenerr_L1"))
    suite.addTest(regTest("test_regsucess_L0"))
    suite.addTest(regTest("test_regagain_L1"))
    return suite

#運行測試用例
if __name__ == '__main__':
    # runner = unittest.TextTestRunner()
    # #調用test runner的run方法執行用例
    # runner.run(suite())
    #以二進制格式打開TestReport.html用於寫入數據
    with open("./TestReport.html","wb") as f:
        runner = HTMLTestRunner(stream=f,title="Reg And Login Test Report")
        result = runner.run(suite())
        totalNums = suite().countTestCases()
        passedNums = result.success_count
        failedNums = result.failure_count
        skippedNums = len(result.skipped)
        #經過率,保留兩位小數
        passRate = round(passedNums * 100/  totalNums)
        emailBody = "Hi,all:\n \t本次構建一共運行:{totalNums}個用例,經過{passedNums}個,失敗{failedNums}個,跳過{skippedNums}個。經過率:{passRate}%.\n \t詳細信息請查看附件。"
        content = emailBody.format(totalNums=totalNums,passedNums=passedNums,failedNums=failedNums,skippedNums=skippedNums,passRate=passRate)
        #收件人列表
        receiver = ['××××@qq.com',"×××××@126.com"]
        #測試報告的路徑
        path1 = "/home/stephen/PycharmProjects/unitTestDemo/TestReport.html"
        subject = "登陸註冊功能每日構建"
        e = sendEmail(subject,content,receiver,attachPath=path1)
        #發送郵件
        e.sendEmail()

運行run.py。登陸郵箱查看已經發送成功的郵件。

點擊這裏返回本篇目錄

相關文章
相關標籤/搜索