python+robot framework實現測報告定制化和郵件發送


前面已經介紹了python+robot framework自動化框架和基本原理的實現,詳情請看

python+robot framework接口自動化測試

本章主要講解報告已經產生那如何以自動化的方式當報告執行結束后以郵件的方式發送通知呢???

其中有3點:第一:這個報告是以什么的格式發送達到簡潔概括的目的?第二:定制化的報告格式怎么帶上附件以郵件的方式發出?

第三:RF如何輸出就實現結構上的自動化框架?

解決此兩點再加上前篇講的基本原理和關鍵字封裝,那么就可以驕傲的說完成了接口自動化框架的實現~~~(當然還未集成到jenkins~~數據未入DB等周邊操作)

首先解決第一點:核心腳本如下~(注:此腳本網上也有例子,我們只需要根據自己的實際需求稍作調整即可~)

__author__ = 'niuzhigang'
# -*- coding: utf-8 -*-
#encoding=utf-8


def createReportContent(detailContent,totalContent,byTagContent,bySuiteContent,percentage,reportSavePath):
        result=detailContent.split("\n")
        sDetail=''
        for index in range(len(result)):
            if(index!=len(result)):
                sDetail=sDetail+result[index]+"<br>"
            else:
                sDetail=sDetail+result[index]
        detailTable="<font size='5' style='font-weight:bold'>Summary Information</font><br><table width='1000' border='1' cellpadding='1' cellspacing='1'><tr><td width='100%'>"+'Run Pass Rate: '+percentage+"</td></tr><tr><td width='100%'>"+sDetail+"</td></tr></table>"

        totalTable="<table width='1000' border='1' cellpadding='1' cellspacing='1'><tr bgcolor='#DCDCDC'><td width='40%''>Total Statistics</td><td>Total</td><td>Pass</td><td>Fail</td><td>Elapsed</td><td>Pass/Fail</td></tr>"
        result=totalContent.split("\n")
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        for index in range(len(result)):
            if((index+1)%2==1):
                totalTable=totalTable+"<tr><td>"+result[index]+"</td>"
            else:
                s=result[index]
                items=s.split(" ")
                for item in items:
                    totalTable=totalTable+"<td>"+item+"</td>"
                sColor="";
                if(items[2]=="0"):
                    sColor="green"
                else:
                    sColor="red"
                totalTable=totalTable+"<td><center><font style='font-weight:bold;color:green'>"+items[1]+"/</font><font style='font-weight:bold;color:"+sColor+"'>"+items[2]+"</font></center></td></tr>"
        totalTable=totalTable+"</table>"
        byTagTable="<table width='1000' border='1' cellpadding='1' cellspacing='1'><tr bgcolor='#DCDCDC'><td width='40%'>Statistics by Tag</td><td>Total</td><td>Pass</td><td>Fail</td><td>Elapsed</td><td>Pass/Fail</td></tr>"
        result=byTagContent.split("\n")
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        for index in range(len(result)):
            if((index+1)%2==1):
                byTagTable=byTagTable+"<tr><td>"+result[index]+"</td>"
            else:
                s=result[index]
                items=s.split(" ")
                for item in items:
                    byTagTable=byTagTable+"<td>"+item+"</td>"
                sColor="";
                if(items[2]=="0"):
                    sColor="green"
                else:
                    sColor="red"
                byTagTable=byTagTable+"<td><center><font style='font-weight:bold;color:green'>"+items[1]+"/</font><font style='font-weight:bold;color:"+sColor+"'>"+items[2]+"</font></center></td></tr>"
        byTagTable=byTagTable+"</table>"   
        bySuiteTable="<table width='1000' border='1' cellpadding='1' cellspacing='1'><tr bgcolor='#DCDCDC'><td width='40%'>Statistics by Suite</td><td>Total</td><td>Pass</td><td>Fail</td><td>Elapsed</td><td>Pass/Fail</td></tr>"
        result=bySuiteContent.split("\n")
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        del result[0]
        for index in range(len(result)):
            if((index+1)%2==1):
                bySuiteTable=bySuiteTable+"<tr><td>"+result[index]+"</td>"
            else:
                s=result[index]
                items=s.split(" ")
                for item in items:
                    bySuiteTable=bySuiteTable+"<td>"+item+"</td>"
                sColor="";
                if(items[2]=="0"):
                    sColor="green"
                else:
                    sColor="red"
                bySuiteTable=bySuiteTable+"<td><center><font style='font-weight:bold;color:green'>"+items[1]+"/</font><font style='font-weight:bold;color:"+sColor+"'>"+items[2]+"</font></center></td></tr>"
        bySuiteTable=bySuiteTable+"</table>"
        html="<html> <head><title></title><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /></head><body>"+detailTable+"<font size='5' style='font-weight:bold;'>Test Statistics</font>"+totalTable+"<br>"+byTagTable+"<br>"+bySuiteTable+"<br><font size='5' style='font-weight:bold;'>更多詳情請查看郵件附件【report.html】和【log.html】!!!</font></body></html>"
        print html
        read = open(reportSavePath,'w')  
        read.write(html)  
        read.close  

