Mappings with defined keys (Map)

Mappings of one value to another are represented by : in YAML and parsed as python dicts.

Using StrictYAML's 'Map' you can validate that a mapping contains the right keys and the right type of values.

Note: for mappings where you don't know the exact names of the keys in advance but you do know the type, use MapPattern.

Example 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()})

one key mapping:

x: 1
Ensure(load(yaml_snippet, Map({"x": Int()})).data).equals(OrderedDict([('x', 1)]))

key value:

Ensure(load(yaml_snippet, schema_2)[u'â']).equals(1)

get item key not found:

load(yaml_snippet, schema_2)['keynotfound']
:
'keynotfound'

cannot use .text:

load(yaml_snippet, schema_2).text
builtins.TypeError:YAML({'â': 1, 'b': 2, 'c': 3}) is a mapping, has no text value.:

parse snippet where key is not found in schema:

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)

sequence not expected when parsing:

- 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)

List not expected when serializing:

as_document([1, 2, 3], schema)
strictyaml.exceptions.YAMLSerializationError:
Expected a dict, found '[1, 2, 3]'

Empty dict not valid when serializing:

as_document({}, schema)
strictyaml.exceptions.YAMLSerializationError:
Expected a non-empty dict, found an empty dict.
Use EmptyDict validator to serialize empty dicts.

Unexpected key:

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)

required key not found:

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)

iterator:

a: 1
b: 2
c: 3
assert [item for item in load(yaml_snippet, schema)] == ["a", "b", "c"]

serialize:

assert as_document(OrderedDict([(u"â", 1), ("b", 2), ("c", 3)]), schema_2).as_yaml() == yaml_snippet

Executable specification

Documentation automatically generated from map.story storytests.