本文講述如何在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(“”)將字段顯示在接口調用的控制台中
斷言結果在接口的斷言中查看是否成功