• 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("
    ")
            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("
    ")
            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("
    ")
            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("
    ")
            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:pythonrfsample	estReportlog.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:pythonrfsample	estReportlog.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:pythonrfsample	estReport
    eport.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、集成微信等等~ 

    欢迎上神讨论!!!

  • 相关阅读:
    新四军的7个师,以及粟裕的山头背景
    基于easyui的webform扩展
    Mac入门(一)基本用法
    HtmlAgilityPack实战代码
    摄像头、麦克风、扬声器测试程序
    依赖注入(IOC)
    类型
    C#私房菜[二][提供编程效率的技巧]
    Fluent Nhibernate code frist简单配置
    Ubuntu环境搭建系列—JavaEE篇
  • 原文地址:https://www.cnblogs.com/nzg-noway/p/6673276.html
Copyright © 2020-2023  润新知