用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写好用例直接执行。脚本中的检查点等可根据实际项目再调整。

相关推荐
lzhdim3 分钟前
SQL 入门 14:SQL 触发器与事件:自动化数据处理
linux·前端·数据库·sql·自动化
CHENKONG_CK1 小时前
工业 RFID 技术在发动机气缸缸体生产中的落地应用
自动化·制造·rfid
Black蜡笔小新2 小时前
自动化AI算法训练服务器DLTM深度学习推理工作站AI赋能质检助力制造业智能化转型
人工智能·算法·自动化
凯瑟琳.奥古斯特2 小时前
页面置换算法详解与对比
开发语言·分布式·职场和发展
BestHeaker3 小时前
CC Switch 全能使用教程
后端·职场和发展·跳槽·学习方法
测试_AI_一辰3 小时前
AI时代,学东西的方式变了
人工智能·ai·自动化·状态模式·ai编程
折哥的程序人生 · 物流技术专研3 小时前
Java面试85题图解版 · 全系列总目录
java·开发语言·后端·面试·职场和发展
广州创科水利3 小时前
精准监测守护边坡安全!广州创科深圳两大森林公园边坡 GNSS 自动化监测项目
人工智能·安全·自动化·边坡
call me by ur name4 小时前
polymarket_api文档_概览
自动化
Android出海4 小时前
2026年Codex新手教程:安装、使用与自动化实战指南
人工智能·ai·chatgpt·自动化·脚本·codex·自动化脚本