019 python接口 报告 + 邮件

'''
时间:2020/10/27
功能:断言与报告
目录:
    一: 目录
        1 缩进目录
        2 完整目录
    二: 具体内容  
        1 case: test_qq_api.py
        2 case: test_integer_arithmetic.py
        3 run_all_case.py
    三: 报告展示
四: 完整内容
'''


一: 目录
  1 缩进目录

  2 完整目录

二: 具体内容
  1 case: test_qq_api.py

#coding:utf-8
import requests
import unittest

class TestQQ(unittest.TestCase):
    ''' 测试QQ接口 '''
    # key - 正确
    def test_qq_right_key(self):
        url = "http://japi.juhe.cn/qqevaluate/qq"
        par = {
            "key": "980bf619855953f6ebef9abe90d52712",
            "qq": "384056521"
        }
        r = requests.get(url, params=par)
        res = r.json()
        self.assertTrue(res["reason"] == "success")
        self.assertTrue(res["error_code"] == 0)
        self.assertTrue(res["result"] != [])

    # key - 错误
    def test_qq_error_key(self):
        url = "http://japi.juhe.cn/qqevaluate/qq"
        par = {
            "key": "123456789", # 错误的key
            "qq": "1812436356"
        }
        r = requests.get(url, params=par)
        res = r.json()
        self.assertTrue(res["reason"] == "KEY ERROR!")
        self.assertTrue(res["error_code"] == 10001)
        self.assertTrue(res["result"] == [])


if __name__ == "__main__":
    unittest.main()

  2 case: test_integer_arithmetic.py

#coding:utf-8
import requests
import unittest

class IntegerArithmeticTest(unittest.TestCase):
    # def setUp(self):
    #     print("setUP start")
    # def tearDown(self):
    #     print("tearDown start")
    #
    # @classmethod
    # def setUpClass(cls):
    #     print("setUpClass")
    # @classmethod
    # def tearDownClass(cls):
    #     print("tearDownClass")

    def testAdd(self):
        # print("testAdd strat")
        self.assertEqual((1 + 2), 5)
        self.assertEqual((0 + 1), 1)
    def testMultiply(self):
        # print("testMultiply strat")
        self.assertEqual((0 * 10), 0)
        self.assertEqual((5 * 6), 30)
    def testSubtraction(self):
        # print("testSubtraction strat")
        self.assertEqual((0 - 5), -5)
        self.assertEqual((1 - 5), -4)

if __name__ == "__main__":
    unittest.main()

  3 run_all_case.py

# coding:utf-8
import unittest
import os
import time
from common import html_report
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

cur_path = os.path.dirname(os.path.realpath(__file__))


def add_case(case_name = "case", rule = "test*.py"):
    '''第一步: 加载测试用例 '''
    case_path = os.path.join(cur_path, case_name)
    # 如果不存在case文件夹,就创建
    if not os.path.exists(case_path):
        os.mkdir(case_path)
    print("test case path:%s" %case_path)

    # 定义参数 - discover
    discover = unittest.defaultTestLoader.discover(case_path,
                                                   pattern = rule,
                                                   top_level_dir=None)
    print(discover)
    return discover

def run_case(all_case, report_name = "report"):
    '''第二步: 执行用例'''
    now = time.strftime("%Y_%m_%d_%H_%M_%S")
    report_path = os.path.join(cur_path, report_name)

    # 如果不存在report文件夹,就创建
    if not os.path.exists(report_path):
        os.mkdir(report_path)
    report_abspath = os.path.join(report_path, "report.html")
    print("report path: %s"%report_abspath)

    fp = open(report_abspath, "wb")
    runner = html_report.HTMLTestRunner(stream = fp,
                                        title = u"自动化测试用例报告",
                                        description = u"用例执行情况")

    # 调用add_case, 返回值
    runner.run(all_case)
    fp.close()

def get_report_file(report_path):
    '''第三步: 获取最新的测试报告 '''
    lists = os.listdir(report_path)
    lists.sort(key = lambda fn: os.path.getmtime(os.path.join(report_path, fn)))
    print(u"最新测试报告: " + lists[-1])

    # 找到最新报告
    report_file = os.path.join(report_path, lists[-1])
    return report_file

def send_mail(sender, psw, receiver, smtpserver, report_file, port):
    '''第四步: 发送最新测试报告'''
    with open(report_file, "rb") as f:
        mail_body = f.read()

    # 定义邮件内容
    msg = MIMEMultipart()
    body = MIMEText(mail_body, _subtype="html", _charset="utf-8")
    msg['Subject'] = u"自动化测试报告"
    msg["from"] = sender

    if isinstance(receiver, list):
        msg["to"] = ",".join(receiver)
    else:
        msg["to"] = receiver
    msg.attach(body)

    # 添加邮件
    att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename="report.html" '
    msg.attach(att)
    try:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)    # 连接服务器
        smtp.login(sender, psw)
    except:
        smtp = smtplib.SMTP_SSL(smtpserver, port)
        smtp.login(sender, psw)        # 登录
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
    print("Test report email has send out !")

    
if __name__ == "__main__":
    # 1 加载用例
    all_case = add_case()

    # 2 执行用例
    run_case(all_case)

    # 3 获取报告 - 最新报告
    report_path = os.path.join(cur_path, "report")
    report_file = get_report_file(report_path)

    # 4 邮箱配置
    sender = "384056521135@qq.com"    # 发送邮箱
    psw = "tsrpkljzdvzrbifekk"    # 授权码
    smtp_server = "smtp.qq.com"    # 邮箱服务器
    port = 465                    # 端口号
    receiver = ["1812436356135@qq.com"]    # 接受邮箱

    # 5 发送邮件
    send_mail(sender, psw, receiver, smtp_server, report_file, port)

三: 报告展示

四: 完整内容

  压缩包: 链接

原文地址:https://www.cnblogs.com/huafan/p/13884362.html