zoukankan      html  css  js  c++  java
  • Appium+python 自动发送邮件(2)

    移动端执行完测试case之后,通过邮件自动发送测试报告。大体流程如下:

    1、通过unittest框架的discover()发现所有测试用例

    2、使用HTMLTestRunner的run()方法运行测试用例,生成HTML测试报告

    3、寻找测试报告目录下的最新测试报告,返回最新测试报告的路径

    4、将最新测试报告路径传给send_mail()函数,发送带HTML格式的邮件

    # coding:utf-8
    import unittest
    import time
    import smtplib
    import os
    from email.mime.text import MIMEText
    from email.header import Header
    from email.mime.multipart import MIMEMultipart
    from HTMLTestRunner import HTMLTestRunner
    
    testcase_dir = 'E:\python_work\appium\test_app\testcase'   # 测试用例路径
    testreport_dir = 'E:\python_work\appium\test_app\report'    # 测试报告路径
    
    # 发送邮件
    def sendmail(sendfile):
        smtpserver = 'smtp.qq.com'
        user = 'username@qq.com '
        password = 'password'
        sender = 'username@qq.com'
        receiver = 'receiver@163.com'
        subject = '自动化测试报告'
    
        f = open(sendfile, 'rb')
        mailbody = f.read()  # 读取测试报告作为邮件正文
        f.close()
    
        # 编写HTML类型的邮件正文
        msg = MIMEText(mailbody, 'html', 'utf-8')
        msg["Subject"] = Header(subject, 'utf-8')
    
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)
        smtp.login(user, password)
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
        print('Email has send out')
    
    
    # 查找目录下最新生成的测试报告,返回最新报告的详细路径
    def find_Report(reportpath):
        lists = os.listdir(reportpath)
        lists.sort(key=lambda fn: os.path.getmtime(reportpath + "\" + fn))
        newfile = os.path.join(reportpath, lists[-1])
        print(newfile)
        return newfile
    
    
    # 运行case,并生成测试报告
    def run_case():
        discover = unittest.defaultTestLoader.discover(testcase_dir, pattern='test*.py')
        now_time = time.strftime("%Y%m%d_%H-%M-%S")
        fp = open(testreport_dir + '\' + now_time + '_TestResult.html', 'wb')
        runner = HTMLTestRunner(
            stream=fp,
            title='测试报告',
            description='测试用例执行情况',
        )
        runner.run(discover)  # 运行case,生成HTML测试报告
        fp.close()
    
    
    if __name__ == '__main__':
        run_case()
        new_report = find_Report(testreport_dir)
        sendmail(new_report)

    收到的邮件如下:

  • 相关阅读:
    CareerCup Questions List 职业杯题目列表
    [CareerCup] Guards in a museum 博物馆的警卫
    [LeetCode] 7. Reverse Integer 翻转整数
    Python笔记11------一个K-means聚类的小例子
    python笔记10-----便捷网络数据NLTK语料库
    Python笔记9-----不等长列表转化成DataFrame
    Python笔记8----DataFrame(二维)
    Python笔记7----Pandas中变长字典Series
    Python笔记6----数组
    Python笔记5----集合set
  • 原文地址:https://www.cnblogs.com/fancy0158/p/10056418.html
Copyright © 2011-2022 走看看