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()
相关推荐
这里有鱼汤1 小时前
原来基金经理都偷偷用这个指标选股,难怪回撤小还赚钱
后端·python
广州智造1 小时前
EPLAN教程:流体工程
开发语言·人工智能·python·算法·软件工程·软件构建
Enougme1 小时前
python-使用鼠标对图片进行涂抹&自定义绘图
python·opencv
CF14年老兵1 小时前
🐍 Python黑魔法手册:让你的代码从能跑到飞起的奇技淫巧
后端·python·trae
天天进步20151 小时前
Python实战--基于Django的企业资源管理系统
开发语言·python·django
万邦科技Lafite2 小时前
利用淘宝开放API接口监控商品状态,掌握第一信息
大数据·python·电商开放平台·开放api接口·淘宝开放平台
Hy行者勇哥4 小时前
Python 与 VS Code 结合操作指南
开发语言·python
大力水手(Popeye)4 小时前
Pytorch——tensor
人工智能·pytorch·python
飞翔的佩奇8 小时前
【完整源码+数据集+部署教程】表盘指针检测系统源码和数据集:改进yolo11-CA-HSFPN
python·yolo·计算机视觉·数据集·yolo11·表盘指针检测
larance9 小时前
SQLAlchemy 的异步操作来批量保存对象列表
数据库·python