繁体   English   中英

Postman 无法验证 JSON 架构中的所有对象

[英]Postman Trouble Validating All Objects in JSON Schema

看起来它应该足够直截了当,但是当返回多个 ZA8CFDE6331BD59EB2AC96F8911C4B666 时,我在完全验证 Postman(Tiny Validator 4)中的 JSON 响应数据时遇到问题。 在做负测的时候,我发现它只检查第一个 object 而不是所有对象,以确保返回所有数据。 我想确保所有对象中返回的所有数据都是正确的类型并且按预期存在。 我意识到这不应该是一个问题,但想在我的测试环境中验证回归。

响应示例:

[
    {
        "productID": 1,
        "product": "Desktop",
        "versionID": 123,
        "version": "Win10 x64"
    },
    {
        "productID": 2,
        "product": "Laptop",
        "versionID": 321,
        "version": "Win 10 x64"
    },
    {
        "productID": 3,
        "product": "Monitor",
        "versionID": 456,
        "version": "LCD Panel"
    }
];

Postman 架构和 Object 设置:

var schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "productID": {
          "type": "integer"
        },
        "product": {
          "type": "string"
        },
        "versionID": {
          "type": "integer"
        },
        "version": {
          "type": "string"
        }
      },
      "required": [
        "productID",
        "product",
        "versionID",
        "version"
      ]
    }
  ]
}

var jsonData = pm.response.json();

var wrongDataType = [
    {
        "productID": 1,
        "product": "Desktop",
        "versionID": 123,
        "version": "Win10 x64"
    },
    {
        "productID": "2",       //data returned as a string instead of integer
        "product": "Laptop",
        "versionID": 321,
        "version": "Win 10 x64"
    }
];

var dataMissing = [
    {
        "productID": 1,
        "product": "Desktop",
        "versionID": 123,
        "version": "Win10 x64"
    },
    {
        "productID": "2",
        //"product": "Laptop",      //data not present in response
        "versionID": 321,
        "version": "Win 10 x64"
    }
];

使用 Tiny Validator 4 进行测试验证:

pm.test('Schema is valid', function() {
  pm.expect(tv4.validate(jsonData, schema)).to.be.true;
});

pm.test('Wrong data type is not valid', function() {
  pm.expect(tv4.validate(wrongDataType, schema)).to.be.false;
});

pm.test('Data missing is not valid', function() {
  pm.expect(tv4.validate(dataMissing, schema)).to.be.false;
});

在针对模式对返回的 jsonData 进行 TV4 验证时,它返回 true,因为 API 响应有效。 对于后续比较,将 wrongDataType 和 dataMissing 与模式进行比较,Postman 测试显示为失败,因为 TV4 验证预期无效比较,但实际上匹配。

如果我在第一个 object 中输入了错误的数据类型或丢失的数据,它会捕获它,验证失败,并且测试通过。 但是,如果将不正确的数据放入任何其他返回的 object(如示例中所示)中,则测试将失败,因为它没有捕获第二个对象中的错误。

如何让我的测试检查响应中的所有对象,如果有任何不正确或丢失则失败?

我花了一些时间,但您已将items指定为数组。 这意味着每个项目都是在位置上指定的。 由于您只有一个子模式,因此仅验证了第一项。

如果您只使用子模式,但没有包装在数组中,它应该可以解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM