接口测试框架

在这里插入图片描述
本文中只讲到 测试用例 - 用例读取器 - 用例解析器 - 核心运行器 - 结果分析器 - 报告 - 通知

在一个exexl中存放测试用例,通过unittest进行用例读取、解析,并生成测试报告,将报告以邮件形式发送给接收者。
API接口:https://www.sojson.com/blog/234.html(感谢博主提供的免费天气查询的API)

建立一个项目test_API
新建如下文件夹,各文件夹作用如下:
case : 存放写有测试用例的execl表
execl : 读取execl的文件
httpop : 通过requests.get获取API数据
report : 生成测试报告
mail : 发送邮件
test : 自动化测试模块

在这里插入图片描述
execl表中数据:
在这里插入图片描述

代码:

test/my_test.py

import unittest
import json
import jsonpath
from httpop.httpop import httpop
from execl.execlop import execlop


class Mytestcase(unittest.TestCase):

    listcheacklist = []
    def setUp(self):
        Mytestcase.listcheacklist = execlop().execlread()
       
    def test_checklist3(self):
        for checklist in Mytestcase.listcheacklist:
            url = checklist[0]
            expect = str(checklist[2]) #将execl中存放的数字转换成字符
            jsondir = checklist[3]


            res = httpop().api_get(url)
            res_json = json.loads(res.content)
            result = jsonpath.jsonpath(res_json, jsondir)#返回的是一个列表
            print(res_json)
            self.assertEqual(expect,result[0])

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

execl/execlop.py

from openpyxl import load_workbook
import os
class execlop:
    def execlread(self):
        listcheacklist = []
        pathdir = os.path.dirname(__file__)  # 当前文件夹的路径
        path = pathdir + '/../case/case.xlsx'  # /../返回到上一级目录  path = G:/py_study/test_API_learning/case/case.xlsx
        work_book = load_workbook(path)
        # work_book = load_workbook(r'../case/case.xlsx') #在IDE中与前三行起的作用相同,可替代前三行代码;在CMD中因为运行路径问题会报错,所以需要使用前三行代码
        sheet = work_book['Sheet1']
        rows_sheet = sheet.iter_rows()

        for item in rows_sheet:
            if item[0].value == 'url':  # item是单元格对象,item[0].value是A1单元格中的值
                continue
            list = []
            for col in item:
                list.append(col.value)
            listcheacklist.append(list)
        return listcheacklist

httpop/httpop.py

import requests

class httpop:
    def api_get(self,url):
        res = requests.get(url)
        return res

report/report.py

from HTMLTestRunner import HTMLTestRunner
import unittest
from datetime import datetime
from mail.sendmail import sendmail
class report:
    def toReport(self):
        #加载测试文件
        dir_path = '../test'
        discover = unittest.defaultTestLoader.discover(dir_path, pattern = '*.py') #找到test文件夹里所有.py文件(执行测试的文件)

        #测试报告的文件名,用时间戳做文件名比较好区分
        time = datetime.now()
        now = time.strftime('%Y-%m-%d %H-%M-%S')
        report_path = now + 'result.html' #测试报告文件名

        #定义 HTMLTestRunner 测试报告,stream 定义报告所写入的文件;title 为报告的标题;description 为报告的说明与描述
        with open(report_path, 'wb') as f:
            #verbosity:=1时,默认值为1,不限制完整结果,即单个用例成功输出’.’, 失败输出’F’, 错误输出’E’;=0的时候,不输出信息;=2
            #的时候,需要打印详细的返回信息
            runner = HTMLTestRunner(stream = f, verbosity = 2, title = '接口测试报告', description = '用例执行报告')
            runner.run(discover)#运行测试容器中的用例,并将结果写入的报告中

        f.close()#关闭文件流,将HTML内容写进测试报告文件

        sendmail().send_mail(report_path) #发送测试邮件
if __name__ == '__main__':
    report().toReport()

报告详情:
在这里插入图片描述

mail/sendmail.py

import smtplib
from email.mime.text import MIMEText

class sendmail:
    def send_mail(self, path):
        #读测试报告
        f = open(path, 'rb')
        mail_body = f.read()
        f.close()

        #设置邮箱
        '''
        465端口(SMTPS):465端口是为SMTPS(SMTP-over-SSL)协议服务开放的,这是SMTP协议基于SSL安全协议之上的一种变种协议,
        它继承了SSL安全协议的非对称加密的高度安全可靠性,可防止邮件泄露。SMTPS和SMTP协议一样,也是用来发送邮件的,只是更安全些,
        防止邮件被黑客截取泄露,还可实现邮件发送者抗抵赖功能。防止发送者发送之后删除已发邮件,拒不承认发送过这样一份邮件。
        '''
        host = 'smtp.163.com'
        port = 465
        sender = '#########@163.com' #改成合法邮箱
        pwd = '###########' #邮箱授权码,可见https://jingyan.baidu.com/article/495ba841ecc72c38b30ede38.html
        receiver = '##############'

        #设置邮件内容
        msg = MIMEText(mail_body, 'HTML', 'UTF-8')
        msg['subject'] = 'API测试报告发送'
        msg['from'] = sender
        msg['to'] = receiver

        #做连接
        s = smtplib.SMTP_SSL(host, port)
        s.login(sender, pwd)
        s.sendmail(sender, receiver, msg.as_string())

邮件详情:
在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