用excel格式书写的接口用例执行脚本

创建测试用例和测试结果集文件夹:

excel编写的接口测试用例如下:

1 encoding 响应的编码格式。所测项目大部分是utf-8,有一个特殊项目是utf-8-sig

2 params 对应requests的params

3 data,对应requests的data

有些参数是动态的:写参数名,程序中用eval()函数转化

baseapi.py

python 复制代码
#-*-coding:utf-8-*-
"""
接口基类
dinghanhua
baseapi.py
"""

import requests
from requests.cookies import RequestsCookieJar


class apitest:
    def __init__(self):
        self.cookies = RequestsCookieJar()

    def response_text(self,method,url,encoding='utf-8',**kwargs):
        """请求函数"""
        response = requests.request(method,url,cookies=self.cookies,**kwargs)

        self.cookies.update(response.cookies) #更新cookies

        if encoding: # 如果有响应编码则配置编码
            response.encoding = encoding
        result = response.text

        return result

runtest.py

python 复制代码
#-*-coding:utf-8-*-
"""
读取excel用例并执行
dinghanhua
"""

import xlrd
from xlutils.copy import copy
from baseapi import apitest
import datetime
import os
import re
import logging;logging.basicConfig(level=logging.INFO)


def run_testcase(excelpath,sheetindex=0):

    # region 读取excel和sheet
    book = xlrd.open_workbook(excelpath)  # 打开excel
    try:
        sheet = book.sheet_by_index(sheetindex)  # 读取sheet
        wb = copy(book)  # 转变成xlwt book对象
        wsheet = wb.get_sheet(sheetindex)
    except IndexError:
        logging.info("读取的sheet不存在")
        raise IndexError("读取的sheet不存在")
    #endregion

    # region 读取和运行用例
    testapi = apitest()
    fail = 0 # 用例执行失败个数
    success = 0 # 用例执行成功个数
    for row in range(1, sheet.nrows):
        isrun = str(int(sheet.cell_value(row,8))).strip() # 是否运行
        if isrun == '1': # 判断用例是否运行;运行则读取其他字段
            label = str(sheet.cell_value(row, 1)).strip()
            method = str(sheet.cell_value(row,2)).strip()
            url = str(sheet.cell_value(row, 3)).strip()
            encoding = str(sheet.cell_value(row, 4)).strip()
            headers = str(sheet.cell_value(row, 5)).strip()
            params = str(sheet.cell_value(row, 6)).strip()
            data = str(sheet.cell_value(row, 7)).strip()
            checkpoint = str(sheet.cell_value(row, 9)).strip()

            try:
                params = eval(params)  # 参数转变 从字符串转变成字典或带入参数;转变不了则不处理
            except:
                pass

            try:
                data = eval(data)
            except:
                pass

            try:
                headers = eval(headers)
            except:
                pass

            actual_result = testapi.response_text(method=method,url=url,params=params,data=data,encoding=encoding,headers=headers) # 获取响应

            if re.search(checkpoint,actual_result):  #测试通过写excel ; 测试通过计数加1
                wsheet.write(row,10,'pass')
                success += 1
                logging.info(label+'test pass')
            else:  #测试不通过写excel ; 测试不通过计数加1
                wsheet.write(row,10,'fail')
                wsheet.write(row,11, actual_result)  # 写入响应
                fail += 1
                logging.info("%s test fail.检查点:%s,响应结果:%s"%(label,checkpoint,actual_result))
    # endregion

    # region 保存测试结果
    filepath = os.path.join(os.path.dirname(__file__),'testresult') # 测试结果目录
    if not os.path.exists(filepath): # 目录不存在则创建
        os.mkdir(filepath)
    filename = os.path.join(filepath,datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')+'.xls') # 测试结果文件
    wb.save(filename) # 保存文件
    logging.info('测试结果:测试通过%s,测试不通过%s。测试结果文件路径:%s'%(success,fail,filename))
    # endregion



#执行测试用例

# 测试要用的动态参数
nowtime = datetime.time().strftime('%Y%m%d%H%M%S%f') # 时间戳
today = str(datetime.date.today()) # 当前日期
newdate = (datetime.datetime.now()-datetime.timedelta(minutes=30)).strftime('%Y-%m-%d %H:%M:%S') # 当前时间点前半小时
sso = "test" # sso串
id = 1 # id
token = 'token' # token,通过抓包获取


excelpath = r'C:\Users\dinghanhua\PycharmProjects\ApiTest\testcase\testcase1.xlsx' # excel用例文件
run_testcase(excelpath=excelpath,sheetindex=1) # 逐条读取并运行用例

运行之后testresult文件夹下查看已生成的测试结果文件,文件名=测试运行时间戳

该项目用jmeter、postman也可以做接口测试。用python脚本可以用excel写好用例直接执行。脚本中的检查点等可根据实际项目再调整。

相关推荐
你好龙卷风!!!5 小时前
SpringCloud,vue3应用使用AlibabaCloudToolkit自动化部署到远程服务器上的docker
云原生·自动化
未来之窗软件服务10 小时前
万象EXCEL开发(十一)excel 结构化查询 ——东方仙盟金丹期
excel·仙盟创梦ide·东方仙盟·万象excel
小熊出擊14 小时前
【pytest】finalizer 执行顺序:FILO 原则
python·测试工具·单元测试·pytest
旗讯数字14 小时前
企业OCR实战:基于OCR技术实现双节差旅报销单表格解析与文字信息自动化采集
运维·自动化·ocr·表格识别
云闲不收15 小时前
接口请求工具对比 apifox apipost swagger postman等
测试工具·postman
梁萌16 小时前
自动化测试框架playwright使用
自动化测试·python·ui自动化·playwright
墨染点香19 小时前
LeetCode 刷题【103. 二叉树的锯齿形层序遍历、104. 二叉树的最大深度、105. 从前序与中序遍历序列构造二叉树】
算法·leetcode·职场和发展
zzywxc78719 小时前
AI 在金融、医疗、教育、制造业等领域都有广泛且深入的应用,以下是这些领域的一些落地案例
人工智能·金融·自动化·prompt·ai编程·xcode
sitellla20 小时前
Testify Go测试工具包入门教程
git·测试工具·其他·golang
黑色的山岗在沉睡21 小时前
LeetCode 2761. 和等于目标值的质数对
算法·leetcode·职场和发展