随笔记录方便自己和同路人查阅。
#------------------------------------------------我是可耻的分割线-------------------------------------------
学习selenium自动化之前,最好先学习HTML、CSS、JavaScript等知识,有助于理解定位及操作元素的原理。关于python和selenium安装请自行搜索别的资料,这里就不多做介绍了,所有例子均使用python3.6+selenium执行的。
#------------------------------------------------我是可耻的分割线-------------------------------------------
整合自动发邮件功能
解决了前面的问题后,现在就可以将自动发邮件功能继承到自动化测试项目中了。下面打开runtest.py文件重新进行编辑。
# !/usr/bin/env python
# -*- coding: UTF-8 –*-
__author__ = 'Mr.Li'
from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import unittest
import time
import os
# =====================定义发送邮件================
def send_mail(file_new):
f = open(file_new,'rb')
mail_bobd = f.read()
f.close()
msg = MIMEText(mail_bobd,'html','utf-8')
msg['Subject'] = Header('自动化测试报告','utf-8')
smtp = smtplib.SMTP()
smtp.connect("smtp.qq.com")
smtp.login('xxxx@qq.com','mbnzfxlnmwbkbcfb')
smtp.sendmail('xxxx@qq.com','xxxx@qq.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_new
#执行测试类的测试方法
if __name__ == '__main__':
test_report = 'C:\\Users\\86136\\PycharmProjects\\spider\\test\\test_project\\report\\'
test_dir = 'C:\\Users\\86136\\PycharmProjects\\spider\\test\\test_project\\test_case'
#把测试用例加载到一个套件
dicscover = 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(dicscover) # 运行测试用例
fp.close() # 关闭报告文件
new_report = new_report(test_report)#找到最新测试报告
send_mail(new_report) #发送测试报告
整个程序的执行过程可以分为三步骤:
1、通过unittest框架的discover()找到匹配测试用例,由HTMLTestRunner的run()方法执行测试用例并生成最新的测试报告。
2、调用new_report()函数找到测试报告目录(report)下最新生成的测试报告,返回测试报告的路径。
3、将得到的最新测试报告路径传给send_mail()函数,实现发邮件功能。
整个脚本执行完成后,打开接收邮箱,即可看到最新测试执行的测试报告,如下图:


来源:https://www.cnblogs.com/lirongyang/p/11595866.html