使用 TV4 的 Postman 架构验证

Postman Schema Validation using TV4

我在测试选项卡中使用 tv4 验证 Postman 中的模式时遇到问题 - 它总是 return 进行真正的测试,无论我提供什么。我完全不知所措,真的可以用手 - 这是我的示例 JSON 响应,以及我的测试:

我已经尝试了我能找到的每个 Stack Overflow/tutorial 的大量变体,但没有任何效果 - 它总是 return 是正确的。

//Test Example 

var jsonData = JSON.parse(responseBody);
const schema = {
"required" : ["categories"],
"properties": {
"categories": {
    "required" : ["aStringOne", "aStringTwo", "aStringThree" ],
    "type": "array",
    "properties" : {
        "aStringOne": {"type": "string" },
        "aStringTwo": {"type": "null" },
        "aStringThree": {"type": "boolean" }
    }
}
}
};

pm.test('Schema is present and accurate', () => {
var result=tv4.validateMultiple(jsonData, schema);
console.log(result);
pm.expect(result.valid).to.be.true;
});

//Response Example

{
"categories": [
{
    "aStringOne": "31000",
    "aStringTwo": "Yarp",
    "aStringThree": "More Yarp Indeed"
}
]
}

这应该 return false,因为所有三个属性都是字符串,但它是通过的。我愿意使用不同的验证器或其他技术,只要我可以将其导出为邮递员集合以在我的 CI/CD 流程中与 newman 一起使用。我期待着您能提供的任何帮助。

我建议不要使用 tv4 in Postman, the project isn't actively supported and Postman now includes a better (in my opinion), more actively maintained option called Ajv

语法略有不同,但希望这能让您了解它如何为您工作。

我模拟了你的数据,并把所有的东西都添加到 Tests 选项卡中 - 如果你将 jsonData 变量更改为 pm.response.json(),它将 运行 反对实际响应正文。

var jsonData = {
    "categories": [
        {
            "aStringOne": "31000",
            "aStringTwo": "Yarp",
            "aStringThree": "More Yarp Indeed"
        }
    ]
}



var Ajv = require('ajv'),
    ajv = new Ajv({logger: console, allErrors: true}),
    schema =  {
    "type": "object",
    "required": [ "categories"],
    "properties": {
      "categories": {
          "type": "array",
          "items": {
              "type": "object",
              "required": [ "aStringOne", "aStringTwo", "aStringThree" ],
              "properties": {
                  "aStringOne": { "type": "string" },
                  "aStringTwo": { "type": "integer"},
                  "aStringThree": { "type": "boolean"},
         }
       }
     }
   }
}

pm.test('Schema is valid', function() {
    pm.expect(ajv.validate(schema, jsonData), JSON.stringify(ajv.errors)).to.be.true
});

这是它失败的一个例子,我包含了 allErrors 标志,这样它将 return 所有错误,而不仅仅是它看到的第一个错误。在 pm.expect() 方法中,我添加了 JSON.stringify(ajv.errors) 以便您可以在 Test Result 选项卡中看到错误。它有点乱,可以整理一下,但所有错误信息都在那里。

将属性设置为 string 显示验证通过:

如果所需 Keys 之一不存在,它也会为此出错:

使用模式非常困难,而且创建它们(嵌套数组和对象很棘手)并确保它们按照您的意愿行事并不容易。

有时我认为某些东西应该失败并且它通过了验证测试。它只需要一点 learning/practising,一旦您理解了模式结构,它们就会变得非常有用。