知识点拓展:
eval
:eval这个函数,会自动按你的数据格式,格式化掉对应的数据()[]{}
接口测试Excel文档:测试用例.xls
图片.png
全局变量文件:global_value.py
# 全局变量
class g_var(object):
_global_dict = {} #最大程度保证这个字典不被污染
def set_dict(self, key, value):
self._global_dict[key] = value
def get_dict(self,key):
return self._global_dict[key]
def show_dict(self):
return self._global_dict
运行文件:Test_framework.py文件代码:
import pytest,requests,jsonpath
# 导入xToolkit读取 excel
from xToolkit import xfile
#Template会自动替换字典中${}的同名变量
from string import Template
#调用全局变量
from api.global_value import g_var
# xToolkit:---------------------读取 excel 文件内容---------------------------
# xToolkit读取 excel 文件数据,只能.xls,不支持.xlsx
excel_file = xfile.read("测试用例.xls").excel_to_dict(Sheet=1)
print("xToolkit读取.xlsx:\n",excel_file)
# 接收 excel 数据
#--------------------------------------自动循环 DDT---------------------------
#pytest 有一个对应的方法 参数化机制
#自动循环 DDT
@pytest.mark.parametrize("case_info",excel_file)
def test_case_exec(case_info):#把这个列表传进来
url = case_info["接口URL"]
dic = g_var().show_dict()
if "$" in url :
url = Template(url).substitute(dic)
rep = requests.request(
url = url,
method = case_info["请求方式"],
params=eval(case_info["URL参数"]),#eval这个函数,会自动按你的数据格式,格式化掉对应的数据()[]{}
data=eval(case_info["JSON参数"])
)
#------------------------数据写入到对象中去----------------------
print("--------请求接口为:",case_info["用例编号"],"---",case_info["描述"])
print("返回数据:",rep.json())
if case_info['提取参数'] != None or case_info['提取参数'] !='':
# 使用jsonpath,提取 token参数值,需要case_info['提取参数']值没有空格!,所以 excel 只能靠左,不能居中或局右,如果不想被空格干扰,需处理
# 去掉字符串两端的空格strip()
tiqucanshu = format(case_info['提取参数']).strip()
print("-------提取参数"+tiqucanshu)
lst = jsonpath.jsonpath(rep.json(),'$..'+tiqucanshu)
g_var().set_dict(case_info['提取参数'],lst[0])
# ---------------------添加断言-----------------
#断言
assert rep.status_code == case_info["预期状态码"]
if __name__ == "__main__":
pytest.main(["-vs","--capture=sys"])#pytest的启动命令