[英]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.