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

创建在文件夹的第一级,命名为run_all_case.py。
运行整个项目的时候,只需要 python run_all_case.py就能完美运行用例,取最新报告并发送邮件。

# -*- 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 = 'win'


# 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(smtpserver)
        smtp.connect(smtpserver, 25)
        smtp.ehlo()
        smtp.starttls()
        smtp.login(user, password)
        smtp.sendmail(sender, receiver, msg.as_string())
        smtp.quit()
    except Exception as e:
        print(e)


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

        test_dir = os.path.abspath('.')
        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.发送邮件,发送最新测试报告html
    #     send_email(new_report)
    except Exception as e:
        print(e)

你可能感兴趣的:(自动化测试,接口,单元测试)