【Unittest】接口自动化测试(一)运行用例、取最新测试报告并发送邮件

需要导入python的HTMLTestRunner第三方模块

# -*- coding: utf-8 -*-
import unittest
from HTMLTestRunner import HTMLTestRunner
import time
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# import logging
# from tool import output_log
import urllib3
urllib3.disable_warnings()

run_os = 'linux'


# 2.定义:取最新测试报告
def new_file(test_dir):
    # 列举test_dir目录下的所有文件,结果以列表形式返回。
    lists = os.listdir(test_dir)
    # sort按key的关键字进行排序,lambda的入参fn为lists列表的元素,获取文件的最后修改时间
    # 最后对lists元素,按文件修改时间大小从小到大排序。
    if run_os == 'linux':
        lists.sort(key=lambda fn: os.path.getmtime(test_dir + '/' + fn))    # linux
    else:
        lists.sort(key=lambda fn: os.path.getmtime(test_dir + '\\' + fn))     # windows
    # 获取最新文件的绝对路径
    file_path = os.path.join(test_dir, lists[-1])
    return file_path


# 3.定义:发送邮件,发送最新测试报告html
def send_email(newfile):
    try:
        # 打开文件
        f = open(newfile, 'rb')
        # 读取文件内容
        mail_body = f.read()
        # 关闭文件
        f.close()
        # 发送邮箱服务器
        import configparser
        if run_os == 'linux':
            config_file = os.path.abspath('.') + '/Config/config.ini'  # linux 运行全部接口
        else:
            config_file = os.path.abspath('.') + '\\Config\\config.ini'  # windows 运行全部接口
        # print "config_file :" + str(config_file)
        config = configparser.ConfigParser()
        config.read_file(open(config_file, encoding='UTF-8'))
        user = config.get("SENDER", "user")
        password = config.get("SENDER", "password")
        smtpserver = config.get("SENDER", "smtpserver")
        sender = config.get("SENDER", "sender")
        receiver = config.get("RECEIVER", "receiver")
        subject = config.get("MSG", "subject")
        # 发送邮件主题
        # subject = '自动定时测试报告(生产api)'+now
        msg = MIMEMultipart('mixed')
        msg_html1 = MIMEText(mail_body, 'html', 'utf-8')
        msg.attach(msg_html1)
        msg_html = MIMEText(mail_body, 'html', 'utf-8')
        msg_html["Content-Disposition"] = 'attachment; filename="TestReport.html"'
        msg.attach(msg_html)
        msg['From'] = sender
        # 多个收件人
        msg['To'] = receiver
        msg['Subject'] = Header(subject, 'utf-8')
        # 连接发送邮件
        # 2.7版本不需要往SMTP()里面加实参
        smtp = smtplib.SMTP_SSL(smtpserver)
        smtp.connect(smtpserver, 465)
		#smtp.ehlo()
		# smtp.starttls()
        smtp.login(user, password)
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
    except Exception as e:
        print(e)


# 4.查找报告中是否有failtest(ft),find找不到则返回-1
def parse_html(new_report):
    from bs4 import BeautifulSoup
    with open(new_report, 'r', encoding='utf-8') as wb_data:
        soup = BeautifulSoup(wb_data, 'html.parser')
    return str(str(soup).find('id="ft'))


if __name__ == '__main__':
    try:
        # 1.执行测试用例,生成最新的测试用例
        now = time.strftime('%Y-%m-%d_%H_%M_%S')

        test_dir = os.path.abspath('./TestCase')
        print(test_dir)
        discover = unittest.defaultTestLoader.discover(test_dir, pattern='test_*.py')
        # 测试报告的路径
        if run_os == 'linux':
            test_report_dir = os.path.abspath('.') + '/Report'  # linux
            filename = test_report_dir + '/' + now + '_result.html'
        else:
            test_report_dir = os.path.abspath('.') + '\\Report'  # windows
            filename = test_report_dir + '\\' + now + '_result.html'
        fp = open(filename, 'wb')
        runner = HTMLTestRunner(stream=fp, title=u'测试报告', description=u'用例执行情况:')
        runner.run(discover)
        fp.close()
    # 2.取最新测试报告
        new_report = new_file(test_report_dir)
        print("测试报告路径:%s" % new_report)

    # 3.如果有运行失败的case,发送邮件,发送最新测试报告html
        if parse_html(new_report) != "-1":
            send_email(new_report)
            print("Email sent successfully...")
        elif parse_html(new_report) == "-1":
            print("All passed, no need to send email...")

    except Exception as e:
        print(e)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值