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()
相关推荐
PythonFun2 小时前
Python批量下载PPT模块并实现自动解压
开发语言·python·powerpoint
炼丹师小米3 小时前
Ubuntu24.04.1系统下VideoMamba环境配置
python·环境配置·videomamba
GFCGUO3 小时前
ubuntu18.04运行OpenPCDet出现的问题
linux·python·学习·ubuntu·conda·pip
985小水博一枚呀4 小时前
【深度学习基础模型】神经图灵机(Neural Turing Machines, NTM)详细理解并附实现代码。
人工智能·python·rnn·深度学习·lstm·ntm
萧鼎6 小时前
Python调试技巧:高效定位与修复问题
服务器·开发语言·python
IFTICing6 小时前
【文献阅读】Attention Bottlenecks for Multimodal Fusion
人工智能·pytorch·python·神经网络·学习·模态融合
大神薯条老师6 小时前
Python从入门到高手4.3节-掌握跳转控制语句
后端·爬虫·python·深度学习·机器学习·数据分析
程序员爱德华6 小时前
Python环境安装教程
python
huanxiangcoco6 小时前
152. 乘积最大子数组
python·leetcode
萧鼎7 小时前
Python常见问题解答:从基础到进阶
开发语言·python·ajax