[英]Validate jsonschema against a json array having multiple elements using postman and tv4
下面是我的 JSON 模式
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": [
{
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"stations": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"serial_number": {
"type": "string"
},
"name": {
"type": "string"
}
},
"required": [
"id",
"serial_number",
"name"
]
}
]
}
},
"required": [
"id",
"name",
"stations"
]
}
]
}
下面是要验证的json
[
{
"id": 1,
"name": "Test location",
"stations": [
{
"id": 1,
"serial_number": "TEST001",
"name": "TEST-STN!"
}
]
},
{
"id": 2,
"name": "Test location2"
}
]
这里元素“stations”在模式中被标记为必需,但它在json的第二个项目中缺失。 仍然 tv4 验证通过。
我们真正需要的是,它应该无法通过验证,因为第二个 Item 中缺少 station 元素
观察结果是 IF 站元素不存在于任何 JSON 项目中,则验证失败。 但是,如果站元素存在于其中一项中,则验证通过
pm.test("Login Validation", function() { pm.expect(tv4.validate(pm.response.json(), pm.environment.get('schema.json'), true, true), tv4.error).to.be.true;});
我尝试了 tv4 选项“checkRecursive”,其值为 true 和 false ......它仍然通过了验证
任何帮助表示赞赏
我认为这样的事情对您有用并显示问题:
let schema = {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"name",
"stations"
],
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"stations": {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"serial_number",
"name"
],
"properties": {
"id": {
"type": "integer"
},
"serial_number": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
}
}
}
}
pm.test("Check Schemat", () => {
pm.response.to.have.jsonSchema(schema)
})
我已经包含了jsonSchema()
Postman 函数,因为它使用 AJV 而不是旧的且当前未维护的 tv4 模块。
items
关键字可以采用模式或模式数组,并且根据使用的版本具有不同的语义。
当items
采用单个模式时,它描述了一个数组,其中数组中的所有项都必须符合给定的模式。
{
"type": "array".
"items": { "type": "string" }
}
["a", "b", "c"]
当items
采用模式数组时,它描述了一个元组,其中items
中的每个模式都与实例数组中的相应项进行比较。
{
"type": "array",
"items": [{ "type": "string" }, { "type": "integer" }, { "type": "boolean }]
}
["a", 1, false]
你很困惑,因为你使用了错误的items
形式。 因为您使用了数组形式,所以只会验证数组中的第一个元素。 验证器忽略其余项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.