使用Validator收紧python数据结构验证

时间:2018-04-05 23:13:31

标签: python json schema

我正在尝试测试json文件是否与标准json文件相同。使用valideer:

import valideer as V
product_schema = {
     "+id": "number",
     "+name": "string",
     "+price": V.Range("number", min_value=0),
     "tags": ["string"],
     "stock": {
         "warehouse": "number",
         "retail": "number",
     }
 }
validator = V.parse(product_schema)

3个例子,其中两个正在做所需的事情,第三个例子通过它应该失败:

 product1 = {
      "id": 1,
      "name": "Foo",
      "price": 123,
      "tags": ["Bar", "Eek"],   
      "stock": {
          "warehouse": 300,
          "retail": 20
      } }

validator.is_valid(product1) # gives true, which makes sense (identical schema)

另一个例子

 product2 = {
      "id": 1,
      "price": 123,  }

validator.is_valid(product2) # gives False, since the schema are different

我的问题在于我们有额外功能的情况:

product3 = {
          "id": 1,
          "extra id": 12,
          "name": "Foo",
          "price": 123,
          "tags": ["Bar", "Eek"],
          "Hi" : "bar",   
          "stock": {
              "warehouse": 300,
              "retail": 20
          } }

validator.is_valid(product3) # gives true! though the schema are different!

这在尝试进行单元测试时会导致问题,以确保架构不会发生变化。我怎样才能确保第三次护理会给出错误?

1 个答案:

答案 0 :(得分:0)

解决方案是添加" additional_properties"旗 Valideer github page

validator = V.parse(config_schema, additional_properties=False)

现在我们运行三个例子:

validator.is_valid(product1)  # gives true
validator.is_valid(product2)  # gives false
validator.is_valid(product3)  # gives false