1 # -*- coding:utf-8 -*-
2
3 from HTMLTestRunner import HTMLTestRunner
4 from email import encoders
5 from email.mime.text import MIMEText
6 from email.header import Header
7 from email.mime.multipart import MIMEMultipart
8 from email.mime.base import MIMEBase
9 import smtplib
10 import unittest
11 import time
12 import os
13
14
15 # 定义发送邮件
16 def send_mail(file_new):
17
18 msg_from = '' # 发送方邮箱
19 passwd = '' # 填入发送方邮箱的授权码
20 msg_to = '' # 收件人邮箱
21
22 msg_subject = "" # 邮件主题
23 msg_cOntent= "" # 邮件正文
24
25 msg = MIMEMultipart()
26 # 邮件正文是MIMEText:
27 msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))
28
29 # # 构造附件,传送当前目录下的 .txt 文件
30 # att1 = MIMEText(open('mybook.txt', 'rb').read(), 'base64', 'utf-8')
31 # att1["Content-Type"] = 'application/octet-stream'
32 # att1["Content-Disposition"] = 'attachment; filename="file1.txt"'
33 # msg.attach(att1)
34
35 # 添加附件,发送一个 .html文件
36 with open(file_new, 'rb') as f:
37 mime = MIMEBase('html', 'html')
38 # 加上必要的头信息
39 mime.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_new))
40 mime.add_header('Content-ID', '<0>')
41 mime.add_header('X-Attachment-Id', '0')
42 # 把附件的内容读进来
43 mime.set_payload(f.read())
44 # 用Base64编码
45 encoders.encode_base64(mime)
46 msg.attach(mime)
47
48 msg['Subject'] = Header(msg_subject, 'utf-8') # 主题
49 msg['From'] = msg_from
50 msg['To'] = msg_to
51
52 try:
53 s = smtplib.SMTP_SSL("smtp.qq.com", 465) # 邮件服务器及端口号
54 s.login(msg_from, passwd)
55 s.sendmail(msg_from, msg_to, msg.as_string())
56 print('发送成功!')
57 except s.SMTPException as e:
58 print("发送失败!")
59 finally:
60 s.quit()
61
62
63 # 查找测报告目录,找到最新生成的测试报告文件
64 def new_report(testreport):
65 lists = os.listdir(testreport)
66 lists.sort(key=lambda fn: os.path.getmtime(testreport + "\\" + fn))
67 file_new = os.path.join(testreport, lists[-1])
68 print(file_new)
69 return file_new
70
71
72 if __name__ == '__main__':
73 # 测试用例存放位置
74 test_dir = 'E:\ALL_Demo\Py_Demo\Job3\ExamCase'
75 # 测试报告存放位置
76 test_report = 'E:\ALL_Demo\Py_Demo\Job3\ExamReport'
77
78 discover = unittest.defaultTestLoader.discover(test_dir, 'test_*.py')
79
80 now = time.strftime("%Y-%m-%d_%H_%M_%S_")
81 filename = test_report + '\\' + now + 'result.html'
82 fp = open(filename, 'wb')
83 runner = HTMLTestRunner(stream=fp,
84 title='测试报告',
85 description='用例执行情况:')
86 runner.run(discover)
87 fp.close()
88
89 new_report = new_report(test_report)
90 send_mail(new_report) # 发送测试报告