具有任意键名的映射 (MapPattern)
当你不想让用户在映射中定义键名,而只指定键的类型时,使用 MapPattern。
当你希望指定确切的键名时,使用 'Map' 验证器。
from strictyaml import MapPattern, Int, Float, Str, Any, Seq, YAMLValidationError, load
from ensure import Ensure
schema = MapPattern(Str(), Int())
等价性 1
â: 1
b: 2
Ensure(load(yaml_snippet, schema)).equals({u"â": 1, "b": 2})
等价性 2
a: 1
c: 3
Ensure(load(yaml_snippet, schema)).equals({"a": 1, "c": 3})
等价性 3
a: 1
Ensure(load(yaml_snippet, schema)).equals({"a": 1, })
使用浮点数和整数
10.25: 23
20.33: 76
Ensure(load(yaml_snippet, MapPattern(Float(), Int())).data).equals({10.25: 23, 20.33: 76})
使用 Int 和 List
1:
- ABC
2:
- DEF
Ensure(load(yaml_snippet, MapPattern(Int(), Seq(Str()))).data).equals({1: ["ABC"], 2: ["DEF"]})
无效 1
b: b
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
found arbitrary text
in "<unicode string>", line 1, column 1:
b: b
^ (line: 1)
无效 2
a: a
b: 2
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
found arbitrary text
in "<unicode string>", line 1, column 1:
a: a
^ (line: 1)
超过最大键数
â: 1
b: 2
load(yaml_snippet, MapPattern(Str(), Int(), maximum_keys=1))
strictyaml.exceptions.YAMLValidationError:
while parsing a mapping
in "<unicode string>", line 1, column 1:
"\xE2": '1'
^ (line: 1)
expected a maximum of 1 key, found 2.
in "<unicode string>", line 2, column 1:
b: '2'
^ (line: 2)
少于最小键数
â: 1
load(yaml_snippet, MapPattern(Str(), Int(), minimum_keys=2))
strictyaml.exceptions.YAMLValidationError:
while parsing a mapping
expected a minimum of 2 keys, found 1.
in "<unicode string>", line 1, column 1:
"\xE2": '1'
^ (line: 1)
使用非 ASCII 字符无效
a: 1
b: yâs
c: 3
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
found arbitrary text
in "<unicode string>", line 2, column 1:
b: "y\xE2s"
^ (line: 2)