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

校验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)

输出为

 

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

 

posted @ 2020-07-03 14:42  只宅不技术  阅读(2366)  评论(0编辑  收藏  举报