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

2021-04-30 04:28

阅读:365

标签:loading   for   red   如何   tle   prope   自动化   ken   password   

校验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": "error msg ",
            "type": "string"
        },
        "msg":
        {
            "description": "login success return token",
            "type": "string"
        },
        "password":
        {
            "description": "login success return token",
            "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

 

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

标签:loading   for   red   如何   tle   prope   自动化   ken   password   

原文地址:https://www.cnblogs.com/ffrs/p/13230360.html


评论


亲,登录后才可以留言!