当前位置:网站首页>技术分享 | 接口自动化测试之JSON Schema模式该如何使用?
技术分享 | 接口自动化测试之JSON Schema模式该如何使用?
2022-08-09 21:35:00 【hog_ceshiren】
JSON Schema 模式是一个词汇表,可用于注释和验证 JSON 文档。在实际工作中,对接口返回值进行断言校验,除了常用字段的断言检测以外,还要对其他字段的类型进行检测。对返回的字段一个个写断言显然是非常耗时的,这个时候就需要一个模板,可以定义好数据类型和匹配条件,除了关键参数外,其余可直接通过此模板来断言,JSON Schema 可以完美实现这样的需求。
JSON Schema 官网:
http://json-schema.org/implementations.html
环境准备
安装 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 中也可以写正则进行匹配。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K12bEfqU-1659923704774)(upload://rWFXH62wcBJrNH0xcCf6O7w1UJA.png)]
点击“设置”按钮会出现各个类型返回值更详细的断言设置,这个就是 schema 最常用也是最实用的功能。也可以对每种类型的字段最更细化的区间值校验或者断言,例如长度、取值范围等。
点击复制按钮,可以将生成的 schema 模板保存下来。
实战练习
接下来会发起一个 post 请求,验证响应值中的 url 字段与 origin 字段是否都为 string 类型。
Python版本
import requests
from jsonschema import validate
def 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 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=r.json(), schema=schema)
返回报错信息
> raise error
E 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 error
E 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"
}
}
}
同 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"));
}
}
️ 复制“下方链接”,提升测试核心竞争力!
你好呀,喜欢这篇文章的话记得点个“赞”哦!大家的支持很重要~(▽) PS:有问题可以联系我们哦
边栏推荐
- Jmeter 使用正则表达式提取器将返回值全部保存到一个文件中
- Wps下划线怎么弄?Wps添加下划线的最全方法
- Characteristics and Development Prospects of Korea's Cyber Security System
- 2021(ICPC)亚洲区域赛昆明站(CGHIJLM)
- How to deal with keys when Redis is large?
- Unity2D_背景粒子效果
- 字节二面问的MySQL,差点没答好
- An overall security understanding and method of cyberspace based on connection and security entropy
- linux定时执行sql文件[通俗易懂]
- MySQL跨表、多表更新SQL语句总结
猜你喜欢
小黑leetcode清爽雨天之旅,刚吃完宇飞牛肉面、麻辣烫和啤酒:112. 路径总和
小黑leetcode之旅:94. 二叉树的中序遍历(补充Morris 中序遍历)
DSPE-PEG-PDP, DSPE-PEG-OPSS, phospholipid-polyethylene glycol-mercaptopyridine reduce the immunogenicity of peptides
Word第一页空白页怎么删除?删除Word第一页空白页方法教程
普源精电上半年扭亏为盈,高端产品持续发力!你看好仪器界“华为”吗?
QGIS编译SIP的问题
RHEL7系统修复rm -rf /boot /etc/fstab
MySQL慢查询的多个原因
人人都可以DIY的大玩具,宏光MINIEV GAMEBOY产品力强,出行新装备
别叫我玩,我要考PMP:考PMP选择机构需要了解的那些事儿
随机推荐
C语言之实现倒置字符串的两种方法
Deceptive Dice(期望计算)
Don't use array.length-1 to get the last item of the array
[Generic Programming] Full Detailed Explanation of Templates
What to do if Windows 11 can't find Internet Explorer
linux定时执行sql文件[通俗易懂]
cad图纸怎么复制到word文档里面?Word里插CAD图怎么弄?
筑牢安全防线 鹤壁经济技术开发区开展安全生产培训
cadence中复制一部分PCB到另一个PCB中去
How to fix Windows 11 not finding files
MySQL:错误1153(08S01):得到的数据包大于“ max_allowed_packet”字节
编程时请选择正确的输入法,严格区分中英文
没有 accept,我可以建立 TCP 连接吗?
Cholesterol-PEG-Thiol,CLS-PEG-SH,胆固醇-聚乙二醇-巯基用于改善溶解度
Word第一页不要页眉怎么设置?设置Word首页不要页眉方法教程
访问控制知识
角度和弧度的相互换算
Hessian Matrix 海森矩阵
QGIS编译SIP的问题
浅谈Numpy中的shape、reshape函数的区别