【问题标题】:ajv validation of json schema is wrong in postman [duplicate]json模式的ajv验证在邮递员中是错误的[重复]
【发布时间】:2020-04-30 05:32:50
【问题描述】:

我有 JSON:

{
    "data": {
        "regex": "some regex",
        "validationMessage": "some validation message"
    }
}

我使用this tool 构建 json 架构。

初始化如下:

var Ajv = require('ajv'),
    ajv = new Ajv({logger: console}),
    schema = {
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/root.json",
  "type": "object",
  "properties": {
    "data": {
      "$id": "#/properties/data",
      "type": "object",
      "properties": {
        "regex": {
          "$id": "#/properties/data/properties/regex",
          "type": "string",
          "pattern": "^(.*)$"
        },
        "validationMessage": {
          "$id": "#/properties/data/properties/validationMessage",
          "type": "string",
          "pattern": "^(.*)$"
        }
      }
    }
  }
};

那我要检查json模式是否有效

pm.test('Schema is valid', function() {
    pm.expect(ajv.validate(schema, {alpha: 123})).to.be.true;
});

我看到测试通过了。 怎么了?为什么架构有效?

此外,我将把 {alpha: 123} 替换为 JSON.parse(responseBody)

【问题讨论】:

  • 你在邮递员中究竟是如何使用它的?作为 OpenAPI 定义文档的一部分?
  • 我可以告诉您为什么该实例对架构有效,但我无法告诉您需要更改什么,除非您告诉我为什么您希望验证失败。 =]
  • 我正在使用 Postman 测试我的 API 查询,我想检查响应中是否存在所有字段(在架构中)。
  • @A.Gladkiy 我提供的答案有帮助吗?
  • 是的,谢谢,我只需要包含必填字段就可以了。

标签: json postman jsonschema ajv


【解决方案1】:

您可以尝试将其更改为以下内容:

var Ajv = require('ajv'),
    ajv = new Ajv({logger: console, allErrors: true}),
    schema = {
      "type": "object",
      "required": [
        "data"
      ],
      "properties": {
        "data": {
          "type": "object",
          "required": [
            "regex",
            "validationMessage"
          ],
          "properties": {
            "regex": {
              "type": "string",
              "pattern": "^(.*)$"
            },
            "validationMessage": {
              "type": "string",
              "pattern": "^(.*)$"
            }
          }
        }
      }
    };

pm.test('Schema is valid', function() {
    pm.expect(ajv.validate(schema, { alpha: 123 }), JSON.stringify(ajv.errors)).to.be.true;
});

我将allErrors 选项添加到Ajv 并在测试中公开了这些选项。我还稍微修改了您的架构,以添加对象所需的键。

我测试了这将是一个在测试中硬编码的对象,但也有一个模拟的响应。

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 2019-04-22
    • 2017-04-29
    • 2018-02-03
    • 2022-01-23
    • 1970-01-01
    • 2019-06-10
    • 2018-01-22
    • 2020-07-15
    相关资源
    最近更新 更多