• selenium+python自动化89-用例不通过的时候发送邮件


    前言

    实现需求:当测试用例全部通过的时候,不发邮件,当用例出现Error或Failure的时候发送邮件

    解决思路:生成html测试报告后,用bs4解析html页面,写个函数判断页面上是都有不通过的记录

    html报告

    1.查看html报告,主要看Status这一行是否会出现Failure 或 Error 的记录

    bs4解析html

    1.bs4模块在我的博客上上海-悠悠之前有过介绍,就不重复写了,先定位html页面元素,先通过它的class属性:attribute定位到这三行记录

    2.取出最后一行,然后读出文本内容。

    # coding:utf-8
    from bs4 import BeautifulSoup
    
    # 打开html文件,读取报告内容
    with open("result.html", "r", encoding="utf-8") as fp: 
    f = fp.read() # 读报告 # 解析html,查找class属性attribute soup = BeautifulSoup(f, "html.parser") status = soup.find_all(class_="attribute") # 打印查找内容 print(status) print("qq交流群:226296743") result = status[2].contents[-1] # 获取报告结果 print(result)

    运行结果:

    [<p class="attribute"><strong>Start Time:</strong> 2018-01-18 16:35:49</p>, <p class="attribute"><strong>Duration:</strong> 0:00:00</p>, <p class="attribute"><strong>Status:</strong> Pass 2 Failure 1 Error 1</p>]
    qq交流群:226296743
     Pass 2 Failure 1 Error 1

    写个判断函数

    1.对结果判断,写个判断是否有失败用例的函数

     # coding:utf-8
    from bs4 import BeautifulSoup
    
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    
    def is_result_pass():
        try:
            with open("result.html", "r") as fp:
                f = fp.read()  # 读报告
            soup = BeautifulSoup(f, "html.parser")
            status = soup.find_all(class_="attribute")
            result = status[2].contents[-1] # 获取报告结果
            if "Failure" in result or "Error" in result:
                print("测试过程有不通过用例:%s"%result)
                return False
            else:
                return True
        except Exception as msg:
            print("判断过程出现异常:%s"%str(msg))
            return False
    
    if __name__ == "__main__":
        print("qq交流群:226296743")
        res = is_result_pass()
        print(res)

    运行结果:

    测试过程有不通过用例: Pass 2 Failure 1 Error 1
    False

    2.在最后发邮件之前加个判断

     if not is_result_pass():
            # 判断html报告是否有报错
            
            # 执行发送邮件函数,自己写一个发邮件函数
            # send_mail(sender, psw, receiver, smtp_server, report_file)
            
        else:
            print("测试用例全部通过,不发送邮件")

    自己写的整个封装:
    # coding:utf-8
    import unittest,time,os
    from email.mime.text import MIMEText
    import smtplib
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from bs4 import BeautifulSoup
    from email.utils import formataddr
    from unittest import defaultTestLoader
    import test
    from baogao import HTMLTestRunner
    from moxiu_lianxi import *
    case_dir = r"C:moxiulianximsq01 est_case"
    def all_case():
    discover = unittest.defaultTestLoader.discover(case_dir,pattern="test_00*.py",top_level_dir=None)
    suite = unittest.TestSuite()
    suite.addTest(discover)
    return suite
    def send_email(report_path,receiver):
    a = open(report_path, "rb")
    mail_body = a.read()
    msg = MIMEMultipart()
    body = MIMEText(mail_body, _subtype='html', _charset='utf-8')
    msg['Subject'] = u"我自己发送的接口测试报告"
    msg["from"] = "mashuqi@wetalktv.cn"
    msg["to"] = ";".join(receiver)
    msg.attach(body)
    att = MIMEText(mail_body,'base64', _charset='utf-8')
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename="zhuti_jiekou_baogao.html"'
    msg.attach(att)
    smtp = smtplib.SMTP_SSL("smtp-n.global-mail.cn", 465) #全球网邮箱服务器
    smtp.login("mashuqi@wetalktv.cn", "Abcd1234")
    smtp.sendmail("mashuqi@wetalktv.cn", receiver, msg.as_string())
    smtp.quit()
    def Error_sendEmail(report_path,receiver):
    try:
    # 打开html文件,读取报告内容
    with open(report_path, "r", encoding="utf-8") as fp: #注意:python3这里一定要加encoding="utf-8";否则会包gbk错误;
                f = fp.read()  # 读报告
    soup = BeautifulSoup(f, "html.parser")
    status = soup.find_all(class_="attribute")
    resul = status[2] # 获取报告结果
    result = str(resul)
    if "Failure" in result or "Error" in result:
    print("测试过程有不通过用例:%s" % result)
    # receiver = ["mashuqi@wetalktv.cn"]
    send_email(report_path,receiver)
    return False
    else:
    return True
    except:
    print("判断过程出现异常")
    return False
    if __name__=="__main__":
    runner = unittest.TextTestRunner()
    # # now = time.strftime("%Y-%m-%d %H_%M_%S", time.localtime())
    # # report_path = r"D:moxiulianximsq01aogao esult" + now + ".html"
    report_path = r"C:moxiulianximsq01aogao esult.html"
    fp = open(report_path,"wb")
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title=u'自动化测试生成测试报告-练习',description=u"测试结果:通过")
    runner.run(all_case())
    fp.close()
    receiver = ["mashuqi@wetalktv.cn"]
    # send_email(report_path,receiver)
    Error_sendEmail(report_path,receiver)
     
  • 相关阅读:
    combo,raido
    块级作用域问题ES5 & ES6
    基本类型和引用类型_深拷贝和浅拷贝
    由数组扁平化切入generator函数
    Promise基本用法
    原生ajax请求之前端
    ExtJS组件window
    ORACLE(+) 号的用法,及与逗号运算符的差别
    centos7发布json中文显示乱码
    centos7 svn在repository在的情况下重装恢复
  • 原文地址:https://www.cnblogs.com/mashuqi/p/10417255.html
Copyright © 2020-2023  润新知