python+selenium+HTMLTestRunner生成测试报告并发送邮件给指定邮箱

配置邮件发送人及接收人,并执行测试用例,最后发送测试报告到指定邮箱(注意:打开测试报告目录后,最后记得关闭,不然邮箱接收到的测试报告内容将会为空)

python 复制代码
import time
import unittest
import os
import smtplib
from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart

#================发送邮件===================
def send_mail(file_new):
    mail_host = 'smtp.qq.com'
    mail_user = '123456@qq.com'
    mail_pwd = 'v*****g'  # qq生成的授权码

    receivers = ['123456@126.com']
    subject = '自动化测试报告'

    f=open(file_new,'rb')
    mail_content=f.read()

    #把报告作为邮件内容
    #msg=MIMEText(mail_content,'html','utf-8')
    #msg['Subject']=Header(subject,'utf-8')

    #把报告作为附件发送
    att = MIMEText(mail_content, 'base64', 'utf-8')
    att['Content-Type'] = 'application/octet-stream'
    att['Content-Disposition'] = 'attachment; filename=test_report.html'

    msg = MIMEMultipart('related')
    msg['Subject'] = Header(subject,'utf-8')
    msg.attach(att)

    #连接邮箱,登录,发送邮件
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host)
    # 上面两行也可以写成:smtpObj=smtplib.SMTP_SSL(mail_host,465)
    smtpObj.login(mail_user, mail_pwd)
    smtpObj.sendmail(mail_user, receivers, msg.as_string())

#=====================查找最新的测试报告===================
def new_report(test_report):
    lists = os.listdir(test_report)
    # lambda argument_list: expression表示的是一个函数
    # 比如:lambda x, y: x*y;函数输入是x和y,输出是它们的积x*y
    # lists.sort(key=lambda fn: os.path.getmtime(result_dir+'\\'+fn))
    lists.sort(key=lambda fn: os.path.getmtime(test_report + '/' + fn))
    latest_file = os.path.join(test_report, lists[-1])
    print(latest_file)
    return latest_file

def main():
    """
    一个一个加
    suite = unittest.TestSuite()
    # suite.addTest(TestAdd("test_case"))
    suite.addTest(TestAdd("test_add1"))
    suite.addTest(TestAdd("test_add2"))
    suite.addTest(TestSub("test_sub1"))
    suite.addTest(TestSub("test_sub2"))
    runner = unittest.TextTestRunner()
    runner.run(suite)

    """

    test_dir = r"./test_case/"
    test_report=r'./report/'

    """
    TestLoader是用来加载TestCase到TestSuite中的,
    其中有几个loadTestsFrom__()方法,就是从各个地方寻找TestCase,
    创建它们的实例,然后add到TestSuite中,再返回一个TestSuite实例
    """
    discover = unittest.defaultTestLoader.discover(test_dir, pattern="test_*.py")

    #给生成的测试报告设置名称
    current_time = time.strftime("%Y-%m-%d %H_%M_%S")
    file_name=test_report+current_time+"_result.html"

    fp=open(file_name,"wb")
    runner = HTMLTestRunner(stream=fp,
                            title="测试报告",
                            description="用例执行情况啦啦啦:")
    runner.run(discover)
    fp.close()
    
    latest_report=new_report(test_report)
    send_mail(latest_report)

if __name__ == '__main__':
    main()

百度为例如下:

python 复制代码
from selenium import webdriver
import unittest
import time
from HTMLTestRunner import HTMLTestRunner

class Baidu(unittest.TestCase):
    def setUp(self):
        self.driver=webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.implicitly_wait(10)
        self.base_url="http://www.baidu.com"

    def test_baidu_search(self):
        '''百度搜索测试一下注释'''
        driver=self.driver
        driver.get(self.base_url)
        driver.find_element_by_id("kw").clear()
        driver.find_element_by_id("kw").send_keys("HTMLTestRunner")
        driver.find_element_by_id("su").click()
        time.sleep(2)

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    """
    testunit=unittest.TestSuite()
    testunit.addTest(Baidu("test_baidu_search"))
    current_time=time.strftime("%Y-%m-%d %H_%M_%S")
    file_name="C:\\Users\\xxx\\Documents\\"
                +current_time+"_result.html"
    fp=open(file_name,'wb')

    runner=HTMLTestRunner(stream=fp,
                          title="百度搜索测试报告",
                          description="用例执行情况:")
    runner.run(testunit)
    fp.close()
    """
    unittest.main()
相关推荐
清水白石0082 分钟前
协程不是线程:深入理解 Python async/await 运行机制
java·linux·python
阿贵---9 分钟前
如何为开源Python项目做贡献?
jvm·数据库·python
NGC_661111 分钟前
详解Java包装类
开发语言·windows·python
暮冬-  Gentle°14 分钟前
用Python破解简单的替换密码
jvm·数据库·python
写点什么呢22 分钟前
Pytorch学习16_损失函数与反向传播
人工智能·pytorch·python·学习·pycharm
wertyuytrewm22 分钟前
使用Python控制Arduino或树莓派
jvm·数据库·python
程序媛徐师姐27 分钟前
Python基于深度学习的声音识别青少年防沉迷系统【附源码、文档说明】
python·深度学习·声音识别青少年防沉迷系统·python声音识别·python青少年防沉迷系统·python深度学习声音识别·青少年防沉迷系统
汤姆yu34 分钟前
基于python大数据的天气可视化及预测系统
大数据·开发语言·python
huohuopro34 分钟前
只能录入不能粘贴?这里解决
python