代码如下:
#coding=utf-8
import unittest
import time,HTMLTestRunner
import smtplib
from email.mime.text import MIMEText
import os
#==================定义发送邮件=================
def send_mail(file_new):
sender = 'alyna_cai@163.com' #发送邮箱
receiver = '1755897460@qq.com' #接收邮箱
f = open(file_new,'rb')
content = f.read()
f.close()
msg = MIMEText(content,'html','utf-8')
msg['Subject'] = '自动化测试报告'
msg['From'] = sender
msg['To'] = receiver
#msg['Date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z') #定义发送时间
try:
stmp = smtplib.SMTP()
stmp.connect('smtp.163.com') #连接smtp服务器
stmp.login(sender,'XCMQESJMOKLWRYBF') #使用授权码登录
stmp.sendmail(sender,receiver,msg.as_string()) #发送邮件
print("邮件发送成功")
stmp.quit()
except smtplib.SMTPException:
print("Error:无法发送邮件")
#=====查找测试报告目录,找到最新生成的测试报告文件======
def send_report(testreport):
result_dir = testreport #定义文件目录
lists = os.listdir(testreport)
#重新按时间对目录下的文件进行排序
lists.sort(key=lambda fn:os.path.getmtime(result_dir+'\\'+fn))
print(u'最新测试生成的报告:'+lists[-1])
file_new = os.path.join(result_dir,lists[-1]) #找到最新生成的文件
print(file_new)
send_mail(file_new) #调用发送模块
#===============将用例添加到测试套件=================
def creatsuite():
testunit = unittest.TestSuite()
#定义测试文件查找的目录
test_dir = ".\\test_case"
#定义discover方法的参数
discover = unittest.defaultTestLoader.discover(test_dir,pattern='test*.py',top_level_dir=None)
#将用例循环添加到测试套件
for test_case in discover:
testunit.addTest(test_case)
print(testunit)
return testunit
if __name__ == "__main__":
now = time.strftime("%Y-%m-%d %H_%M_%S")
testreport = 'D:\\python\\_project\\test_163email\\test_case\\report\\'
filename = testreport +now+'result.html'
fp = open(filename, 'wb')
runner = HTMLTestRunner.HTMLTestRunner(
stream=fp,
title=u'自动测试用例',
description=u'用例执行情况:'
)
alltestnames = creatsuite()
runner.run(alltestnames)
fp.close()
send_report(testreport)
网友评论