- 判断是否为ddt数据
python
def read_testcase(yaml_path):
with open(yaml_path,encoding="utf-8") as f:
case_list = yaml.safe_load(f)
if "parametrize" in dict(*case_list).keys(): # 读取出来的yaml用例带有parametrize就说明是ddt用例,格式为:[{}]
new_caseinfo = ddt(*case_list)
return new_caseinfo # 将数据解包后,返回格式为:[{},{}]
else:
return case_list
- 处理数据
python
def ddt(caseinfo:dict):
data_list = caseinfo["parametrize"] # 获取到caseinfo下的parametrize数据
len_flag = True # 设置一个判断指标
name_len = len(data_list[0]) # 获取参数的长度,即有几个参数
for data in data_list:
if len(data) != name_len: # 判断获取到的所有的参数长度是否与name_len一致,不一致直接结束
len_flag = False
print("parametrize数据长度不一致")
break
# 将caseinfo转为str类型方便后续操作
str_caseinfo = yaml.dump(caseinfo)
new_caseinfo = []
if len_flag: # 当长度一致时,进行后续操作
for x in range(1,len(data_list)): # 从下标为1开始取行数据,即排除数据名称行后的就是用例数据行
raw_caseinfo = str_caseinfo
for y in range(0,name_len): # 从下标为0开始取列数据,即长度有多少就去多少列
# 处理数字类型的字符串数据
if isinstance(data_list[x][y],str) and data_list[x][y].isdigit():
data_list[x][y] = "'" + data_list[x][y] + "'" # 转为字符串类型的数字
raw_caseinfo = raw_caseinfo.replace("$ddt{"+data_list[0][y]+"}",str(data_list[x][y])) # 将获取到的数据写入
case_list = yaml.safe_load(raw_caseinfo) # 再次进行数据转换回list
case_list.pop("parametrize")
new_caseinfo.append(case_list)
return new_caseinfo
- yaml用例中设置和使用数据
python
-
feature: 测试模块4
story: 测试接口4
title: 验证测试接口4正常返回
request:
method: post
url: http://192.168.0.1/phpwind/index.php?m=u&c=login&a=dorun
data:
username: $ddt{username}
password: $ddt{password}
parametrize:
- [ "username","password" ]
- [ "ces1","123" ]
- [ "ces2",123 ]
- [ "ces","ces" ]