您的位置:首页 > 编程语言 > Python开发

Python3+unitest自动化测试初探(中篇)

2019-04-18 01:41 1451 查看

目录

本篇随笔承接:Python3+unitest自动化测试初探(上篇)

地址:Python3+unitest自动化测试初探(上篇)

6、生成测试报告

6.1、下载HTMLTestRunner.py

原版下载地址:http://tungwaiyip.info/software/HTMLTestRunner.html
原版的只支持Python 2.x版本,Python 3.x版本需要做适配

适配后的下载地址:https://github.com/Slience007/pyunitest/blob/master/untils/HTMLTestRunner.py

6.2、安装HTMLTestRunner.py

安装方法比较简单,将HTMLTestRunner.py放到sys.path路径下即可。ubuntu下,我放到了如下路径:/usr/lib/python3.7。

6.3、生成报告

HTMLTestRunner.py提供HTMLTestRunner()类来代替unittest.TextTestRunner()执行用例,修改后的run.py的代码如下:

#coding:utf-8
import  unittest
#导入HTMLTestRunner
from HTMLTestRunner import  HTMLTestRunner
#从testCase包里面导入测试类
from testCases.userLoginTest import loginTest
from testCases.userRegTest import regTest

#构造测试套
def suite():
suite = unittest.TestSuite()
suite.addTest(loginTest("test_loginsucess_L0"))
suite.addTest(loginTest("test_pwdwrong_L0"))
suite.addTest(loginTest("test_statuserr_L1"))
suite.addTest(regTest("test_pwdlenerr_L1"))
suite.addTest(regTest("test_regsucess_L0"))
suite.addTest(regTest("test_regagain_L1"))
return suite

#运行测试用例
if __name__ == '__main__':
# runner = unittest.TextTestRunner()
# #调用test runner的run方法执行用例
# runner.run(suite())
#以二进制格式打开TestReport.html用于写入数据
with open("./TestReport.html","wb") as f:
runner = HTMLTestRunner(stream=f,title="Reg And Login Test Report")
runner.run(suite())

运行run.py后,打开TestReport.html,查看生成的测试报告。

7、编写邮件发送工具

在Project下新建包utils用来封装一些常用的工具,在utils下新建Python文件emailUtil.py。定义sendEmail类。这个类主要包含3个方法:

  1. init():初始化
  2. writeEmail():构造邮件主题,邮件正文,添加邮件附件。
  3. sendEmail():连接邮件服务器,认证,发送邮件。我采用的是网易邮件服务器,其地址是smtp.126.com。收件地址为QQ邮箱。

[ 代码如下:]emailUtil.py

#coding:utf-8
'''
email模块负责构造邮件内容
smtplib模块负责发送邮件
'''
from email.mime.text import  MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email.header import Header

class sendEmail():
#定义全局变量邮件服务器地址,登录用户,授权码
global MAILHOST,MAILUSER,MAILPWD
MAILHOST = "smtp.126.com"
MAILUSER = "××××@126.com"
MAILPWD = "×××"

def __init__(self,subject,content,reveiver,attachPath=""):
self.subject = subject
self.content = content
self.receiver = reveiver
self.attachPath = attachPath
#写邮件,返回msg.as_string()
def writeEmail(self):
msg = MIMEMultipart()
#邮件正文
msg.attach(MIMEText(self.content, 'plain', 'utf8'))
receiverName = ",".join(self.receiver)
msg['from'] = Header(MAILUSER,'utf-8')
#msg['to'] =  Header(",".join(self.receiver)).encode()
msg['to'] = Header(receiverName).encode()
#邮件主题
msg['Subject'] = Header(self.subject,'utf-8').encode()
#print("msg is:",msg)
#attachPath不为空则添加附件到邮件中
if self.attachPath != "":
with open(self.attachPath, 'rb') as f:
attach1  = MIMEText(f.read(), 'base64', 'utf-8')
attach1["Content-Type"] = 'application/octet-stream'
#filename可以随便写
attach1["Content-Disposition"] = 'attachment; filename="Result.html"'
msg.attach(attach1)

