python 导出数据并发邮件_python接口自动化-生成测试报告-然后自动发送邮件

前两篇单独介绍了生成测试报告和自动发送邮件,那么现在把两者整合到一起;生成测试报告后然后自动发送邮件,这里只是简单的整合实现功能,其实还可以优化的,先用吧,后面再慢慢优化

先看下目录,其实目录还是一样,只是在run_all_case中添加了函数

case 存放测试用例

commen 存放公共模块

report 存放测试报告

7cc6abb48431747d2ad3e981abb76c77.png

# coding:utf-8

import unittest

from commen import HTMLTestRunner_jpg

import os

import smtplib

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

current_path = os.getcwd() # 当前文件路径

report_path = os.path.join(current_path, "report")

# 测试报告为result.html

result_path = os.path.join(report_path, "result.html")

# 加载全部用例

def all_case():

case_path = os.path.join(current_path, "case") # 用例路径

discover = unittest.defaultTestLoader.discover(case_path,

pattern="test*.py")

return discover

def send_email(smtpserver, port, sender, psw, receiver):

# 写信模板

msg = MIMEMultipart()

msg['Subject'] = "这是opa项目的自动化测试报告"

msg['From'] = sender

msg['to'] = receiver

# 通过os获取文件路径

annex = open(result_path, "r", encoding="utf-8").read() # 附件,打开并且读取测试报告

main_body = '

 
 

这是opa项目的自动化测试报告,请查阅!`

' # 正文的内容

# 添加正文到容器

body = MIMEText(main_body, "html", "utf-8")

msg.attach(body)

# 添加附件到容器

att = MIMEText(annex, "base64", "utf-8")

att["Content-Type"] = "application/octet-sream"

att["Content-Disposition"] = 'attachment;filename="opa_test_report.html"' # 附件名称

msg.attach(att)

# 连接发送邮件

smtp = smtplib.SMTP_SSL(smtpserver, port)

smtp.login(sender, psw)

smtp.sendmail(sender, receiver, msg.as_string())

smtp.quit()

if __name__ == "__main__":

# 打开文件,把结果写进文件中,w,有内容的话,清空了再写进去

fp = open(result_path, "wb") # 打开result.html,把测试结果写进去

runner = HTMLTestRunner_jpg.HTMLTestRunner(stream=fp,

title="测试报告",

description="用例执行情况")

# 调用all_case函数返回值

runner.run(all_case())

# 有开有闭,关闭刚才打开的文件

fp.close()

# 发送邮件

send_email("smtp.qq.com", 465, "3437871062@qq.com", "这里填自己的授权码", "1039020476@qq.com")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值