具有定义键的映射(Map)
一对一映射在 YAML 中用 : 表示,并解析为 Python 字典。
使用 StrictYAML 的“Map”,你可以验证映射是否包含正确的键和正确的类型的值。
注意:对于事先不知道键确切名称但知道类型的映射,请使用 MapPattern。
示例 yaml_snippet
â: 1
b: 2
c: 3
from collections import OrderedDict
from strictyaml import Map, Int, load, as_document
from collections import OrderedDict
from ensure import Ensure
schema = Map({"a": Int(), "b": Int(), "c": Int()})
schema_2 = Map({u"â": Int(), "b": Int(), "c": Int()})
一个键映射
x: 1
Ensure(load(yaml_snippet, Map({"x": Int()})).data).equals(OrderedDict([('x', 1)]))
键值
Ensure(load(yaml_snippet, schema_2)[u'â']).equals(1)
获取未找到的项目键
load(yaml_snippet, schema_2)['keynotfound']
:
'keynotfound'
无法使用 .text
load(yaml_snippet, schema_2).text
builtins.TypeError:YAML({'â': 1, 'b': 2, 'c': 3}) is a mapping, has no text value.:
解析在模式中找不到键的片段
a: 1
b: 2
â: 3
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
while parsing a mapping
unexpected key not in schema 'â'
in "<unicode string>", line 3, column 1:
"\xE2": '3'
^ (line: 3)
解析时不期望序列
- 1
- 2
- 3
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting a mapping
in "<unicode string>", line 1, column 1:
- '1'
^ (line: 1)
found a sequence
in "<unicode string>", line 3, column 1:
- '3'
^ (line: 3)
序列化时不期望列表
as_document([1, 2, 3], schema)
strictyaml.exceptions.YAMLSerializationError:
Expected a dict, found '[1, 2, 3]'
序列化时空字典无效
as_document({}, schema)
strictyaml.exceptions.YAMLSerializationError:
Expected a non-empty dict, found an empty dict.
Use EmptyDict validator to serialize empty dicts.
意外键
a: 1
b: 2
c: 3
d: 4
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
while parsing a mapping
unexpected key not in schema 'd'
in "<unicode string>", line 4, column 1:
d: '4'
^ (line: 4)
未找到必需的键
a: 1
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
while parsing a mapping
required key(s) 'b', 'c' not found
in "<unicode string>", line 1, column 1:
a: '1'
^ (line: 1)
迭代器
a: 1
b: 2
c: 3
assert [item for item in load(yaml_snippet, schema)] == ["a", "b", "c"]
序列化
assert as_document(OrderedDict([(u"â", 1), ("b", 2), ("c", 3)]), schema_2).as_yaml() == yaml_snippet