return msg.as_string()

#发送邮件
def sendEmail(self):
receiver = ";".join(self.receiver)
try:
#连接邮件服务器
server = smtplib.SMTP()
server.connect(MAILHOST,25)
#打开debug模式可以看到握手过程
#server.set_debuglevel(1)
#登录,MAILPWD为网易邮件的授权码
server.login(MAILUSER,MAILPWD)
#发送邮件
server.sendmail(MAILUSER,receiver,self.writeEmail())
server.quit()
print("Email send sucess.")
except Exception as  e:
print("Email send fail.")
print(e)

在编写邮件工具的时候,碰到了一个错误:smtplib.SMTPDataError: (554, b'DT:SPM。原因可能是:邮件被网易邮件服务器当成了垃圾邮件。解决办法:邮件主题不能包含test,另外msg[from"],msg['to']要和server.sendmail(MAILUSER,receiver,self.writeEmail())中的MAILUSER和receiver保持一致。

8、发送邮件

在发送邮件之前,先获取本次执行用例总数,失败用例数,成功用例数,跳过的用例数。并计算出用例通过率。

  1. suite().countTestCases():获取用例总数。
  2. runner.run(suite()).success_count:运行通过的用例数。
  3. runner.run(suite()).failure_count:失败的用例数。
  4. runner.run(suite()).skipped:返回的是跳过的用例list。

接下来来修改run.py ,需要先从utils模块导入sendEmail类,构造主题,邮件正文,指定收件人列表,指定测试报告的路径,之后调用sendEmail方法发送邮件。修改后的run.py代码如下:

#coding:utf-8
import  unittest
#导入HTMLTestRunner
from HTMLTestRunner import  HTMLTestRunner
#从testCase包里面导入测试类
from testCases.userLoginTest import loginTest
from testCases.userRegTest import regTest

from utils.emailUtil import sendEmail
#构造测试套
def suite():
suite = unittest.TestSuite()
suite.addTest(loginTest("test_loginsucess_L0"))
suite.addTest(loginTest("test_pwdwrong_L0"))
suite.addTest(loginTest("test_statuserr_L1"))
suite.addTest(regTest("test_pwdlenerr_L1"))
suite.addTest(regTest("test_regsucess_L0"))
suite.addTest(regTest("test_regagain_L1"))
return suite

#运行测试用例
if __name__ == '__main__':
# runner = unittest.TextTestRunner()
# #调用test runner的run方法执行用例
# runner.run(suite())
#以二进制格式打开TestReport.html用于写入数据
with open("./TestReport.html","wb") as f:
runner = HTMLTestRunner(stream=f,title="Reg And Login Test Report")
result = runner.run(suite())
totalNums = suite().countTestCases()
passedNums = result.success_count
failedNums = result.failure_count
skippedNums = len(result.skipped)
#通过率,保留两位小数
passRate = round(passedNums * 100/  totalNums)
emailBody = "Hi,all:\n \t本次构建一共运行:{totalNums}个用例,通过{passedNums}个,失败{failedNums}个,跳过{skippedNums}个。通过率:{passRate}%.\n \t详细信息请查看附件。"
content = emailBody.format(totalNums=totalNums,passedNums=passedNums,failedNums=failedNums,skippedNums=skippedNums,passRate=passRate)
#收件人列表
receiver = ['××××@qq.com',"×××××@126.com"]
#测试报告的路径
path1 = "/home/stephen/PycharmProjects/unitTestDemo/TestReport.html"
subject = "登录注册功能每日构建"
e = sendEmail(subject,content,receiver,attachPath=path1)
#发送邮件
e.sendEmail()

运行run.py。登录邮箱查看已经发送成功的邮件。

点击这里返回本篇目录

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: