| 1 |
Enumerated scalars (Enum): |
| 2 |
docs: scalar/enum |
| 3 |
based on: strictyaml |
| 4 |
description: | |
| 5 |
StrictYAML allows you to ensure that a scalar |
| 6 |
value can only be one of a set number of items. |
| 7 |
|
| 8 |
It will throw an exception if any strings not |
| 9 |
in the list are found. |
| 10 |
given: |
| 11 |
setup: | |
| 12 |
from strictyaml import Map, Enum, MapPattern, YAMLValidationError, load |
| 13 |
from collections import OrderedDict |
| 14 |
from ensure import Ensure |
| 15 |
|
| 16 |
schema = Map({"a": Enum(["A", "B", "C"])}) |
| 17 |
variations: |
| 18 |
Valid because it contains 'A': |
| 19 |
given: |
| 20 |
yaml_snippet: 'a: A' |
| 21 |
steps: |
| 22 |
- Run: | |
| 23 |
Ensure(load(yaml_snippet, schema)).equals({"a": "A"}) |
| 24 |
|
| 25 |
Get .data from enum: |
| 26 |
given: |
| 27 |
yaml_snippet: 'a: A' |
| 28 |
steps: |
| 29 |
- Run: | |
| 30 |
assert isinstance(load(yaml_snippet, schema)['a'].data, str) |
| 31 |
|
| 32 |
Valid because it contains 'B': |
| 33 |
given: |
| 34 |
yaml_snippet: 'a: B' |
| 35 |
steps: |
| 36 |
- Run: |
| 37 |
code: | |
| 38 |
Ensure(load(yaml_snippet, schema)).equals({"a": "B"}) |
| 39 |
|
| 40 |
Valid because it contains 'C': |
| 41 |
given: |
| 42 |
yaml_snippet: 'a: C' |
| 43 |
steps: |
| 44 |
- Run: |
| 45 |
code: | |
| 46 |
Ensure(load(yaml_snippet, schema)).equals({"a": "C"}) |
| 47 |
|
| 48 |
Invalid because D is not in enum: |
| 49 |
given: |
| 50 |
yaml_snippet: 'a: D' |
| 51 |
steps: |
| 52 |
- Run: |
| 53 |
code: load(yaml_snippet, schema) |
| 54 |
raises: |
| 55 |
type: strictyaml.exceptions.YAMLValidationError |
| 56 |
message: |- |
| 57 |
when expecting one of: A, B, C |
| 58 |
found arbitrary text |
| 59 |
in "<unicode string>", line 1, column 1: |
| 60 |
a: D |
| 61 |
^ (line: 1) |
| 62 |
|
| 63 |
Invalid because blank string is not in enum: |
| 64 |
given: |
| 65 |
yaml_snippet: 'a:' |
| 66 |
steps: |
| 67 |
- Run: |
| 68 |
code: load(yaml_snippet, schema) |
| 69 |
raises: |
| 70 |
type: strictyaml.exceptions.YAMLValidationError |
| 71 |
message: |- |
| 72 |
when expecting one of: A, B, C |
| 73 |
found a blank string |
| 74 |
in "<unicode string>", line 1, column 1: |
| 75 |
a: '' |
| 76 |
^ (line: 1) |
| 77 |
|
| 78 |
Successful serialization: |
| 79 |
given: |
| 80 |
yaml_snippet: 'a: A' |
| 81 |
steps: |
| 82 |
- Run: |
| 83 |
code: | |
| 84 |
yaml = load(yaml_snippet, schema) |
| 85 |
yaml['a'] = "B" |
| 86 |
print(yaml.as_yaml()) |
| 87 |
will output: 'a: B' |
| 88 |
|
| 89 |
Invalid serialization: |
| 90 |
given: |
| 91 |
yaml_snippet: 'a: A' |
| 92 |
steps: |
| 93 |
- Run: |
| 94 |
code: | |
| 95 |
yaml = load(yaml_snippet, schema) |
| 96 |
yaml['a'] = "D" |
| 97 |
print(yaml.as_yaml()) |
| 98 |
raises: |
| 99 |
type: strictyaml.exceptions.YAMLSerializationError |
| 100 |
message: "Got 'D' when expecting one of: A, B, C" |