for key, value in step_assert.items(): for key1, value1 in value.items(): try: # 使用缓存结果或进行查询 result = result_cache.get(key, jsonpath.jsonpath(param, key)) result_cache[key] = result # 更新缓存
defset_variable(step_jsonpath: dict, step_body: dict, variable: dict=VARIABLE) -> dict: """ 提取变量并更新给定的变量字典 :param step_jsonpath: 包含变量名和对应JSON路径的字典 :param step_body: 待提取变量的JSON结构体 :param variable: 用于存储提取变量的字典 :return: 更新后的变量字典 :raises ValueError: 当step_jsonpath或step_body的格式不正确时 :raises IndexError: 当jsonpath查询结果为空列表且尝试访问第一个元素时 """ # 输入验证 ifnotisinstance(step_jsonpath, dict): raise ValueError("step_jsonpath must be a dictionary") ifnotisinstance(step_body, dict): raise ValueError("step_body must be a dictionary") ifnotisinstance(variable, dict): raise ValueError("variable must be a dictionary")
try: # 更新变量字典 for key, value in step_jsonpath.items(): # jsonpath查询并更新变量 result = jsonpath.jsonpath(step_body, value) if result: variable[key] = result[0] else: # 如果查询结果为空,可以考虑记录日志、抛出异常或其他处理方式 print(f"Warning: JSON path '{value}' did not match any value.") except Exception: raise ValueError(f"JSON path '{value}' error.")
defset_variable(step_jsonpath: dict, step_body: dict, variable: dict = VARIABLE) -> dict: """ 提取变量并更新给定的变量字典 :param step_jsonpath: 包含变量名和对应JSON路径的字典 :param step_body: 待提取变量的JSON结构体 :param variable: 用于存储提取变量的字典 :return: 更新后的变量字典 :raises ValueError: 当step_jsonpath或step_body的格式不正确时 :raises IndexError: 当jsonpath查询结果为空列表且尝试访问第一个元素时 """ # 输入验证 ifnotisinstance(step_jsonpath, dict): raise ValueError("step_jsonpath must be a dictionary") ifnotisinstance(step_body, dict): raise ValueError("step_body must be a dictionary") ifnotisinstance(variable, dict): raise ValueError("variable must be a dictionary")
try: # 更新变量字典 for key, value in step_jsonpath.items(): # jsonpath查询并更新变量 result = jsonpath.jsonpath(step_body, value) if result: if key == 'token': variable[key] = "Bearer " + result[0] variable[key] = result[0] else: # 如果查询结果为空,可以考虑记录日志、抛出异常或其他处理方式 print(f"Warning: JSON path '{value}' did not match any value.") except Exception: raise ValueError(f"JSON path '{value}' error.")
return variable
封装变量替换方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defreplace_variable(step_obj:'StepInfo'): """ 替换变量 :param step_obj: :return: """ for attr_name indir(step_obj): # 使用 dir 获取属性的值,注意过滤掉特殊方法(以__开头和结尾的) ifnot attr_name.startswith("__") andnot attr_name.endswith("__"): data=json.dumps(getattr(step_obj, attr_name))#将属性值转换为字符串 variable_list = re.findall(r'<(.*?)>',data) # 获取所有变量名 for i in variable_list: try: data = data.replace('<' + i + '>', VARIABLE[i]) # 替换变量值 except KeyError: raise ValueError(f"变量 {i} 在变量字典中不存在,请检查变量名是否正确。") setattr(step_obj,attr_name,json.loads(data))#将替换后的字符串转换为字典