这几天由于需要结合 jenkins 执行自动化脚本并发送报告附件, 折腾了几天, 解决了, 源码如下:
部分读取配置文件等内容可以根据自己公司的内容做增减
- #coding=utf-8
- from htmlTestRunner import HTMLTestRunner
- from email.mime.text import MIMEText
- from email.mime.multipart import MIMEMultipart
- import smtplib,sys,unittest,configparser,os
- # ============== 定义发送邮件 ==========
- def send_mail(file_new,title):
- #读取报告
- f = open(file_new, 'rb')
- mail_body = f.read()
- f.close()
- #设置邮件信息
- msg = MIMEMultipart()
- msg["subject"] = title #主题
- body = MIMEText(mail_body, "html", "utf-8")
- msg.attach(body)
- #添加附件
- att = MIMEText(mail_body, "html", "utf-8")
- att["Content-Type"] = "application/octet-stream"
- att["Content-Disposition"] = 'attachment; filename="CRM_UItest_report.html"' #定义附件名称
- msg.attach(att)
- #配置邮箱信息
- smtp = smtplib.SMTP()
- smtp.connect('192.168.0.1') # 邮箱服务器
- smtp.login("abcd", "123456") # 登录邮箱 -->abcd 为登录服务器账号, 123456 为登录服务器密码
- smtp.sendmail("abd@qq.com", "123@qq.com", msg.as_string()) # 配置发送邮箱 abd@qq.com 和接收邮箱 123@qq.com, 接收邮箱可以定义成字符串 "123@qq.com,456@qq.com", 设置多个接受者
- smtp.quit()
- print("Email had send! Please recevie")
- # ====== 查找测试目录, 找到最新生成的测试报告文件 ======
- def new_report(test_report):
- lists = os.listdir(test_report) # 列出目录的下所有文件和文件夹保存到 lists
- lists.sort(key=lambda fn: os.path.getmtime(test_report + "\\" + fn)) # 按时间排序
- file_new = os.path.join(test_report, lists[-1]) # 获取最新的文件保存到 file_new
- print(file_new)
- return file_new
- if __name__ == "__main__":
- #定义配置 (可以根据公司实际需要增减此部分)
- config = configparser.ConfigParser()
- #获取相对路径
- dir = os.path.dirname(os.path.abspath('.'))
- #获取配置文件
- file_path = dir + '/config/config.ini'
- #读取配置文件
- config.read(file_path)
- #定义变量
- URL_address = config.get('testServer', 'URL_address')
- version = config.get('testServer', 'version')
- testcase_path = dir + '\\test_case\\'
- crm_path = dir + '\\report\\'
- curPath = os.path.abspath(os.path.dirname(__file__))
- rootPath = os.path.split(curPath)[0]
- sys.path.append(rootPath)
- #获取测试用例
- discovers = unittest.defaultTestLoader.discover(testcase_path,pattern = 'test*.py',top_level_dir=None)
- #discovers = unittest.defaultTestLoader.discover(testcase_path, pattern='test.py')
- #now = time.strftime("%Y-%m-%d_%H-%M-%S")
- filename = dir + '\\report\\CRM_UItest_report.html'
- fp = open(filename, 'wb')
- #定义报告名称
- title = 'CRM 系统_' + URL_address[:2] + '环境_' + version + '版本 UI 自动化测试报告'
- #runner = HTMLTestRunner(stream=fp,title='CRM 系统 UI 自动化测试报告',description='测试用例执行情况')
- #生成 HTML 报告
- runner = HTMLTestRunner(stream=fp, title=title, description='测试用例执行情况')
- #执行测试用例
- runner.run(discovers)
- fp.close()
- new_report = new_report(crm_path)
- send_mail(new_report,title) # 发送测试报告
来源: http://www.bubuko.com/infodetail-2992821.html