在映射(Map)中验证可选键
YAML 映射中的每个键都不一定是必需的。如果你使用“Optional('key')”验证器与 YAML 一起使用,你可以表明键值对不是必需的。
from strictyaml import Map, Int, Str, Bool, Optional, load
from ensure import Ensure
schema = Map({"a": Int(), Optional("b"): Bool(), })
有效示例 1
a: 1
b: yes
Ensure(load(yaml_snippet, schema)).equals({"a": 1, "b": True})
有效示例 2
a: 1
b: no
Ensure(load(yaml_snippet, schema)).equals({"a": 1, "b": False})
缺少键的有效示例
a: 1
Ensure(load(yaml_snippet, schema)).equals({"a": 1})
无效 1
a: 1
b: 2
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting a boolean value (one of "yes", "true", "on", "1", "y", "no", "false", "off", "0", "n")
found an arbitrary integer
in "<unicode string>", line 2, column 1:
b: '2'
^ (line: 2)
无效 2
a: 1
b: yes
c: 3
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
while parsing a mapping
unexpected key not in schema 'c'
in "<unicode string>", line 3, column 1:
c: '3'
^ (line: 3)