JSON Schema校验接口响应格式类型

一、背景

在测试中除了断言响应值的是否相等,还需要断言响应数据的结构及字段属性是否发生了变化,如果响应数据的结构及字段属性发现了变化,就需要对应的调整客户端的代码,因此,需要对 JSON 的 Schema 进行校验。

二、安装jsonschema

1、安装包

pip install jsonschema

2、导入包

# validate用于断言
from jsonschema import validate

3、示例演示

import requests
from jsonschema import validate

def test_schema_01():
    """
    断言通过用例:接口响应格式与schema格式一致
    """
    schema = {
        "type": "object",
        "properties": {
            "url": {
                "type": "string"
            },
            "origin": {
                "type": "string"
            }
        }
    }
    r = requests.post("http://httpbin.org/post")
    validate(instance=r.json(), schema=schema)

如果将 origin 的 type 写成 number ,则会出现报错

import requests
from jsonschema import validate

def test_schema_02():
    """
    断言失败用例:接口响应格式与schema格式不一致,origin的type写成number
    """
    schema = {
        "type": "object",
        "properties": {
            "url": {
                "type": "string"
            },
            "origin": {
                "type": "number"
            }
        }
    }
    r = requests.post("http://httpbin.org/post")
    validate(instance=r.json(), schema=schema)

提示报错,如图所示:

若将 url 的 type 改为 number,也会有报错提示,如图所示:

三、综合运用

1、内容转jsonschema语言

首先,需要讲被测的接口内容获取到,尽量让接口响应的字段更全。

然后,将响应结果复制,并粘贴至https://transform.tools/json-to-json-schema将内容转为json schema语言。

然后,将转换后的Json schema复制并粘贴至脚本当中,作为断言时的标准模板。

schema = {
        "type": "object",
        "properties": {
            "url": {
                "type": "string"
            },
            "origin": {
                "type": "string"
            }
        }
    }

这样,只要接口的字段出现了类型的变化或者缺失,脚本马上就能发现其错误,测试就能第一时间知道该接口有了变化,测试就能第一时间发现,并及时修改对应的脚本。

四、参考

1、接口转jsonschema语言:https://transform.tools/json-to-json-schema

2、https://www.convertsimple.com/convert-json-to-json-schema/

3、https://json-schema.org/implementations.html

4、https://www.w3toolhub.com/json-to-json-schema-converter.html

5、http://httpbin.org/

posted @ 2023-02-16 17:32  xyztank  阅读(83)  评论(0编辑  收藏  举报