Enumerated scalars (Enum)

StrictYAML allows you to ensure that a scalar value can only be one of a set number of items.

It will throw an exception if any strings not in the list are found.

from strictyaml import Map, Enum, MapPattern, YAMLValidationError, load
from collections import OrderedDict
from ensure import Ensure

schema = Map({"a": Enum(["A", "B", "C"])})

Valid because it contains 'A':

a: A
Ensure(load(yaml_snippet, schema)).equals({"a": "A"})

Get .data from enum:

a: A
assert isinstance(load(yaml_snippet, schema)['a'].data, str)

Valid because it contains 'B':

a: B
Ensure(load(yaml_snippet, schema)).equals({"a": "B"})

Valid because it contains 'C':

a: C
Ensure(load(yaml_snippet, schema)).equals({"a": "C"})

Invalid because D is not in enum:

a: D
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting one of: A, B, C
found arbitrary text
  in "<unicode string>", line 1, column 1:
    a: D
     ^ (line: 1)

Invalid because blank string is not in enum:

a:
load(yaml_snippet, schema)
strictyaml.exceptions.YAMLValidationError:
when expecting one of: A, B, C
found a blank string
  in "<unicode string>", line 1, column 1:
    a: ''
     ^ (line: 1)

Successful serialization:

a: A
yaml = load(yaml_snippet, schema)
yaml['a'] = "B"
print(yaml.as_yaml())
a: B

Invalid serialization:

a: A
yaml = load(yaml_snippet, schema)
yaml['a'] = "D"
print(yaml.as_yaml())
strictyaml.exceptions.YAMLSerializationError:
Got 'D' when  expecting one of: A, B, C

Executable specification

Documentation automatically generated from enum.story storytests.