接口自動化的結果校驗分兩個層次:協議層,業務層
(本篇僅對協議層校驗做擴展,僅考慮返回結果為json格式的接口)
協議層校驗即對返回結果的key是否存在,value類型是否與協議一致進行判斷
class CheckResp(): def check_keys(self,target,template,except_key=""): if isinstance(target,(str,unicode)): target = json.loads(target) if isinstance(template,(str,unicode)): template = json.loads(template) for key,value in template.items(): if not target.has_key(key) and key not in except_key: # 校驗斷言json的key在返回結果中的是否存在 raise Exception("key:%s not in the response" % key) elif target.has_key(key) and type(value) != type(target[key]): # 校驗返回結果的value類型與斷言json的value類型一致 raise Exception("the value's type of key:%s not match the assert json" % key) if isinstance(value,dict): # 多重嵌套的字典類型遞歸校驗判斷 self.check_keys(target[key],value)
在robot framework中的應用:
- 引用代碼庫
- 在接口調用請求后,獲取返回結果,賦值給${resp}
- 接口返回結果協議層校驗關鍵字使用:Check Keys ${resp} {"a":1,"b":{"c":"d"}}