到此,創建報告的模板腳本已經完成了~ 是不是也沒什么難度~那么接下來我們繼續發送郵件了

其次就是第二點:相對創建報告,發送郵件的腳本更是easy~主要借助BeautifulSoup庫讀取html文件~

具體py腳本如下

__author__ = 'niuzhigang'
# -*- coding: utf-8 -*-
#encoding=utf-8


import time
import smtplib
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import sys
from bs4 import BeautifulSoup
import os.path 
reload(sys)
sys.setdefaultencoding('utf-8')

#如果是list請以逗號分隔
mailto_list=['niuzhigang@XXX.com']
mail_host="smtp.XXX.com"
mail_user="niuzhigang"
mail_pass="nisuiyi"
mail_postfix="XXX.com"

def send_mail(open_file, attfile1, attfile2):
    soup = BeautifulSoup(open(open_file,'rb+'),"html.parser")
    body = soup.find("body")
    runPassRate =  body.find("td").string
    PassRate = runPassRate.split(" ")[3]
    today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
    detailTime = time.strftime('%H:%M:%S',time.localtime(time.time()))
    todaytime = today + ' 00:00:00'
    selectres = todaytime
    send_header = "[跟團-跟團頻道][線上環境][主流程自動化用例批跑報告]- ".encode("utf-8") + today +" "+detailTime + " " +PassRate
    me="[跟團-跟團頻道][線上環境][主流程自動化用例批跑報告]".encode("utf-8")+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEMultipart()
    msg['Subject'] = send_header
    msg['From'] = me
    msg['To'] = ";".join(mailto_list)

    #fp = open(r'D:\pythonrf\sample\testReport\log.html',"r")
    fp = open(open_file,"r")
    content = fp.read()
    msg.attach(MIMEText(content, _subtype='html', _charset='utf-8'))
    fp.close()

    #log report
    #att1 = MIMEText(open(r'D:\pythonrf\sample\testReport\log.html', 'rb').read(), 'base64', 'gb2312')
    att1 = MIMEText(open(attfile1, 'rb').read(), 'base64', 'gb2312')
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = 'attachment; filename="report.html"'
    msg.attach(att1)

    #result report
    #att2 = MIMEText(open(r'D:\pythonrf\sample\testReport\report.html', 'rb').read(), 'base64', 'gb2312')
    att2 = MIMEText(open(attfile2, 'rb').read(), 'base64', 'gb2312')
    att2["Content-Type"] = 'application/octet-stream'
    att2["Content-Disposition"] = 'attachment; filename="log.html"'
    msg.attach(att2)


    try:
        server = smtplib.SMTP()
        server.connect(mail_host)
        server.login(mail_user,mail_pass)
        server.sendmail(me, mailto_list, msg.as_string())
        server.close()
        return True
    except Exception, e:
        print str(e)
        return False

if __name__ == '__main__':  
    if send_mail(r'D:/pythonrf/sample/testReport/reportlog.html', r'D:/pythonrf/sample/testReport/reportlog.html', r'D:\pythonrf/sample/testReport/report.html'):
        print u"發送成功"
    else:  
        print u"發送失敗"
    '''today = time.strftime('%Y-%m-%d',time.localtime(time.time()))
    detailTime = time.strftime('%H:%M:%S',time.localtime(time.time()))
    print today,detailTime
    soup = BeautifulSoup(open("D:/pythonrf/sample/testReport/reportlog.html",'rb+'),"html.parser")
    print soup
    body = soup.find("body")
    runPassRate =  body.find("td").string
    print runPassRate.split(" ")[3]'''

那么問題來了,前面只是關鍵字的封裝,前面只是關鍵字的封裝,前面只是關鍵字的封裝(重要的申請說三遍~)!!!

怎么集成到rf上呢?實現接口執行結束后自動化創建報告並發送呢?

前章也介紹了如何導入自定義的py庫,借用定義的函數來完成這個任務~

最后就是第三:在RF上創建case(創建報告和發送郵件最為一條最后執行的case)

步驟1:就是在測試套上導入依賴的library

Selenium2Library庫很重要 ,主要用到Get Text 關鍵字獲取html標簽內里面的文本內容,用來下次請求創建報告入參值。

也就是createReportContent庫中的createReportContent方法的入參!

def createReportContent(detailContent,totalContent,byTagContent,bySuiteContent,percentage,reportSavePath):

 

--->createReportContent.py和sendmail.py庫是通過Selenium2Library獲取入參value后,用這2庫完成創建報告和發送郵件

 步驟2:RF輸出如下:

 

 好了,到此case輸出結束(發送報告也作為了一個單獨的case輸出~)

中間過程會生成一個名稱為reportlog.html文件

如下:

 

發送郵件的格式如下:

 到此已經結束,后期在慢慢輸出一些個性化的東西,如集成Jenkins、集成微信等等~ 

歡迎上神討論!!!


免責聲明!

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



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