Python+request+ smtplib 测试结果html报告邮件发送(下)《六》
Posted syw20170419
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python+request+ smtplib 测试结果html报告邮件发送(下)《六》相关的知识,希望对你有一定的参考价值。
配置与实现代码分隔编写,详见如下:
目录结构如下:
1、cfg.ini的配置信息写法如下:
[email] ;--------------------------使用腾讯企业邮箱作为发件人的操作如下--------------------- smtp_server = smtp.qq.com Port = 465 Sender = 请写你自己的QQ邮箱 psw = 请写你自己的QQ授权码 Receiver = [email protected] (注:请写你的邮件收件人邮箱)
2、readConfig.py 此文件主要是获取cfg.ini中对应的配置信息
#!/usr/bin/env python # coding=UTF-8 ‘‘‘此文件主要是获取cfg.ini中对应的配置信息‘‘‘ import os import ConfigParser cur_path = os.path.dirname(os.path.realpath(__file__)) configpath = os.path.join(cur_path,"cfg.ini") conf = ConfigParser.ConfigParser() conf.read(configpath) smtp_server = conf.get("email","smtp_server") sender = conf.get("email","sender") psw = conf.get("email","psw") receiver = conf.get("email","receiver") port = conf.get("email","port") ‘‘‘测试时通过print查看获取的值是否正确,不用释放开‘‘‘ # print cur_path # print configpath # print smtp_server # print sender # print psw # print receiver # print port
3、接收和发送邮件的主体内容
#!/usr/bin/env python # coding=UTF-8 import os import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from Common.logs import logging from Config.email import readConfig report_path = os.getcwd()[:-5] + ‘/Result/Report‘ + "/" class email_L: def get_Report_file(self,report_path): ‘‘‘ 用途:获取最新的API测试报告 参数介绍: report_path:报告存储的路径 ‘‘‘ logging.info("获取最新的测试报告") lists = os.listdir(report_path) #print lists lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn))) logging.info(u"最新测试生成的报告:" + lists[-1]) report_file = os.path.join(report_path, lists[-1]) return report_file def send_mail(self,sender, psw, receiver, smtpserver, report_file, port,status): ‘‘‘ 用途:发送最新的测试报告 参数介绍: sender:发送者 psw:QQ的授权码 receive:接收者 smtpserver:邮件的格式 report_file:发送的邮件附件 port:邮箱的端口 ‘‘‘ logging.info("邮件发送最新的API测试报告") with open(report_file, "rb") as f: mail_body = f.read() # 定义邮件内容 msg = MIMEMultipart() body = MIMEText(mail_body, _subtype="html", _charset="utf-8") msg[‘subject‘] = u"【%s】iBer接口自动化测试报告"%status msg[‘from‘] = sender msg[‘to‘] = psw msg.attach(body) # 添加附件 att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8") att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = ‘attachment;filename = "report.html"‘ msg.attach(att) try: smtp = smtplib.SMTP_SSL(smtpserver, port) except: smtp = smtplib.SMTP() smtp.connect(smtpserver, port) # 用户名和密码 smtp.login(sender, psw) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() logging.info("API测试报告已发送成功 !") receiver = readConfig.receiver logging.info("已发送的邮箱: %s" %receiver) def test_run(self,status): ‘‘‘如上2个方法的集合整理方法‘‘‘ report_file = self.get_Report_file(report_path) # 邮箱配置 sender = readConfig.sender psw = readConfig.psw smtp_server = readConfig.smtp_server port = readConfig.port receiver = readConfig.receiver self.send_mail(sender, psw, receiver, smtp_server, report_file, port,status) # 发送报告
4、Run_Test.py 主要是针对测试结果,发送邮件。在你的接口测试执行结束后,添加此段代码即可
from Common.email_L import email_L #调用的写法根据你自己的文件路径来写
y = email_L()
y.test_run() #无论成功失败均发送邮件
升级版,结合unittest框架,根据测试结果判断邮件发送的格式和内容:
执行结果中有失败的项,接收的邮件标题:【FAIL】接口自动化测试报告
执行结果全部成功,接收的邮件标题:【PASS】接口自动化测试报告
注:
logging:是我自己封装的logs模块。若你没有,则直接注释,用print打印结果
suite:result = runner.run(suite) 是对所有测试用例的合集(不会者可查看下:https://blog.csdn.net/ljl6158999/article/details/80994979)
#!/usr/bin/env python # coding=UTF-8 import os,time import unittest from Common.logs import logging from Test.Case.Z_Case_collects import suite import Common.HTMLTestRunner2 from Common.email_L import email_L class run(unittest.TestCase): def test_Runtest(self): now = time.strftime(‘%Y-%m-%d-%H-%M-%S‘, time.localtime(time.time())) File_Path = os.getcwd()[:-5]+ ‘/Result/Report‘ + "/" # 获取到当前文件的目录,并检查是否有report文件夹,如果不存在则自动新建report文件 #print File_Path if not os.path.exists(File_Path): os.makedirs(File_Path) #logging.info(File_Path) Report_FileName = file(File_Path + now + r"_API测试报告.html", ‘wb‘) runner = Common.HTMLTestRunner2.HTMLTestRunner(stream=Report_FileName, title="接口测试报告", description="用例执行情况:",verbosity=2) #verbosity=2:将会取到方法名下的注释内容 result = runner.run(suite) ## suite为Case_Gathers.py中的suite,用法:将case中的suite添加到报告中生成 Report_FileName.close() ################################如下:测试结果邮件发送给对应接收者################################### # print "运行成功的数目",result.success_count # print "运行失败的数目",result.failure_count # print "运行测试用例的总数",Common.HTMLTestRunner2.HTMLTestRunner.total time.sleep(2) y = email_L() #y.test_run() #无论成功失败均发送邮件 if result.success_count != Common.HTMLTestRunner2.HTMLTestRunner.total: y.test_run(status = "FAIL") #接口用例有执行失败,则发送的邮件标题中会标出【Fail】 logging.error("用例中执行有失败,请查看邮件!!!!") else: y.test_run(status="PASS") #与上面反之,标注【Pass】 logging.error("用例执行全部成功,请查看邮件!!!!") if __name__ == "__main__": unittest.main()
实现结果示例:
以上是关于Python+request+ smtplib 测试结果html报告邮件发送(下)《六》的主要内容,如果未能解决你的问题,请参考以下文章