Postman使用tv4进行JSON Schema结构验证和断言
原文如上链接
北京-临渊
Postman使用tv4进行JSON Schema结构验证和断言
JSON Scheme简介#
对于JSON格式的请求数据或者响应数据,在不同的数据和场景下往往会有一部分动态的值及字段。此时我们可以使用JSON Scheme Validator(JSON结构验证)来验证JSON的结构,各参数及嵌套参数的类型,以及必要字段。
如:GET http://httpbin.org/get?a=a
的响应数据:
Copy
{ "args": { "a": "a" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Cache-Control": "no-cache", "Host": "httpbin.org", "Postman-Token": "08abebe1-eaa4-46a2-9b3a-0f2a5580c44f", "User-Agent": "PostmanRuntime/7.15.0" }, "origin": "164.52.33.194, 164.52.33.194", "url": "https://httpbin.org/get?a=a" }
我们可以验证其结构为:
- 整体是一个(类型为)object对象,包含属性args, headers,origin,url, 必要字段(必须出现的字段)假设为所有
- args类型为object, 包含属性a, a类型为string
- headers类型为object, 包含属性Accept, Accept-Encoding, Cache-Control, Host, Postman-Token, User-Agent, 这些类型都为string
- origin类型为string
- url类型为string
转为JSON Schema语法如下:
Copy
{ "type": "object", "properties": { "args": {"type": "object","properties": {"a": {"type": "string"}} }, "hearders": { "type": "object", "properties": { "Accept": {"type": "string"}, "Cache-Control": {"type": "string"}, "Host": {"type": "string"}, "Postman-Token": {"type": "string"}, "User-Agent": {"type": "string"}, }, }, "origin": {"type": "string"}, "url": {"type": "string"}, }, "required": ["args", "headers", "origin", "url"] }
object类型的验证格式一般为:
Copy
{ "type": "object", "properties": {...} "required": [....] }
其中type类型指定为object, properties下写各个子属性,required中填写必须要出现的元素,required中为注明的元素可以不出现,但出现则必须是限定的类型
array类型的验证格式一般为:
Copy
{ "type": "array", "items": {...} "required": [....] }
其中type类型为array, items下写各个子项, required中填写必须要出现的元素。
string类型的验证格式:
Copy
{"type": "string"}
integer类型的验证格式:
Copy
{"type": "integer"}
JSON Scheme还支持引用等很多赋值的语法,详细可以参考:JSON Schema | The home of JSON Schema
Postman tv4使用#
tv4即 Tiny Validator for JSON data的缩写,微型JSON结构验证器。
在Postman中的使用方法也很简单,首先在Tests脚本中根据响应编写JSON Schema结构模板,然后使用tv3.validate(jsonData, schema)进行验证即可,如下图:
Tests代码如下:
Copy
var schema = { "type": "object", "properties": { "args": {"type": "object", "properties": {"a": {"type": "string"}}}, "hearders": { "type": "object", "properties": { "Accept": {"type": "string"}, "Cache-Control": {"type": "string"}, "Host": {"type": "string"}, "Postman-Token": {"type": "string"}, "User-Agent": {"type": "string"}, }, }, "origin": {"type": "string"}, "url": {"type": "string"}, }, "required": ["args", "headers", "origin", "url"] } pm.test('Schema is valid', function() { var jsonData = pm.response.json(); pm.expect(tv4.validate(jsonData, schema)).to.be.true; });
运行可看到,断言通过:
分类: Postman
标签: Postman, tv4, JSON Schema, JSON结构, JSON Schema Validator
Sponsor
- PayPal
- AliPay
0
0
« 上一篇: Postman中的全局/环境/集合变量的使用及优先级
» 下一篇: 九月未晚
CONTENTS
- 1. JSON Scheme简介
- 2. Postman tv4使用