Postman与tv4无法验证内部数组对象的解决方案
使用Postman和tv4验证Petstore API的对象数组
我正在研究Petstore API示例,尝试用Postman和tv4验证对象数组。
编辑:在@Wladimir Diskowski的提示下,我明白了必须在执行任何验证前把所有schema.definitions加载到tv4中,这样才能找到所有内部对象引用。
复现步骤
1. 前置请求:获取Petstore Swagger文件并加载到环境中
GET https://petstore.swagger.io/v2/swagger.json Test Tab 执行代码: const jsonResponse = pm.response.json(); pm.environment.set("https://petstore.swagger.io/v2/swagger.json", jsonResponse);
2. 创建新的Postman请求
GET https://petstore.swagger.io/v2/pet/findByStatus?status=available Test Tab 代码: // 1. 获取响应 const jsonResponse = pm.response.json(); // 2. 加载之前请求获取的Swagger Schema var _schema = pm.environment.get("https://petstore.swagger.io/v2/swagger.json"); for (var prop in _schema.definitions) { tv4.addSchema('#/definitions/'+prop, _schema["definitions"][prop]); } // 3. 定位目标API接口的响应Schema const findByStatusSuccessSchema = _schema["paths"]["/pet/findByStatus"].get.responses[200].schema; var isValid = tv4.validate(jsonResponse.slice(1, 10), findByStatusSuccessSchema); // 截取部分数组,因为并非所有响应元素都符合验证规则 console.log("1.isValid " + isValid); // 输出true // 4. 测试不符合规则的Pet对象数组 var notValidPetArray = [{"propA":"valueA"}] isValid = tv4.validate(notValidPetArray, findByStatusSuccessSchema); console.log("2.isValid " + isValid); // 输出false console.log("error " + tv4.error); // 提示'name'字段缺失 // 5. 测试格式错误的Pet对象(内部tag.id字段应为整数) var malfommedPet = { "id": 9223372036854761039, "category": { "id": 0, "name": "string" }, "name": "doggie", "photoUrls": [ "string" ], "tags": [ { "id": "I must be a number", "name": "string" } ], "status": "available" }; var petSchema = _schema["definitions"]["Pet"]; var malfommedPet_isValid = tv4.validate(malfommedPet, petSchema); console.log("Malformed Pet isValid= "+ malfommedPet_isValid); console.log("error " + tv4.error); // 提示Invalid type: string (expected integer)(tags.id必须为整数)
现在我可以根据paths/{pathID}/responses/{response}/schema中定义的架构,验证对应路径请求的响应了。
内容的提问来源于stack exchange,提问作者danipenaperez
相关产品推荐
相关产品推荐

