Postman array schema validation

Deadly 提交于 2019-12-24 01:01:46

问题


I have the problem with array json schema validation in postman.

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;
});

And the response body is:

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

I have always passed result. Also I tried with removed [].

Where is the problem?


回答1:


The schema used in question is incorrect, you need to define the type of item in array as object. The correct JSON schema would look like:

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;
});

Please note there are only 2 numeric types in JSON Schema: integer and number. There is no type as long.




回答2:


You could also use Ajv, this is now included with the Postman native apps and the project is actively maintained:

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;
});



回答3:


Hi you should first parse the schema to json, else it will be considered as empty data in some cases.

The correct code is as below:

let jsonData = JSON.parse(responseBody);

schema = JSON.parse(schema); 

Now you have to pass recursive validation and nondefined property check to the tv4.validation function.

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(), schema, true, true)

will check the json data recursively and if any new property is present in the resonse data, it fail the validation.



来源:https://stackoverflow.com/questions/56933925/postman-array-schema-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!