当前位置: 首页 > news >正文

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

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

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

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

2 params  对应requests的params

3 data,对应requests的data

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

baseapi.py

#-*-coding:utf-8-*-
"""
接口基类
dinghanhua
baseapi.py
"""import requests
from requests.cookies import RequestsCookieJarclass 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) #更新cookiesif encoding: # 如果有响应编码则配置编码response.encoding = encodingresult = response.textreturn result

runtest.py

#-*-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和sheetbook = xlrd.open_workbook(excelpath)  # 打开exceltry:sheet = book.sheet_by_index(sheetindex)  # 读取sheetwb = 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:passtry:data = eval(data)except:passtry:headers = eval(headers)except:passactual_result = testapi.response_text(method=method,url=url,params=params,data=data,encoding=encoding,headers=headers) # 获取响应if re.search(checkpoint,actual_result):  #测试通过写excel ; 测试通过计数加1wsheet.write(row,10,'pass')success += 1logging.info(label+'test pass')else:  #测试不通过写excel ; 测试不通过计数加1wsheet.write(row,10,'fail')wsheet.write(row,11, actual_result)  # 写入响应fail += 1logging.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写好用例直接执行。脚本中的检查点等可根据实际项目再调整。

http://www.lryc.cn/news/114701.html

相关文章:

  • 【flink】Chunk splitting has encountered exception
  • 单元测试用例分组 demo
  • 观察者模式(Observer)
  • 20天学会rust(二)rust的基础语法篇
  • Stephen Wolfram:嵌入的概念
  • springboot,swagger多个mapper包,多个controller加载问题
  • 湖大CG满分教程:作业训练四编程题20. 回文串(暴力×动态规划算法√)
  • 使用toad库进行机器学习评分卡全流程
  • Python数据容器——列表(list)
  • Linux CEF(Chromium Embedded Framework)源码下载编译详细记录
  • Adaptive AUTOSAR—— Communication Management 3.1
  • VMnet0 桥接设置
  • Sublime Text 4 Build 4151 4152 发布及注册方法
  • 第八篇: K8S Prometheus Operator实现Ceph集群企业微信机器人告警
  • 软件单元测试
  • Redis | 集群模式
  • 8.3day04git+数据结构
  • 04-5_Qt 5.9 C++开发指南_QComboBox和QPlainTextEdit
  • Sqlserver_Oracle_Mysql_Postgresql不同关系型数据库之主从延迟的理解和实验
  • Clickhouse学习系列——一条SQL完成gourp by分组与不分组数值计算
  • 做好“关键基础设施提供商”角色,亚马逊云科技加快生成式AI落地
  • 如何使用 ChatGPT 规划家居装修
  • 题解 | #1002.Random Nim Game# 2023杭电暑期多校7
  • 篇九:组合模式:树形结构的力量
  • 【注册表】windows系统注册表常用修改方案
  • ant-design-vue 4.x升级问题-样式丢失问题
  • 【果树农药喷洒机器人】Part3:变量喷药系统工作原理介绍
  • GoogLeNet创新点总结
  • 不同路径1、2、3合集(980. 不同路径 III)
  • 【云原生】Yaml文件详解