Python+selenium整合自动发邮件功能
主要实现的目的是:自动将测试报告以邮件的形式通知相关人员
1 from HTMLTestRunner import HTMLTestRunner 2 import HTMLTestReport 3 from email.mime.text import MIMEText 4 from email.header import Header 5 import smtplib 6 import unittest 7 import time 8 import os 9 10 11 # ******************定义发送邮件****************** 12 def send_mail(file_new): 13 f = open (file_new, 'rb') 14 filename = f.read () 15 f.close () 16 smtp = smtplib.SMTP () 17 smtp.connect ('smtp.163.com') 18 sender = 'fengyiru6369@163.com' 19 receiver = '1194150169@qq.com' 20 username = 'fengyiru6369@163.com' 21 password = 'FYRu19200915' 22 smtp.login (username, password) 23 24 subject = '附件为最新测试报告,望查收' 25 msg = MIMEText (filename, 'html', 'utf-8') 26 msg['Subject'] = Header("自动化测试报告",'utf-8') 27 msg['From'] = 'Tim<fengyiru6369@163.com>' 28 msg['To'] = '1194150169@qq.com' 29 smtp.sendmail (sender, receiver, msg.as_string ()) 30 smtp.quit () 31 32 print ('email has send out!') 33 34 35 # ===========================查找测试报告目录,找到最新的测试报告文件 =========================== 36 def new_report(testreport): 37 lists = os.listdir (testreport) 38 lists.sort (key=lambda fn: os.path.getmtime (testreport + "\\" + fn)) 39 file_new = os.path.join (testreport, lists[-1]) 40 print (file_new) 41 return file_new 42 43 44 if __name__ == "__main__": 45 test_dir = r'E:\python\测试报告' 46 test_report = r'E:\python\测试报告' 47 discover = unittest.defaultTestLoader.discover (test_dir, pattern='testreport1.py') 48 now = time.strftime ("%Y-%m-%d_%H_%M_%S") 49 filename1 = test_report + '\\' + now + 'result.html' 50 fp = open (filename1, 'wb') 51 # runner = HTMLTestReport.HTMLTestRunner (stream=fp, title=u"自动化测试报告", description='自动化测试演示报告', tester='fyr') 52 runner = HTMLTestRunner (stream=fp, title='集成测试报告', description='测试用例执行情况') 53 runner.run (discover) 54 fp.close () 55 new_report = new_report (test_report) 56 print(new_report) 57 send_mail (new_report) # 发送测试包
该程序的执行过程分为三个步骤:
1.通过unittest框架的discover()找到匹配的测试用例,由HTMLTestRunner的run()方法执行测试用例并生成最新的测试报告。
2.调用new_report()函数找到测试报告目录找到测试报告目录(report)下最新的测试报告,返回测试报告的测试报告的路径。
3.将得到的最新测试报告的完整路径传给send_mail()函数,实现发送邮件功能。