1.JSON Schema简介
JSON Schema是一个词汇表,可用于注释和验证json文档。在实际测试工作中,对接口测试的返回值进行断言校验,除了对常用字段的断言检测以外,还要对其他字段的类型进行检测。对返回值中的字段一个个进行断言显然是非常耗时的,这个时候就需要一个模板,通过模板可以定义好数据类型和匹配条件,除了关键参数外,其一的返回值可直接通过此模板来断言,JSON Schema可以完美实现这样的需求。
2.环境准备
安装JSON Schema包
Python版本
pip install jsonschema
Java版本
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>3.0.1</version>
</dependency>
3.JSON Schema的使用
JSON Schema模板生成
(1)我们借助与JSON Schema生成网站使用JSON Schema。打开JSON Schema生成网站,将要返回的json字符串复制到网页的左边,并把页面上的“Source type” 项选择为json。然后点击右边的“JSON Schema”项,此时会生成该json对应的JSON Schema结构,如图7-1所示。此结构中的每个字段的返回值类型都会被解析出来,同时还会将必须返回的字段标注在required列表中展示。
(2)在新的界面中点击“Copy"按钮,可以将生成的JSON Schema模板保存下来。
4.实战演示
向服务端发起一个POST请求,验证响应值中的url字段与origin字段是否都为string类型,演示代码如下(Python版和Java版)。
(1)Python演示代码
import requests
from jsonschema import validate
def test_schem():
schema = {
"type":"object",
"properties":{
"url":{
"type":"string"
},
"origin":{
"type":"string"
}
}
}
r = requests.post("https://httpbin.ceshiren.com/post")
validate(instance.json(),schema=schema)
如果将origin的type写成number,则会有报错提示:
import requests
from jsonschema import validate
def test_schema():
schema = {
"type":"object",
"properties:{
"url":{
"type":"string"
},
"origin":{
"type":"number"
}
}
}
r = requests.post("https://httpbin.ceshiren.com/post")
validate(instance.json(), schema=schema)
返回报错信息:
> raise error
E jsonschema.exceptions.ValidationError: 'xxx.xxx.xxx.xxx' is not of type
'nember'
E Failed validating 'type' in schema['properties']['origin']:
E {'type':'number'}
同理,若将url的type改为number,也会有报错提示:
> rasie error
E jsonschema.exceptions.ValidationError:'https://httpin.ceshiren.com/post' is
not of type 'number'
E Failed validating 'type' in schema['properties']['url']:
E {'type':'number'}
(2)Java演示代码
选中上面操作中解析出来的JSON Schema格式数据,然后打开一个文本编辑器,新建一个JsonValidator.json文件,将刚刚复制出来的数据保存到这个文本文件中。文件内容如下:
{
"type":"object",
"properties":{
"url":{
"type":"string"
},
"origin":{
"type":"string"
}
}
}
以下代码校验响应值是否符合JsonValidator.json文件中规定的格式要求。
import static
io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static io.restassured.RestAssured.*;
public class Requests{
public static void main(String[] args){
//定义请求头信息的contentType为application/json
given().when().
post("https://httpbin.ceshiren.com/post").
then().assertThat().
body(matchesJsonSchemaInClasspath("JsonValidator.json"));
}
}