使用 cerberus 验证字典列表

Validate list of dicts using cerberus

开始使用 cerberus 进行合同测试。

在某些情况下,当我们得到基于字典的 JSON 结构时,它可以完美地工作,例如:

{'results': [{"key": "value"}, {"key": "value"}, {"key":"value}]}

但是当响应只是一个指令列表时,一切都会变糟,例如:

[{"key": "value"}, {"key": "value"}, {"key":"value}]

我面临的基本错误是:

cerberus.validator.DocumentError: '[{'id': 'XXX', 'is_supported': True}]' is not a document, must be a dict

指定顶级类型:架构中的“列表”没有帮助,返回架构错误:

cerberus.schema.SchemaError: {'type': ['must be of dict type']}

天真的解决方案只是通过列表并验证其中的所有实体。 但看起来应该有更合适的方法来做到这一点。

据我了解(如 google 所说),顶级数组是有效的 JSON 结构,因此应该有一种方法可以正确验证它,不是吗?

我更愿意 post 将此作为评论,但我没有名气。尽管如此,其他人在这里问了同样的事情:https://github.com/pyeve/cerberus/issues/220

一个解决方案是编写一个 Validator subclass, and another was to use cerberus-list-schema,它显然基于 Cerberus,但也支持列表和数组模式。