Python3+HTMLTestRunner+SMTP生成测试报告后发送邮件

 

在前一篇https://www.cnblogs.com/zhengyihan1216/p/11549820.html 中记录了如何生成html格式的报告,

这篇记录下怎么将测试报告通过邮件发出

 

1、对test_add_dele.py文件进行修改及完善

  注释:email库定义邮件里的内容,smtplib库进行邮件发送

 1 #coding=utf-8
 2 from HTMLTestRunner import HTMLTestRunner
 3 from email.mime.text import MIMEText
 4 from email.header import Header
 5 import smtplib
 6 import unittest
 7 import add_dele
 8 import time
 9 import os
10 
11 #在测试报告目录下找到最新的报告文件,打印且返回最新报告的名称
12 def find_new_report(report_dirc):
13     lists = os.listdir(report_dirc)
14     lists.sort(key=lambda fn:os.path.getmtime(report_dirc+"\\"+fn))
15     new_report = os.path.join(report_dirc,lists[-1])
16     print(new_report)
17     return new_report
18 
19 def send_mail(new_report):
20     #读取报告
21     f = open(new_report,'rb')
22     mail_body = f.read()
23     f.close()
24     #定义邮件正文,报告以正文的形式发送
25     msg = MIMEText(mail_body,'html','utf-8')
26 
27     #定义邮件标题
28     msg['Subject'] = Header("自动化测试报告","utf-8")
29     mail_server = "mail.xxxxx.com"
30     user_name = "username1@xxxxx.com"
31     pwd = "xxxxx"
32     from_add = "username1@xxxxx.com"
33     to_add = "username2@xxxxx.com"
34 
35     smtp = smtplib.SMTP()
36     smtp.connect(mail_server)
37     smtp.login(user_name,pwd)
38     smtp.sendmail(from_add,to_add,msg.as_string())
39     smtp.quit()
40     print("emial has send out")
41 
42 if __name__ =="__main__":
43     #构建测试集
44     suit = unittest.TestSuite()
45     #测试集加入add_dele文件中被调用的方法。格式suit.addTest(文件名.类名("方法名"))
46     suit.addTest(add_dele.Test_test("test_shuzi"))
47     suit.addTest(add_dele.Test_test("test_liangmethod"))
48     #定义存放测试报告的路径及文件名
49     #我定义的路径是:当前路径+存放报告的专有目录Report+文件名(文件名是当前时间+report.html)
50     curent_dirc=os.path.dirname(os.path.realpath(__file__))
51     report_dirc = curent_dirc + "\Report"
52     now = time.strftime("%Y%m%d-%H%M%S")
53     report_name = report_dirc+"\\"+now+"report.html"
54     fp = open(report_name,"wb")
55     runner = HTMLTestRunner(stream=fp,
56                             title="测试一下报告生成",
57                             description="用两个数字的相加减来练习")
58     runner.run(suit)
59     fp.close()
60     #发送邮件
61     send_mail(find_new_report(report_dirc))

 

2、username2@xxxxx.com 该邮箱中收到的报告如下截图所示:

 3、注意问题

  如果发出的测试报告里测试用例没有展开,则将.....Python35\Lib\HTMLTestRunner.py文件中的改行删除:  .hiddenRow  { display: none; }

  由于大家用的HTMLTestRunner.py文件版本不同,所以该文件具体在第几行不同,可以根据文字进行搜索后删除。

  

 

posted on 2019-09-25 11:22  zhengyihan  阅读(1290)  评论(0编辑  收藏  举报

导航