Robot Framework中如何实现多份JSON数据按指定规则比对校验
Robot Framework JSON属性比对实现方案
完全可以实现该需求,只需在现有依赖基础上引入Robot Framework自带的Collections库即可,无需额外安装第三方组件。
核心实现逻辑
对应你提出的两个处理步骤:
- 构造result_A:遍历从json_A提取的Properties属性列表,逐个判断键是否存在于json_B转换的字典中,存在则将对应键值对存入result_A
- 子集校验:直接调用
Collections库的Should Contain Sub Dictionary关键字,校验result_A的所有键值对是否全部存在于json_C中,校验失败会自动抛出错误终止流程,符合你的要求。
修正后完整可运行代码
*** Settings *** Library JsonValidator Library Collections Library RequestsLibrary *** Keywords *** Get_Response_1 [Arguments] ${ip}=${ip} ${username}=${USERNAME} ${password}=${PASSWORD} ${auth} = Create List ${username} ${password} Create Session alias=session1 url=http://${ip}:8080/redfish/v1 auth=${auth} verify=${False} ${response} = GET On Session session1 url=/redfish/v1/XXXXXX/YYYYY/ZZZZZ Status Should Be 200 ${response} Should Be Equal As Strings OK ${response.reason} Delete Session session1 [Return] ${response} Get_Response_2 [Arguments] ${ip}=${ip} ${username}=${USERNAME} ${password}=${PASSWORD} ${auth} = Create List ${username} ${password} Create Session alias=session2 url=http://${ip}:8080/redfish/v1 auth=${auth} verify=${False} ${response} = GET On Session session2 url=/redfish/v1/AAAA/BBBB/CCCC Status Should Be 200 ${response} Should Be Equal As Strings OK ${response.reason} Delete Session session2 [Return] ${response} Get_JSON_File_Data [Documentation] 读取json_A并提取Properties列表 ${json_content}= Get File D:\\xxx\yyy\zzz\\json_A.json ${properties_list}= get json value ${json_content} /Type/SubType/Properties [Return] ${properties_list} Parse_Response_To_Dict [Documentation] 将接口响应转换为JSON字典 [Arguments] ${response} ${json_dict}= Parse Json ${response.content} [Return] ${json_dict} Build_Result_A [Documentation] 对比属性列表和json_B,构造result_A [Arguments] ${properties_list} ${json_b_dict} ${result_a}= Create Dictionary FOR ${prop} IN @{properties_list} ${key_exists}= Run Keyword And Return Status Dictionary Has Key ${json_b_dict} ${prop} IF ${key_exists} Set To Dictionary ${result_a} ${prop} ${json_b_dict}[${prop}] END END [Return] ${result_a} *** Test Cases *** JSON属性比对校验 # 步骤1:获取所有数据源 ${properties_from_a}= Get_JSON_File_Data Log 从json_A提取的属性列表:${properties_from_a} ${resp1}= Get_Response_1 ${json_b}= Parse_Response_To_Dict ${resp1} Log json_B内容:${json_b} ${resp2}= Get_Response_2 ${json_c}= Parse_Response_To_Dict ${resp2} Log json_C内容:${json_c} # 步骤2:构造result_A ${result_a}= Build_Result_A ${properties_from_a} ${json_b} ${result_a_str}= Stringify Json ${result_a} Log 生成的result_A:\n${result_a_str} # 步骤3:校验result_A是否是json_C的子集,校验失败自动终止 Should Contain Sub Dictionary ${json_c} ${result_a} msg=json_C缺少result_A的键值对,校验失败 Log 校验通过,最终返回result_A:\n${result_a_str}
运行效果说明
按你给出的示例数据运行时,校验会直接通过,输出你期望的JSON格式结果;如果json_C缺少result_A的任意键或者对应值不匹配,关键字会自动抛出错误,终止测试流程。
内容的提问来源于stack exchange,提问作者quickme
相关产品推荐
相关产品推荐

