• py37 unitest+html_sendmail


    架构

     1.testcase

    #coding:utf-8
    import unittest
    import os,time
    #import HTMLTestRunner3   #py3版本
    import HTMLTestRunnerNew  #报告样式美化
    
    
    #测试用例
    class Test(unittest.TestCase):
        """测试用例1"""
        def setUp(self):
            print("start")
    
        def tearDown(self):
            time.sleep(1)
            print("end")
    
        def test01(self):
            """用例描述1:登录xxx,账户xxx"""
            print("执行测试用例1")
    
        def test02(self):
            """用例描述2:访问百度"""
            print("执行测试用例2")
    
    if __name__=="__main__":
        #1直接执行
        #unittest.main()
        #2执行测试报告
        test=unittest.TestSuite()
        test.addTest(Test("test01"))
        test.addTest(Test("test02"))
        #添加时间
        now=time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
        #报告路径
        report_path="F:\download\report\report_"+now+".html"
        fp=open(report_path,"wb")
        runner=HTMLTestRunnerNew.HTMLTestRunner(stream=fp,
                                               title="这是我的自动化测试用例",
                                               description="用例执行情况",
                                               verbosity = 2)   #verbosity = 2  执行一个用例打印一条信息
        runner.run(test)
        #关闭文件
        fp.close()

    2.执行

    #coding=utf-8
    
    import unittest
    import os
    import time
    #import HTMLTestRunner3  #老样式,发送邮件可以看到页面样式
    import HTMLTestRunnerNew  #美化样式,发送邮件看不到页面样式
    import sendemail_report as email  #导入邮件模块
    
    #测试用例
    def all_case():
        """所有用例"""
        #待执行用例的目录
        #case_dir=r"F:/download/
        case_dir=os.path.join(os.getcwd(),"case")
        testcase=unittest.TestSuite()
        discover=unittest.defaultTestLoader.discover(case_dir,pattern="test*.py",top_level_dir=None)
    
        testcase.addTests(discover)
        print(testcase)
        return testcase
    
    #查找new测试报告
    def new_report(test_report):
        lists=os.listdir(test_report)  #列出目录洗所有文件夹
        lists.sort(key=lambda  fn:os.path.getmtime(test_report+"\"+fn))  #按时间排序
        file_new=os.path.join(test_report,lists[-1])  #获取最新的
        print("最新的报告是:",file_new)
        return file_new
    
    
    if __name__=="__main__":
    
        #返回实例
        runner=unittest.TextTestRunner()
        #获取当前时间
        now=time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
        #保存报告路径
        report_path="F:\download\report\report_"+now+".html"
        fp=open(report_path,"wb")
        runner = HTMLTestRunnerNew.HTMLTestRunner(stream=fp,
                                                title="这是我的自动化测试用例",
                                                description="用例执行情况",
                                                verbosity=2)
        #run 所有用例
        runner.run(all_case())
        #关闭文件
        fp.close()
    
        # 查找最新的测试报告,并发送邮件
        report_path="F:\download\report\"
        new_report=new_report(report_path)
        email.send_mail_html(new_report)
        #email.send_mail_file(new_report)  #带报告附件

    3.sendmail

    #coding=utf-8
    """
    Created on
    @author:
    Project:py37发送html邮件及附件
    """
    
    from email.header import Header
    from email.mime.text import MIMEText
    import smtplib
    
    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.utils import parseaddr,formataddr
    from email import encoders
    
    import os
    import time
    
    #邮件配置参数
    From_addr = "xx@xx.com"
    Password = "xx"
    To_addr = "xx@xx.com" 
    Smtp_server = "smtp.exmail.qq.com"
    ###
    
    #发送邮件
    def send_mail_txt(file_new):
        """发送邮件"""
        # 读取html报告文件内容
        print('正在发送中-------------------------')
        with open(file_new, 'rb') as f:
            mail_body = f.read()
    
        def _format_addr(s):
            name, addr = parseaddr(s)
            return formataddr((Header(name, 'utf-8').encode(), addr))
    
        # 1.文本
        msg = MIMEText(mail_body, 'plain', 'utf-8')
    
        #邮件参数传递
        from_addr =From_addr
        password =Password
        to_addr = To_addr
        cc_mail = 'xx@xxx.com'  #抄送人员,#to_addr+cc_mail
        smtp_server = Smtp_server
    
        # 邮件对象
        msg['From'] = _format_addr('测试负责人 <%s>' % from_addr)
        msg['To'] = _format_addr('管理员 <%s>' % to_addr)
        msg['Subject'] = Header('测试机', 'utf-8').encode()
        msg['date'] = time.strftime("%a,%d %b %Y %H:%M:%S %z")
    
        # 发送邮件
        server = smtplib.SMTP(smtp_server, 25)
        #server.set_debuglevel(1)   #打印信息
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
        print("邮件已发出!注意查收。")
    
    #发送邮件
    def send_mail_html(file_new):
        """发送邮件"""
        # 读取html报告文件内容
        print('正在发送中-------------------------')
        with open(file_new, 'rb') as f:
            mail_body = f.read()
    
        #邮件内容封装
        def _format_addr(s):
            name, addr = parseaddr(s)
            return formataddr((Header(name, 'utf-8').encode(), addr))
    
        #邮件参数传递
        from_addr =From_addr
        password =Password
        to_addr = To_addr
        cc_mail = 'xx@xxx.com'  #抄送人员,#to_addr+cc_mail
        smtp_server = Smtp_server
    
        # html邮件正文
        msg = MIMEText(mail_body, 'html', 'utf-8')
    
        # 邮件对象
        msg['From'] = _format_addr('测试负责人 <%s>' % from_addr)
        msg['To'] = _format_addr('管理员 <%s>' % to_addr)
        msg['Subject'] = Header('测试机', 'utf-8').encode()
        msg['date'] = time.strftime("%a,%d %b %Y %H:%M:%S %z")
    
        # 发送邮件
        server = smtplib.SMTP(smtp_server, 25)
        #server.set_debuglevel(1)   #打印信息
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
        print("邮件已发出!注意查收。")
    
    # 发送邮件,带附件
    def send_mail_file(file_new):
        """发送带附件的邮件"""
        # file=带文件,其他是待图片png格式
        # 读取html报告文件内容
        print('正在发送中-------------------------')
        with open(file_new, 'rb') as f:
            mail_body = f.read()
    
        # 邮件内容封装
        def _format_addr(s):
            name, addr = parseaddr(s)
            return formataddr((Header(name, 'utf-8').encode(), addr))
    
        # 邮件参数传递
        from_addr = From_addr
        password = Password
        to_addr = To_addr
        cc_mail = 'xx@xxx.com'  # 抄送人员,#to_addr+cc_mail
        smtp_server = Smtp_server
    
        #邮件正文是MIMEText
        body = MIMEText(mail_body, 'html', 'utf-8')
        msg=MIMEMultipart()
    
        # 邮件对象
        msg['From'] = _format_addr('测试负责人 <%s>' % from_addr)
        msg['To'] = _format_addr('管理员 <%s>' % to_addr)
        msg['Subject'] = Header('测试机', 'utf-8').encode()
        msg['date'] = time.strftime("%a,%d %b %Y %H:%M:%S %z")
    
        msg.attach(body)
        #MIMEBase标识附件的对象
        att=MIMEText(mail_body,'base64','utf-8')
        att["Content-Disposition"]='attachment;filename=%s'%file_new
        msg.attach(att)
    
        # 发送邮件
        server = smtplib.SMTP(smtp_server, 25)
        # server.set_debuglevel(1)   #打印信息
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
        print("邮件已发出!注意查收。")
    
    if __name__=="__main__":
        file_new=r"F:/download/report/report.html"
        file_png=r"F:/download/test.png"
        send_mail_html(file_new)
        #发送文件
        send_mail_file(file_new)
        #发送图片
        #send_mail_file(file_png)
        #server
        file_body=r"F:/download/txt.txt"
        send_mail_txt(file_body)
  • 相关阅读:
    zabbix 添加 微信、邮件 媒介详解
    zabbix使用之常用功能使用心得
    Nginx1.8源码包编译安装
    httpd启动显示Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName'
    apache-httpd2.4编译安装
    apache-httpd2.2编译安装
    MYSQL5.7源码包编译安装
    MYSQL常见安装错误集:[ERROR] --initialize specified but the data directory has files in it. Abort
    MYSQL启用数据库错误:ERROR 2002 (HY000)
    编译mysql时CMake Error at cmake/readline.cmake:85 (MESSAGE)
  • 原文地址:https://www.cnblogs.com/lisa2016/p/12561174.html
Copyright © 2020-2023  润新知