| 1 |
Enum with item validation: |
| 2 |
docs: compound/map-pattern |
| 3 |
based on: strictyaml |
| 4 |
description: | |
| 5 |
See also: enum validation. |
| 6 |
|
| 7 |
Your enums can be a transformed string or something other than a string |
| 8 |
if you use an item validator. |
| 9 |
given: |
| 10 |
setup: | |
| 11 |
from strictyaml import Map, Enum, Int, MapPattern, YAMLValidationError, load |
| 12 |
from ensure import Ensure |
| 13 |
|
| 14 |
schema = Map({"a": Enum([1, 2, 3], item_validator=Int())}) |
| 15 |
variations: |
| 16 |
Parse correctly: |
| 17 |
given: |
| 18 |
yaml_snippet: 'a: 1' |
| 19 |
steps: |
| 20 |
- Run: |
| 21 |
code: | |
| 22 |
Ensure(load(yaml_snippet, schema)).equals({"a": 1}) |
| 23 |
|
| 24 |
Invalid because D is not an integer: |
| 25 |
given: |
| 26 |
yaml_snippet: 'a: D' |
| 27 |
steps: |
| 28 |
- Run: |
| 29 |
code: load(yaml_snippet, schema) |
| 30 |
raises: |
| 31 |
type: strictyaml.exceptions.YAMLValidationError |
| 32 |
message: |- |
| 33 |
when expecting an integer |
| 34 |
found arbitrary text |
| 35 |
in "<unicode string>", line 1, column 1: |
| 36 |
a: D |
| 37 |
^ (line: 1) |
| 38 |
|
| 39 |
Invalid because 4 is not in enum: |
| 40 |
given: |
| 41 |
yaml_snippet: 'a: 4' |
| 42 |
steps: |
| 43 |
- Run: |
| 44 |
code: load(yaml_snippet, schema) |
| 45 |
raises: |
| 46 |
type: strictyaml.exceptions.YAMLValidationError |
| 47 |
message: "when expecting one of: 1, 2, 3\nfound an arbitrary integer\n\ |
| 48 |
\ in \"<unicode string>\", line 1, column 1:\n a: '4'\n ^ (line:\ |
| 49 |
\ 1)" |
| 50 |
Invalid because blank string is not in enum: |
| 51 |
given: |
| 52 |
yaml_snippet: 'a:' |
| 53 |
steps: |
| 54 |
- Run: |
| 55 |
code: load(yaml_snippet, schema) |
| 56 |
raises: |
| 57 |
type: strictyaml.exceptions.YAMLValidationError |
| 58 |
message: "when expecting an integer\nfound a blank string\n in \"<unicode\ |
| 59 |
\ string>\", line 1, column 1:\n a: ''\n ^ (line: 1)" |