parameterize.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import json
  2. import traceback
  3. import yaml
  4. from common.yaml_util import read_data_yaml, get_project_path
  5. from common.log_util import error_log
  6. # 读取测试用列
  7. def read_testcase(yaml_path):
  8. try:
  9. # with open(get_project_path() + yaml_path, mode='r', encoding='utf-8') as f:
  10. with open(yaml_path, mode='r', encoding='utf-8') as f:
  11. arg_names = yaml.load(stream=f, Loader=yaml.FullLoader)
  12. if len(arg_names) >= 2:
  13. return arg_names
  14. else:
  15. if "parameterize" in dict(*arg_names).keys():
  16. new_arg_names = ddt(*arg_names)
  17. return new_arg_names
  18. else:
  19. return arg_names
  20. except Exception as e:
  21. error_log("读取测试用例方法read_testcase异常:%s" % str(traceback.format_exc()))
  22. def ddt(arg_names):
  23. # 新方法
  24. try:
  25. arg_names_str = json.dumps(arg_names)
  26. data_list = arg_names["parameterize"]
  27. key_length = len(data_list[0])
  28. # print(key_length)
  29. length_success = True
  30. # 循环数据
  31. for param in arg_names["parameterize"]:
  32. if len(param) != key_length:
  33. length_success = False
  34. error_log("此条数据有误:%s" % param)
  35. # 替换值
  36. new_art_names = []
  37. if length_success:
  38. for x in range(1, len(data_list)):
  39. # print(data_list[x])
  40. temp_arg_names = arg_names_str
  41. for y in range(0, len(data_list[x])):
  42. if isinstance(data_list[x][y], int) or isinstance(data_list[x][y], float):
  43. temp_arg_names = temp_arg_names.replace('"$ddt{' + data_list[0][y] + '}"', str(data_list[x][y]))
  44. else:
  45. temp_arg_names = temp_arg_names.replace("$ddt{" + data_list[0][y] + "}", str(data_list[x][y]))
  46. new_art_names.append(json.loads(temp_arg_names))
  47. # print(new_art_names)
  48. return new_art_names
  49. except Exception as e:
  50. error_log("数据驱动ddt异常:%s" % str())