组合定义和未定义键的映射(MapCombined)

实验性

此功能处于 Alpha 阶段。API 可能会在次要版本增量中发生变化。

当您希望在某些映射中支持任意可选键时(即,在模式中指定一些必需键,但允许在其之上添加任何其他键),请使用 MapCombined。

参见 https://github.com/crdoconnor/strictyaml/issues/148#issuecomment-861007657

from strictyaml import Any, Int, MapCombined, Optional, Str, load
from ensure import Ensure

schema = MapCombined(
  {
    "required": Str(),
    Optional("foo"): Int(),
  },
  Str(),
  Any(),
)

Optional 存在

required: Hello World
foo: 42
bar: 42
Ensure(load(yaml_snippet, schema).data).equals(
    {
        "required": "Hello World",
        "foo": 42,
        "bar": "42",
    }
)

Optional 不存在

required: Hello World
bar: 42
Ensure(load(yaml_snippet, schema).data).equals(
    {
        "required": "Hello World",
        "bar": "42",
    }
)

多个未定义

required: Hello World
bar: 42
baz: forty two
Ensure(load(yaml_snippet, schema).data).equals(
    {
        "required": "Hello World",
        "bar": "42",
        "baz": "forty two",
    }
)

Required 不存在

bar: 42
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
while parsing a mapping
required key(s) 'required' not found
  in "<unicode string>", line 1, column 1:
    bar: '42'
     ^ (line: 1)

未定义的无效类型

required: Hello World
bar: forty two
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
found arbitrary text
  in "<unicode string>", line 2, column 1:
    bar: forty two
    ^ (line: 2)

无效键类型

1: Hello World
not_an_integer: 42
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
found arbitrary text
  in "<unicode string>", line 2, column 1:
    not_an_integer: '42'
    ^ (line: 2)

可执行规范

map-combined.story storytests 自动生成的文档。