I've got a json schema test in Postman.
schema = {
"items": {
"required": [
"id",
"payment_id",
"bank_info_id",
"account_number",
"account_owner",
"entity_sub_systems",
"is_main",
"public_id"
]
}
}
pm.test("JSON schema check", function () {
pm.response.to.have.jsonSchema(schema);
});
It works. But there are some problems. This test most of all checks the names of keys. For example if the response json has "isMain" instead "is_main". The test fails because response doesn't have a required key "is_main". Or if the schema has more keys than in the response.
The problem is that test doesn't fail if response json has extra keys. For example, if the json schema is like this and the response json has more keys than in the schema
schema = {
"items": {
"required": [
"id",
"payment_id",
"bank_info_id",
"is_main",
"public_id"
]
}
}
Response body
{
"id":"65161",
"payment_id":"65161",
"bank_info_id":"65161",
"is_main":true,
"public_id":"65161",
"something":"65161"
}
The test will not fail.
So, the problem is how to check the response json strongly following required json schema keys?
Following Postman docs - Tiny validator works but not supported work after 10 version of Postman. The following test also passed with extra keys in response.
var jsonData = JSON.parse(responseBody);
pm.test('Checking Response Against Schema Validation', function() {
var result=tv4.validateMultiple(jsonData, schema);
console.log(result);
pm.expect(result.valid).to.be.true;
});
There is a field in schema called additionalProperties. If we specify it false, then it will not allow additional properties. Hope this Doc helps.
const schema = {
"items": {
"required": [
"id",
"payment_id",
"bank_info_id",
"account_number",
"account_owner",
"entity_sub_systems",
"is_main",
"public_id"
],
"additionalProperties": false,
"properties": {
"id": {},
"payment_id": {},
"bank_info_id": {},
"account_number": {},
"account_owner": {},
"entity_sub_systems": {},
"is_main": {},
"public_id": {}
}
}
};