61 lines
2.2 KiB
Python
61 lines
2.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
# @Author : caiweichao
|
||
# @explain : 接口返回值校验
|
||
import allure
|
||
|
||
from Commons.util.json_util import JsonUtil
|
||
from Commons.util.logs import Log
|
||
|
||
import jsonschema
|
||
|
||
|
||
class ApiAssert:
|
||
@staticmethod
|
||
def assert_all_expected(jsonPath: str, check: str, response: str):
|
||
"""
|
||
全部字段校验,将全部对返回值进行校验
|
||
:param jsonPath:jsonpath
|
||
:param check: 期望值
|
||
:param response:
|
||
:return:
|
||
"""
|
||
if len(jsonPath := jsonPath.split("\n")) != len(check := check.split("\n")):
|
||
return Exception("用例参数异常请检查!")
|
||
try:
|
||
for k, v in dict(zip(jsonPath, check)).items():
|
||
if (k := JsonUtil.jsonToOneValue(response, rule=k)) == v:
|
||
Log.info(f"\n接口关键字段校验:{v} = {k}")
|
||
else:
|
||
Log.error(f"接口关键字段校验未通过:{v} != {k}")
|
||
return False
|
||
return True
|
||
except Exception:
|
||
Exception("校验异常请检查")
|
||
|
||
@staticmethod
|
||
def assert_jsonschema(response, schema):
|
||
"""
|
||
jsonschema与实际结果断言方法
|
||
:param response: 实际响应结果
|
||
:param schema: jsonschema
|
||
:return:
|
||
"""
|
||
try:
|
||
Log.info("jsonschema校验开始")
|
||
jsonschema.validate(instance=response, schema=schema)
|
||
Log.info("jsonschema校验通过")
|
||
allure.step(f"jsonschema校验通过")
|
||
except jsonschema.exceptions.ValidationError or jsonschema.exceptions.SchemaError as e:
|
||
Log.error(f"jsonschema校验失败,报错信息为: {e}")
|
||
allure.step(f"jsonschema校验失败,报错信息为: {e}")
|
||
raise e
|
||
|
||
|
||
if __name__ == '__main__':
|
||
jsonxx = [{'pm10': 24, 'city': '珠海', 'time': '2016-10-23 13:00:00'}]
|
||
json_schema = {'type': 'array', 'items':
|
||
{'type': 'object',
|
||
'properties': {'pm10': {'type': 'number', }, 'city': {'type': 'string', 'enum': ['珠海', '深圳']},
|
||
'time': {'type': 'string'}}}}
|
||
ApiAssert.assert_jsonschema(jsonxx, json_schema)
|