Metersphere增加脚本断言
本文讲述如何在metersphere平台添加脚本断言
场景:校验接口返回的json对象 key值是否完整准确,key值无缺失
以下是操作步骤:
- 在接口调用后增加断言规则,断言规则选择脚本
脚本中选择python,脚本逻辑处理完后,使用 AssertionResult.setFailure(True)、 AssertionResult.setFailure(False),AssertionResult.setFailureMessage("exist key is not in response")
TODO:后期尝试将变量值打印在FailureMessage中
1 import json
2 res = prev.getResponseDataAsString() #res为响应结果,类型为unicode
3 dic_res = json.loads(res) #将unicode转为dict
4 def checkJsonKey(jsonValue,expKey):
5 '''
6 校验json中的key是否有期望的expKey
7 '''
8 notInKey = []
9 for key in expKey:
10 if not(jsonValue.keys().__contains__(key)):
11 notInKey.append(key)
12 return notInKey
13
14 expKey=["id","fromTwinId","relationType","toTwinId","created"]
15 log.info("response.keys()")
16 log.info(str(dic_res["data"]))
17 notInKey=checkJsonKey(dic_res["data"][0],expKey)
18 if notInKey.__len__()==0:
19 AssertionResult.setFailure(False)
20 log.info("AssertionResult-----ture")
21 else:
22 AssertionResult.setFailure(True)
23 AssertionResult.setFailureMessage("exist key is not in response")
24 log.info("AssertionResult-----false")
25 log.info(str(notInKey))
注意:log.info(“”)将字段显示在接口调用的控制台中
断言结果在接口的断言中查看是否成功