当前位置:网站首页>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>
边栏推荐
- 微软Excel表格点击单元格行和列都显示颜色怎么弄?聚光灯效果设置
- Lyapp exponents and bifurcation diagrams for fractional chaotic systems
- APP自动化测试框架-UiAutomator2基础入门
- STC8H开发(十五): GPIO驱动Ci24R1无线模块
- 编程语言中,取余和取模的区别
- PMP每日一练 | 考试不迷路-8.8(包含敏捷+多选)
- 人人都可以DIY的大玩具,宏光MINIEV GAMEBOY产品力强,出行新装备
- NIO Cup 2022 Nioke Summer Multi-School Training Camp 7 CFGJ
- Technology Sharing | How to Handle Header Cookies in Interface Automation Testing
- DSPE-PEG-PDP, DSPE-PEG-OPSS, phospholipid-polyethylene glycol-mercaptopyridine reduce the immunogenicity of peptides
猜你喜欢
Word文档怎么输入无穷大符号∞
蓝牙模块有哪些种类?BLE低功耗蓝牙模块有什么特点?
角度和弧度的相互换算
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?
cadence中复制一部分PCB到另一个PCB中去
AI识万物:从0搭建和部署手语识别系统
[corctf 2022] section
别叫我玩,我要考PMP:考PMP选择机构需要了解的那些事儿
POWER SOURCE ETA埃塔电源维修FHG24SX-U概述
人人都可以DIY的大玩具,宏光MINIEV GAMEBOY产品力强,出行新装备
随机推荐
简单问题窥见数学
Unity2D_背景粒子效果
SQLi-LABS Page-2 (Adv Injections)
Excel如何打出正负号?Excel打出正负号的方法
cadence中复制一部分PCB到另一个PCB中去
【Efficient Tools】Remote Control Software ToDesk (Favorites)
在VMware上安装win虚拟机
Leetcode 93 复原IP地址
TF中random.normal()与random.truncated_normal()
Reinforcement Learning Weekly Issue 57: DL-DRL, FedDRL & Deep VULMAN
Skywalking系列学习之Trace Profiling源码分析
Don't tell me to play, I'm taking the PMP exam: what you need to know about choosing an institution for the PMP exam
Word怎么制作双面席卡?使用Word制作双面席卡方法
题解:Edu Codeforces 109(div2)
Optimization of SQL Statements and Indexes
定投的基金
Lyapp exponents and bifurcation diagrams for fractional chaotic systems
APP automation test framework - UiAutomator2 introductory
上海控安SmartRocket系列产品推介(三):SmartRocket iVerifier计算机联锁系统验证工具
C语言预处理命令是什么?