1、定义csv文件
name,username,password 输入正确的用户名和密码,USERNAME,PASSWORD 输入错误的用户名和密码,USERNAME1,PASSWORD1
2、在Yaml文件中以$csv{}格式写
注意:name-username-password: username.csv(csv文件路径)
- parameters: name-username-password: username.csv name: $csv{name} request: json: username: $csv{username} password: $csv{password}
3、定义读取csv, 将$csv{}标记出的值,替换成csv表格中的值,最后读取yaml文件时返回
import json from typing import Text, Dict, Union, List import yaml import jsonpath import csv # 读取csv文件 def read_csv_file(csv_path: Text) -> List: """ :param csv_path: csv路径 :return: """ csv_data_list = [] with open(csv_path, mode="r", encoding="utf-8-sig") as file: csv_data = csv.reader(file) for row in csv_data: csv_data_list.append(row) return csv_data_list # 读取测试用例使用该方法,以前的读取方法在这个方法中调用和解析 def read_testcase_yaml(yaml_path: Text) -> Union[Dict, List]: """ :param yaml_path: 测试用例文件 :return: """ with open(yaml_path, mode="r", encoding="utf-8") as file: args = yaml.load(file, Loader=yaml.FullLoader) # 当yaml文件大于等于两个字典的时候,不进行csv数据驱动 if len(args) >= 2: return args else: # 判断用例中是否有csv关键字"parameters" if jsonpath.jsonpath(*args, '$.parameters'): new_args = analysis_parameters(*args) return new_args else: return args # 分析参数化 def analysis_parameters(args: Union[List, Dict]) -> Union[List, Dict]: args_keys = dict(args).keys() if "parameters" in args_keys: args_str = str(eval(json.dumps(args).replace('null', '" "'))) for key, value in dict(args['parameters']).items(): key_list = str(key).split("-") # 规范csv的数据的写法 length_flag = True csv_data_list = read_csv_file(value) one_row_csv_data = csv_data_list[0] for csv_data in csv_data_list: if len(csv_data) != len(one_row_csv_data): length_flag = False break # 解析 new_args = [] if length_flag is True: # row代表行,column代表列 for row in range(1, len(csv_data_list)): temp_args = args_str # 保持args_str数据不变 for column in range(0, len(csv_data_list[row])): if csv_data_list[0][column] in key_list: temp_args = temp_args.replace("$csv{" + csv_data_list[0][column] + "}", csv_data_list[row][column]) new_args.append(eval(temp_args)) # 使用eval将temp_args字符串转换回字典格式 return new_args else: return args
4、main函数演示读取结果
from userUtil import read_testcase_yaml if __name__ == '__main__': args = read_testcase_yaml("user.yaml") print(args)
5、执行结果
[{'parameters': {'name-username-password': 'username.csv'}, 'name': '输入正确的用户名和密码', 'request': {'json': {'username': 'USERNAME', 'password': 'PASSWORD'}}}, {'parameters': {'name-username-password': 'username.csv'}, 'name': '输入错误的用户名和密码', 'request': {'json': {'username': 'USERNAME1', 'password': 'PASSWORD1'}}}]