当前位置:网站首页>Technology Sharing | How to use the JSON Schema mode of interface automation testing?
Technology Sharing | How to use the JSON Schema mode of interface automation testing?
2022-08-09 23:13:00 【hog_ceshiren】
The JSON Schema schema is a vocabulary that can be used to annotate and validate JSON documents.In actual work, to perform assertion verification on the interface return value, in addition to the assertion detection of common fields, the types of other fields should also be detected.It is obviously very time-consuming to write assertions to the returned fields one by one. At this time, a template is needed to define the data type and matching conditions. Except for the key parameters, the rest can be asserted directly through this template. JSON Schema can be perfectly implemented.such demand.
JSON Schema official website:
http://json-schema.org/implementations.html
Environment preparation
Install the JSON Schema package
- Python Version
pip install jsonschema
- Java version
io.rest-assured json-schema-validator 3.0.1
Use of JSON Schema
JSON Schema template generation
First, use the website https://www.jsonschema.net/ of the JSON Schema tool, copy the returned json string to the left side of the page, and then click INFER SHCEMA, it will be automatically converted to the schema json file type, and theThe return value type of each lot is set to a default type, and a regular pattern can also be written in the pattern to match.
[External link image transfer failed, the source site may have anti-leech mechanism, it is recommended to save the image and upload it directly (img-K12bEfqU-1659923704774)(upload://rWFXH62wcBJrNH0xcCf6O7w1UJA.png)]
Click the "Settings" button to display more detailed assertion settings for each type of return value. This is the most common and practical function of schema.You can also check or assert the most refined interval value of each type of field, such as length, value range, etc.
Click the copy button to save the generated schema template.
Practical practice
Next, a post request will be initiated to verify that both the url field and the origin field in the response value are of type string.
Python version
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)
If the type of origin is written as number , an error will occur:
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)
Return error message
> 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'}
Similarly, if the type of the url is changed to number, an error message will also appear.
> 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 version
The verification file is stored in the JsonValidator.json file to verify whether the url field and the origin field in the response value are both of type string. The content of the file is:
"type": "object","properties": {"url": {"type": "string"},"origin": {"type":"string"}}}
Consistent with the Python version, the following code verifies whether the response value conforms to the format requirements specified in the JsonValidator.json file.
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;import static io.restassured.RestAssured.*;public class Requests {public static void main(String[] args) {//Define the contentType of the request header information as application/jsongiven().when().post("https://httpbin.ceshiren.com/post").then().assertThat().body(matchesJsonSchemaInClasspath("JsonValidator.json"));}}
️ Copy the "link below" to improve the core competitiveness of the test!
Hello, if you like this article, remember to click "Like"!Your support is very important~(▽) PS: If you have any questions, please contact us
More technical articles to share and free materials to receivep>
边栏推荐
- CVPR22 Oral | shunt through multi-scale token polymerization from attention, code is open source
- C语言预处理命令是什么?
- 【Efficient Tools】Remote Control Software ToDesk (Favorites)
- [corctf 2022] 部分
- 同步锁synchronized追本溯源
- 宝塔实测-搭建LightPicture开源图床系统
- 浅谈Numpy中的shape、reshape函数的区别
- 6个规则去净化你的代码
- XXE-XML外部实体注入-知识点
- windos安装Mysql8.0,及解决重新登录异常问题 ERROR 1045 (28000)
猜你喜欢
随机推荐
Word第一页空白页怎么删除?删除Word第一页空白页方法教程
leetcode:数组中的第K个最大元素
XXE-XML外部实体注入-知识点
L3-2 至多删三个字符 (30 分)
Word文档怎么输入无穷大符号∞
np中的round函数,ceil函数与floor函数
【云原生】4.2 DevOps 精讲篇
Leetcode 93 复原IP地址
Referenced file contains errors 完美解决方法
普源精电上半年扭亏为盈,高端产品持续发力!你看好仪器界“华为”吗?
2021(ICPC)亚洲区域赛昆明站(CGHIJLM)
Leetcode 93 IP addresses
Puyuan Jingdian turned losses into profits in the first half of the year, and high-end products continued to develop!Are you optimistic about "Huawei" in the instrument industry?
AI识万物:从0搭建和部署手语识别系统
Interpretation of the paper (DropEdge) "DropEdge: Towards Deep Graph Convolutional Networks on Node Classification"
Unity2D_背景粒子效果
Tensorflow中placeholder函数的用法
Jmeter 使用正则表达式提取器将返回值全部保存到一个文件中
MySQL:错误1153(08S01):得到的数据包大于“ max_allowed_packet”字节
CVPR22 Oral | shunt through multi-scale token polymerization from attention, code is open source