python自动发送测试报告邮件功能的实现


Posted in Python onJanuary 22, 2019

自动化发邮件功能也是自动化测试项目中的重要需求之一。在自动化脚本运行完成之后,邮箱就可以收到最新的测试报告结果,把这种主动的且不及时的查看变成被动且及时的查收,就方便多了。

首先我们需要一份漂亮且通俗易懂的测试报告来展示自动化测试成果, HTMLTestRunnerpython 标准库 unittest 单元测试框架的一个扩展,它生成易于使用的HTML测试报告。

下载地址: http://tungwaiyip.info/software/HTMLTestRunner.html

这个扩展非常简单,只有一个.py文件,选中后直接下载到本地即可。安装方法也很简单,将其复制到python的安装目录下即可。

windows:将下载的文件保存在../Python35/Lib目录下

Linux(ubuntu):以root身份将HTMLTestRunner.py复制到/usr/local/Python3.7/dist-packages/ 目录下

修改HTMLTestRunner

#第 94 行
import StringIo
修改为:
import io

#第 539 行
self.outputBuffer=StringIO.StringIO()
修改为:
self.outputBuffer=io.StringIO()

#第 631 行
print >>sys.stderr, 'nTime Elapsed: %s' % (self.stopTime-self.startTime)
修改为:
print(sys.stderr, 'nTime Elapsed: %s' % (self.stopTime-self.startTime))

#第 642 行
if not rmap.has_key(cls):
修改为:
if not cls in rmap:

#第 766 行
uo=o.decode('latin-1')
修改为:
uo=o

#第 772 行
ue=e.decode('latin-1')
修改为:
ue=e

生成HTML测试报告

from selenium import webdriver
import unittest
from HTMLTestRunner import HTMLTestRunner
class Baidu(unittest.TestCase):
 def setUp(self):
  self.driver=webdriver.Firefox()
  self.driver.implicitly_wait(10)
  self.base_url="https://www.baidu.com"
 
 def test_baidu_search(self):
  driver=self.driver
  driver.get(self.base_url)
  driver.find_element_by_id("kw").send_keys("HTMLTestRunner")
  driver.find_element_by_id("su").click()
 def tearDown(self):
  self.driver.quit()
if __name__=="__main__":
 testunit=unittest.TestSuite()
 testunit.addTest(Baidu("test_baidu_search"))
 #定义报告存放路径
 fp=open('./result.html','wb')
 #定义测试报告
 runner=HTMLTestRunner(
  stream=fp,
  title='百度搜索测试报告',
  description='用例执行情况:'
 )
 runner.run(testunit) # 运行测试用例
 fp.close() # 关闭报告文件

代码分析

首先,将HTMLTestRunner模块用import导入进来

其次,通过open()方法以二进制写模式打开当前目录下的result.html,如果没有,则自动创建该文件。

接着,调用HTMLTestRunner模块下的HTMLTestRunner类。stream指定测试报告文件,title用于定义测试报告的标题,description用于定义测试报告的副标题。

最后,通过HTMLTestRunner的run()方法来运行测试套件中所组装的测试用例。最后通过close()关闭测试报告文件。

python自动发送测试报告邮件功能的实现

自动发邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header
#发送邮箱服务器
smtpserver='smtp.**.com'
#发送邮箱用户/密码
user='********@**.com'
password='********'(授权码)
#发送邮箱
sender='********@**.com'
#接收邮箱
receiver='*******@**.com'
#发送邮件主题
subject='python email'
#编写html类型的邮件正文
msg=MIMEText('<HTML><H1>你好</H1></HTML>','html','utf8')
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()

发送带附件的邮件

import smtplib
from email.mime.text import MIMEText
from email.header import Header
#发送邮箱服务器
smtpserver='smtp.**.com'
#发送邮箱用户/密码
user='********@**.com'
password='********'(授权码)
#发送邮箱
sender='********@**.com'
#接收邮箱
receiver='*******@**.com'
#发送邮件主题
subject='python email'
#发送的附件
sendfile=open('D:\\test.txt','rb').read()
att=MIMEText(sendfile,'base64','utf-8')
att["Content-Type"]='application/octet-stram'
att["content-Disposition"]='attachment;filename="test.txt"'
msgRoot=MIMEMultipart('related')
msgRoot['Subject']=subject
msgRoot.attach(att)
#连接发送邮件
smtp=smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()

整合自动发邮件功能

解决了前面的问题后,现在就可以将自动发邮件功能集成到自动化测试项目中了。

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.text import MIMEText
import unittest
import time
import os
#定义发送邮件
def send_mail(file_new):
 f=open(file_new,'rb')
 mail_body=f.read()
 f.close()
 msg=MIMEText(mail_body,'html','utf-8')
 msg['Subject']=Header("自动化测试报告",'utf-8')
 smtp=smtplib.SMTP()
 smtp.connect("******.com")
 smtp.login(****@**.com,*******)
 smtp.sendmail(****@**.com,****@**.com,msg.as_string())
 smtp.quit()
 print('email has send out !')
#查找测试报告目录,找到最新生成的测试报告文件
def new_report(testreport):
 lists=os.listdir(testreport)
 lists.sort(key=lambda fn: os.path.getmtime(testreport+"\\"+fn))
 file_new=os.path.join(testreport,lists[-1])
 print(file_new)
 return file_now
