校验json返回数据格式是否正确需要用到jsonschema

首先进行安装

pip install jsonschema

示例

from jsonschema import validate

result = {
    "code" : 0,
    "name": "中国",
    "msg": "login success!",
    "password": "000038efc7edc7438d781b0775eeaa009cb64865",
    "username": "test"
}
#校验数据格式设定
schema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "test demo",
    "description": "validate result information",
    "type": "object",
    "properties": {
        "code": {
            "description": "error code",
            "type": "integer"
        },
        "name": {
            "description": "name",
            "type": "string"
        },
        "msg":
        {
            "description": "msg",
            "type": "string"
        },
        "password":
        {
            "description": "error password",
            "maxLength": 20,
            "pattern": "^[a-f0-9]{20}$",  # 正则校验a-f0-9的16进制,总长度20
            "type": "string"
        }
    },
    "required": [
        "code","name", "msg", "password"
    ]
}

# validate校验, 跟assert断言一个意思
validate(instance=result, schema=schema)

输出为

【python】接口自动化测试中,如何校验json返回数据的格式是否正确

 

因为password长度超过了我们校验中限制的最大长度20

 

相关文章:

  • 2021-05-26
  • 2021-06-06
  • 2022-12-23
  • 2021-06-21
  • 2022-12-23
  • 2021-09-19
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2022-02-28
  • 2023-03-22
相关资源
相似解决方案