枚举标量 (Enum)
StrictYAML 允许你确保标量值只能是一组项目中的一个。
如果发现列表中不存在任何字符串,它将抛出异常。
from strictyaml import Map, Enum, MapPattern, YAMLValidationError, load
from collections import OrderedDict
from ensure import Ensure
schema = Map({"a": Enum(["A", "B", "C"])})
有效,因为它包含 'A'
a: A
Ensure(load(yaml_snippet, schema)).equals({"a": "A"})
从枚举中获取 .data
a: A
assert isinstance(load(yaml_snippet, schema)['a'].data, str)
有效,因为它包含 'B'
a: B
Ensure(load(yaml_snippet, schema)).equals({"a": "B"})
有效,因为它包含 'C'
a: C
Ensure(load(yaml_snippet, schema)).equals({"a": "C"})
无效,因为 D 不在枚举中
a: D
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting one of: A, B, C
found arbitrary text
in "<unicode string>", line 1, column 1:
a: D
^ (line: 1)
无效,因为空字符串不在枚举中
a:
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting one of: A, B, C
found a blank string
in "<unicode string>", line 1, column 1:
a: ''
^ (line: 1)
序列化成功
a: A
yaml = load(yaml_snippet, schema)
yaml['a'] = "B"
print(yaml.as_yaml())
a: B
序列化无效
a: A
yaml = load(yaml_snippet, schema)
yaml['a'] = "D"
print(yaml.as_yaml())
strictyaml.exceptions.YAMLSerializationError:
Got 'D' when expecting one of: A, B, C