接口测试-JsonShema断言
当接口测试返回的响应非常多字段时,不可能一个个字段去断言,这个时候就可以利用schema格式校验的方式去断言
python 用法
1 下载依赖包
pip install jsonschema
2 获取响应schema
schema内容一般有以下两种获取方式
- 直接从接口文档中获取,部分接口文档可以
- 可以获取json响应后再转换网上进行转换
- 先获取响应
{
"code": 200,
"message": "成功",
"data": {
"status": 1,
"tips": "等待扫描",
"token": null
},
"timestamp": 1656932916768
}
- 进行转换
{
"$schema": "http://json-schema.org/draft-06/schema#",
"$ref": "#/definitions/Welcome",
"definitions": {
"Welcome": {
"type": "object",
"additionalProperties": false,
"properties": {
"code": {
"type": "integer"
},
"message": {
"type": "string"
},
"data": {
"$ref": "#/definitions/Data"
},
"timestamp": {
"type": "integer"
}
},
"required": [
"code",
"data",
"message",
"timestamp"
],
"title": "Welcome"
},
"Data": {
"type": "object",
"additionalProperties": false,
"properties": {
"status": {
"type": "integer"
},
"tips": {
"type": "string"
},
"token": {
"type": "null"
}
},
"required": [
"status",
"tips",
"token"
],
"title": "Data"
}
}
}
3 进行断言
def test_get_list(self, desc, name):
schema = 'json_schema' # json_schema是我们转换得到的schema
res = {
"code": 200,
"message": "成功",
"data": {
"status": 1,
"tips": "等待扫描",
"token": null
},
"timestamp": 1656932916768
}
validate(res, schema)
# 也可以将schema存成一个json文件后进行读取校验
schema_json = json.loads(open('file_path','r',encoding='utf-8').read())
validate(res, schema)
Java用法
我用java做接口都是借助rest assured 框架的 所以这里也是介绍使用rest assured的方式进行schema断言;如果有兴趣的话大家也可以去了解一下这个框架
- 前面两步是一样的
- 执行断言如下
given()
.get("http://localhost:8000/rest-assured.json") // 接口地址
.then()
.body(matchesJsonSchemaInClasspath("json_schema.json")) // 获取到body后进行schema校验