Selenium 2自动化测试实战38(整合自动发邮件功能)

整合自动发邮件功能

解决了前面的问题后,现在就可以将自动发邮件功能集成到自动化测试项目中了。下面重新编辑runtest.py文件

#runtest.py
#coding:utf-8 from HTMLTestRunner import HTMLTestRunner from email.mime.text import MIMEText from email.header import Header import smtplib import unittest,time,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(u"自动化测试报告",'utf-8') msg['from']='[email protected]' msg['to']='[email protected]' smtp=smtplib.SMTP() smtp.connect("smtp.sina.com") smtp.login("xxxxx","xxxxxxx") smtp.sendmail("[email protected]","[email protected]",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_dir='F:\\study\\web_demo1\\test_case' test_report='F:\\study\\web_demo1\\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=u"测试报告",description=u"用例执行情况:") runner.run(discover) fp.close() newreport=new_report(test_report) send_mail(newreport)#发送测试报告

  

执行后,结果如下图所示:

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

猜你喜欢

转载自www.cnblogs.com/Rita-LJ/p/11799475.html
今日推荐