Postman 数组模式验证

Postman array schema validation

我在 postman 中遇到数组 json 模式验证的问题。

var schema = {
    "type": "array",
    "items": [{
         "id": {
            "type":"long"
             },
         "name": {
             "type":"string"
             },
         "email": {
             "type":"string"
            }
    }]
};


pm.test('Response schema type nodes verification', function() {
  pm.expect(tv4.validate(pm.response.json(), schema)).to.be.true;
});

响应正文是:

[
    {
        "id": 1,
        "name": "test1",
        "email": "a@a.com"
    },
    {
        "id": 2,
        "name": "test2",
        "email": "a@a.com"
    },
 .
 .
 .
]

我的成绩一直都是及格的。我也尝试删除 []

问题出在哪里?

问题中使用的模式不正确,您需要将数组中的项目类型定义为object。正确的 JSON 架构如下所示:

var schema = {
    "type": "array",
    "items": [{
        type: "object",
        properties:{
         "id": {
            "type":"integer"
             },
         "name": {
             "type":"string"
             },
         "email": {
             "type":"string"
            }
        }
    }]
};


pm.test('Response schema type nodes verification', function() {
  pm.expect(tv4.validate(pm.response.json(), schema)).to.be.true;
});

请注意 JSON 架构中只有 2 种数字类型:integernumber。没有类型 long.

您也可以使用 Ajv,它现在包含在 Postman 本机应用程序中并且该项目正在积极维护:

var Ajv = require("ajv"),
    ajv = new Ajv({logger: console}),
    schema = {
        "type": "array",
        "items": {
            "type": "object",
            "properties": {
                "id": { "type": "integer" },
                "name": { "type": "string" },
                "email": { "type": "string" }
            }  
        }
    };


pm.test("Schema is valid", function() {
        pm.expect(ajv.validate(schema, pm.response.json())).to.be.true;
});

您好,您应该首先将架构解析为 json,否则在某些情况下它会被视为空数据。

正确的代码如下:

let jsonData = JSON.parse(responseBody);

schema = JSON.parse(schema); 

现在您必须通过 tv4.validation 函数的递归验证和未定义 属性 检查。

pm.test('Response schema type nodes verification', function() {
  pm.expect(tv4.validate(pm.response.json(), schema, true, true)).to.be.true;
});

tv4.validate(pm.response.json(), 架构, 真, 真)

将递归检查 json 数据,如果响应数据中存在任何新的 属性,则验证失败。