if __name__=='__main__':
 test_dir='D:\\testpro\\test_case'
 test_report='D:\\testpro\\report'
 discover=unittest.defaultTestLoader.discover(test_dir,pattern='test_*.py')
 now=time.strftime("%Y-%M-%D_%H_%M_%S")
 filename=test_report+'\\'+now+'result.html'
 fp=open(filename,'wb')
 runner=HTMLTestRunner(stream=fp,title='测试报告',description='用例执行情况:')
 runner.run(discover)
 fp.close()
 new_report=new_report(test_report)
 send_mail(new_report)

整个程序的执行过程可以分为三个步骤:

  • 通过unittest框架的discover()找到匹配测试用例。由HTMLTestRunner的run()方法执行测试用例并生成最新的测试报告。
  • 调用new_report()函数找到测试报告目录(report)下最新生成的测试报告,返回测试报告的路径。
  • 将得到的最新测试报告的完整路径传给send_mail()函数,实现发邮件功能。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
跟老齐学Python之字典,你还记得吗?
Sep 20 Python
python使用Tkinter显示网络图片的方法
Apr 24 Python
Python实现将照片变成卡通图片的方法【基于opencv】
Jan 17 Python
Python处理菜单消息操作示例【基于win32ui模块】
May 09 Python
使用Python快速搭建HTTP服务和文件共享服务的实例讲解
Jun 04 Python
Pandas Shift函数的基础入门学习笔记
Nov 16 Python
Kears+Opencv实现简单人脸识别
Aug 28 Python
Pytorch实现基于CharRNN的文本分类与生成示例
Jan 08 Python
python如何调用字典的key
May 25 Python
Pytest单元测试框架如何实现参数化
Sep 05 Python
Python GUI库Tkiner使用方法代码示例
Nov 27 Python
Python操作PostgreSql数据库的方法(基本的增删改查)
Dec 29 Python
python3去掉string中的标点符号方法
Jan 22 #Python
在Python中将函数作为另一个函数的参数传入并调用的方法
Jan 22 #Python
python3.4爬虫demo
Jan 22 #Python
使用Template格式化Python字符串的方法
Jan 22 #Python
python实现公司年会抽奖程序
Jan 22 #Python
对python函数签名的方法详解
Jan 22 #Python
python实现大转盘抽奖效果
Jan 22 #Python
You might like
编写漂亮的代码 - 将后台程序与前端程序分开
2008/04/23 PHP
在PHP中实现Javascript的escape()函数代码
2010/08/08 PHP
如何使用PHP获取指定日期所在月的开始日期与结束日期
2013/08/01 PHP
PHP传参之传值与传址的区别
2015/04/24 PHP
ThinkPHP V2.2说明文档没有说明的那些事实例小结
2015/07/01 PHP
学习php设计模式 php实现备忘录模式(Memento)
2015/12/09 PHP
PHP创建多级目录的两种方法
2016/10/28 PHP
php 获取xml接口数据的处理方法
2018/05/31 PHP
PHP+MySQL实现模糊查询员工信息功能示例
2018/06/01 PHP
javascript onkeydown,onkeyup,onkeypress,onclick,ondblclick
2009/02/04 Javascript
使用UglifyJS合并/压缩JavaScript的方法
2012/03/07 Javascript
js的隐含参数(arguments,callee,caller)使用方法
2014/01/28 Javascript
Internet Explorer 11 浏览器介绍:别叫我IE
2014/09/28 Javascript
Javascript模块化编程详解
2014/12/01 Javascript
JavaScript使用二分查找算法在数组中查找数据的方法
2015/04/07 Javascript
javascript简单进制转换实现方法
2016/11/24 Javascript
jQuery Masonry瀑布流插件使用方法详解
2017/01/18 Javascript
JS实现JSON.stringify的实例代码讲解
2017/02/07 Javascript
bootstrap datepicker的基本使用教程
2019/07/09 Javascript
解决layui表格的表头不滚动的问题
2019/09/04 Javascript
三步实现ionic3点击退出app程序
2019/09/17 Javascript
vue 递归组件的简单使用示例
2021/01/14 Vue.js
python中pandas.DataFrame对行与列求和及添加新行与列示例
2017/03/12 Python
python Matplotlib画图之调整字体大小的示例
2017/11/20 Python
Python线性方程组求解运算示例
2018/01/17 Python
对python特殊函数 __call__()的使用详解
2019/07/02 Python
flask框架自定义过滤器示例【markdown文件读取和展示功能】
2019/11/08 Python
Selenium启动Chrome时配置选项详解
2020/03/18 Python
浅析python 动态库m.so.1.0错误问题
2020/05/09 Python
沙龙级头发造型工具:FOXYBAE
2018/07/01 全球购物
在线吉他课程,学习如何弹吉他:Fender Play
2019/02/28 全球购物
医学生自我鉴定范文
2013/11/08 职场文书
小学门卫岗位职责
2013/12/17 职场文书
节约用电通知
2015/04/25 职场文书
学法用法心得体会(2016推荐篇)
2016/01/21 职场文书
高三数学复习备考教学反思
2016/02/18 职场文书