我正在使用 petstore api 示例,并尝试使用 postman 和 tv4 验证对象数组。
重现:
1。上一个请求获取 petStore Swagger 文件并加载到环境中:
GET->https://petstore.swagger.io/v2/swagger.json
Test Tab execution:
const jsonResponse = pm.response.json();
pm.environment.set("https://petstore.swagger.io/v2/swagger.json", jsonResponse);
2.提出新的邮递员请求
GET https://petstore.swagger.io/v2/pet/findByStatus?status=available
Test Tab:
//1.Get Response
const jsonResponse = pm.response.json();
//2. Load From Previos calls
var _schema = pm.environment.get("https://petstore.swagger.io/v2/swagger.json");
//3. Look for my APIOperation schemas
var findByStatusSuccessSchema = _schema["paths"]["/pet/findByStatus"].get.responses[200].schema;
console.log('loaded schema: ' + JSON.stringify( findByStatusSuccessSchema));
var isValid = tv4.validate(jsonResponse, findByStatusSuccessSchema);
console.log("1.isValid " +isValid); //true
//4.Try with not valid Pet objects Array
var notValidPetArray = [{"propA":"valueA"}]
isValid = tv4.validate(notValidPetArray, findByStatusSuccessSchema);
console.log("2.isValid " + isValid); //true
两个断言返回 true,但第二个验证是针对无效的 pet 模式对象,因此带有数组的 tv4.validate 似乎仅验证数组包装器。 (如果我用一个简单的对象更改notValidPetArray,isValid= false)
我可以在 (component.schemas.Pet) 找到 Pet 架构,加载并验证数组中的每个元素,但我的问题是为什么 paths.findByStatus.response.200.schema 引用的架构不验证每个数组元素自动。
问候
我玩了你的例子,这是我的结果:
//3. Look for my APIOperation schemas
const findByStatusSuccessSchema = _schema["paths"]["/pet/findByStatus"].get.responses[200].schema;
console.log('loaded schema: ' + JSON.stringify( findByStatusSuccessSchema));
const petSchema = _schema["definitions"]["Pet"];
tv4.addSchema('#/definitions/Pet', petSchema);
var isValid = tv4.validate(jsonResponse.slice(1, 10), findByStatusSuccessSchema); // slice because not all array elements in response are valide
console.log("1.isValid " +isValid); //true
//4.Try with not valid Pet objects Array
var notValidPetArray = [{"propA":"valueA"}]
isValid = tv4.validate(notValidPetArray, findByStatusSuccessSchema);
console.log("2.isValid " + isValid); //false
console.log("error " + tv4.error); // 'name' is missing