(原文:https://www.cnblogs.com/fancy0158/p/10056418.html)
移动端执行完测试case之后,通过邮件自动发送测试报告。大体流程如下:
1、通过unittest框架的discover()发现所有测试用例
2、使用HTMLTestRunner的run()方法运行测试用例,生成HTML测试报告
3、寻找测试报告目录下的最新测试报告,返回最新测试报告的路径
4、将最新测试报告路径传给send_mail()函数,发送带HTML格式的邮件
# coding:utf-8 import unittest import time import smtplib import os from email.mime.text import MIMEText from email.header import Header from email.mime.multipart import MIMEMultipart from HTMLTestRunner import HTMLTestRunner testcase_dir = 'E:\\python_work\\appium\\test_app\\testcase' # 测试用例路径 testreport_dir = 'E:\\python_work\\appium\\test_app\\report' # 测试报告路径 # 发送邮件 def sendmail(sendfile): smtpserver = 'smtp.qq.com' user = 'username@qq.com ' password = 'password' sender = 'username@qq.com' receiver = 'receiver@163.com' subject = '自动化测试报告' f = open(sendfile, 'rb') mailbody = f.read() # 读取测试报告作为邮件正文 f.close() # 编写HTML类型的邮件正文 msg = MIMEText(mailbody, 'html', 'utf-8') msg["Subject"] = Header(subject, 'utf-8') smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() print('Email has send out') # 查找目录下最新生成的测试报告,返回最新报告的详细路径 def find_Report(reportpath): lists = os.listdir(reportpath) lists.sort(key=lambda fn: os.path.getmtime(reportpath + "\\" + fn)) newfile = os.path.join(reportpath, lists[-1]) print(newfile) return newfile # 运行case,并生成测试报告 def run_case(): discover = unittest.defaultTestLoader.discover(testcase_dir, pattern='test*.py') now_time = time.strftime("%Y%m%d_%H-%M-%S") fp = open(testreport_dir + '\\' + now_time + '_TestResult.html', 'wb') runner = HTMLTestRunner( stream=fp, title='测试报告', description='测试用例执行情况', ) runner.run(discover) # 运行case,生成HTML测试报告 fp.close() if __name__ == '__main__': run_case() new_report = find_Report(testreport_dir) sendmail(new_report)
收到的邮件如下:
软件测试