当前位置:网站首页>JSON Schema模式用法
JSON Schema模式用法
2022-08-08 10:15:00 【华为云】
JSON Schema 模式是一个词汇表,可用于注释和验证 JSON 文档。在实际工作中,对接口返回值进行断言校验,除了常用字段的断言检测以外,还要对其他字段的类型进行检测。对返回的字段一个个写断言显然是非常耗时的,这个时候就需要一个模板,可以定义好数据类型和匹配条件,除了关键参数外,其余可直接通过此模板来断言,JSON Schema 可以完美实现这样的需求。
JSON Schema 官网:
环境准备
安装 JSON Schema 包
- Python 版本
pip install jsonschema
- Java 版本
<dependency> <groupId>io.rest-assured</groupId> <artifactId>json-schema-validator</artifactId> <version>3.0.1</version></dependency>
JSON Schema 的使用
JSON Schema 模板生成
首先要借助于 JSON Schema tool 的网站 https://www.jsonschema.net/,将返回 json 字符串复制到页面左边,然后点击 INFER SHCEMA,就会自动转换为 schema json 文件类型,会将每个地段的返回值类型都设置一个默认类型,在 pattern 中也可以写正则进行匹配。
点击“设置”按钮会出现各个类型返回值更详细的断言设置,这个就是 schema 最常用也是最实用的功能。也可以对每种类型的字段最更细化的区间值校验或者断言,例如长度、取值范围等。
点击复制按钮,可以将生成的 schema 模板保存下来。
实战练习
接下来会发起一个 post 请求,验证响应值中的 url 字段与 origin 字段是否都为 string 类型。
Python版本
import requestsfrom jsonschema import validatedef test_schema(): schema = { "type": "object", "properties": { "url": { "type": "string" }, "origin": { "type":"string" } } } r = requests.post("https://httpbin.ceshiren.com/post") validate(instance=r.json(), schema=schema)
如果将 origin 的 type 写成 number ,则会出现报错:
import requestsfrom jsonschema import validatedef test_schema(): schema = { "type": "object", "properties": { "url": { "type": "string" }, "origin": { "type":"number" } } } r = requests.post("https://httpbin.ceshiren.com/post") validate(instance=r.json(), schema=schema)
返回报错信息
> raise errorE jsonschema.exceptions.ValidationError: 'xxx.xxx.xxx.xxx' is not of type 'number'E Failed validating 'type' in schema['properties']['origin']:E {'type': 'number'}
同理,若将 url 的 type 改为 number,也会有报错提示。
> raise errorE jsonschema.exceptions.ValidationError: 'https://httpbin.ceshiren.com/post' is not of type 'number' E Failed validating 'type' in schema['properties']['url']:E {'type': 'number'}
Java 版本
JsonValidator.json 文件中存放校验文件,校验响应值中的 url 字段与 origin 字段是否都为 string 类型,文件内容为:
"type": "object", "properties": { "url": { "type": "string" }, "origin": { "type":"string" } }}>你好呀,喜欢这篇文章的话记得点个“赞”哦!大家的支持很重要~(*^▽^*) PS:有问题可以联系我们哦>>https://qrcode.ceba.ceshiren.com/link?name=article&project_id=qrcode&from=hwyun×tamp=1659921581&author=QY
同 Python 版本一致,以下代码校验响应值是否符合 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")); }}
边栏推荐
- 语音聊天app开发——对用户更具吸引力的设计
- 「每周译Go」这次我们来点不一样的!--《How to Code in Go》系列上线
- A concise tutorial on expanding (increasing capacity) of VMWare Esxi virtual system data storage
- 图数据库是使用什么作为数据模型的呢?
- 一个用来装逼的利器
- C# api 将base64编码 上传至fastdfs转成文件
- 买股票用同花顺安全吗?资金会不会被转走?
- 文档数据库是用来干什么的呢?
- Machine learning model too slow?Look at Intel (R) extension to accelerate
- 左益豪:用代码创造一个新世界|OneFlow U
猜你喜欢
图像分割 总结
Loadrunner12.0.2安装及中文语言包安装(汉化)
移动端/嵌入式-CV模型-2017:MobelNets-v1
Mysql数据库架构介绍
COMSOL Multiphysics 6.0 software installation package and installation tutorial
centos 安装redis
Dubins曲线学习笔记及相关思考
CentOS MySQL体系管理
Apple developer account application process full version
2022 world conference on robots is holding, intelligent robot booster to intelligent, digital transformation and upgrading traditional industry
随机推荐
键值数据库中可以对值进行查询嘛?
What is intrinsic safety?
Jingkai Safety Supervision App technical service support
四、业务数据解析
The entity List to excel
典型的NoSQL数据库有哪些呢?
ASP.NET Core 2.0中,解决大文件上传配置问题
Redis 定长队列的探索和实践
图数据库是使用什么作为数据模型的呢?
软考证书含金量
文档数据库是怎么定位一个文档的呀?
定时任务框架Quartz-(一)Quartz入门与Demo搭建
重载与重写有什么区别?
"Weekly Translate Go" This time we have something different!-- "How to Code in Go" series launched
Recommend 100 nice English songs
键值数据库中的键是什么类型的对象呢?
String equals hashcode
In the.net core, the use of c # realize fastdfs batch file upload more
小程序使用formdata格式传参
机器学习模型太慢?来看看英特尔(R) 扩展加速