Validating optional keys in mappings (Map)
Not every key in a YAML mapping will be required. If you use the "Optional('key')" validator with YAML, you can signal that a key/value pair is not required.
from strictyaml import Map, Int, Str, Bool, Optional, load
from ensure import Ensure
schema = Map({"a": Int(), Optional("b"): Bool(), })
Valid example 1:
a: 1
b: yes
Ensure(load(yaml_snippet, schema)).equals({"a": 1, "b": True})
Valid example 2:
a: 1
b: no
Ensure(load(yaml_snippet, schema)).equals({"a": 1, "b": False})
Valid example missing key:
a: 1
Ensure(load(yaml_snippet, schema)).equals({"a": 1})
Invalid 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)
Invalid 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)
Executable specification
Documentation automatically generated from optional.story storytests.