【问题标题】:tightening python data structure validation using Validator使用 Validator 加强 python 数据结构验证
【发布时间】:2018-09-15 21:33:48
【问题描述】:

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

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!

在尝试进行单元测试以确保架构没有更改时,这会导致问题。我怎样才能确保第三次护理会给出假?

【问题讨论】:

    标签: python json schema


    【解决方案1】:

    解决方案是添加“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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-09
      • 2017-04-23
      • 2014-08-05
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多