runner.py脚本
import unittest from HTMLTestRunner import HTMLTestRunner import time import datetime from test_project.send_mail import send_call pt='./' #表示当前目录下 discover=unittest.defaultTestLoader.discover(pt,pattern='test*.py',top_level_dir=None) #加载当前目录下所有test开头的case if __name__=='__main__': now=time.strftime("%Y_%m_%d_%H_%M_%S") # t=datetime.datetime.now() # tt='{}-{}-{} {}:{}:{}'.format(t.year,t.month,t.day,t.hour,t.minute,t.second) #2种取时间的方式 fp='D:\jodie\jodiepy\test_project\report\result'+now+'.html' filename=open(fp,'wb') runner=HTMLTestRunner(stream=filename,title="搜索测试报告",description="用例执行情况") runner.run(discover) filename.close() time.sleep(5) send_call('D:\jodie\jodiepy\test_project\report')
发送邮件脚本
import smtplib #用于发送邮件 from email.mime.text import MIMEText #定义邮件正文 from email.mime.multipart import MIMEMultipart #定义邮件附件 from email.header import Header #定义邮件标题 import os class SendMail(): def __init__(self,smtpsever='smtp.qq.com',user='270195336',psw='ilwhkdgsfweibgfb',sender='270195336@qq.com' ,receiver='jodie_030809@126.com'): #定义邮件服务器 self.smtpsever=smtpsever #发送邮件的用户名密码 self.user=user self.psw=psw #为邮箱授权密码,而非用户登录密码 #发送的邮箱,一定要先授权客户端 self.sender=sender #接收的邮箱 self.receiver=receiver def send(self,subject,filename='None'): """ 根据用户传入的主题和附件路径,发送邮件 :param subject: 邮件主题 :param filename: 附件的完整路径 :return: """ msgRoot = MIMEMultipart("related") # 构造邮件正文 zhengwen = MIMEText('<html><h1>自动化测试报告!请查阅</h1></html>', 'html', 'utf-8') # 构造邮件头部 msgRoot['subject'] = Header(subject, 'utf-8') msgRoot['From'] = self.sender msgRoot['To'] = self.receiver msgRoot.attach(zhengwen) if filename!='None': # 发送的附件 self.filename = open(filename, 'rb').read() # 取路径中的文件名 file = os.path.split(filename)[1] #构造附件(可构造多个附件) att=MIMEText(self.filename,'base64','uft-8') att['Content-Type']='application/octet-stream' att["Content-Disposition"]="attachment;filename="+file msgRoot.attach(att) #连接发送邮件 smtp=smtplib.SMTP() smtp.connect(self.smtpsever) smtp.login(self.user,self.psw) smtp.sendmail(self.sender,self.receiver,msgRoot.as_string()) smtp.quit() def new_report(testreport): """ 对目录下的文件按时间排序,取日期最新的测试报告返回 :param testreport: 测试报告存放目录 :return: 返回最新的测试报告文件路径 """ 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 def send_call(report,subject="自动化测试报告"): """ :param new_report: 存放测试报告的上级目录 :param subject: 发送邮件的主题 :return: """ filename=new_report(report) sm=SendMail() sm.send(subject,filename) if __name__=='__main__': send_call('D:\jodie\jodiepy\test_project\report')
HTMLTestRunner.py要放到python安装目录下D:UsersjodieAppDataLocalProgramsPythonPython38