| 1 |
Validating optional keys in mappings (Map): |
| 2 |
docs: compound/optional-keys |
| 3 |
based on: strictyaml |
| 4 |
description: | |
| 5 |
Not every key in a YAML mapping will be required. If |
| 6 |
you use the "Optional('key')" validator with YAML, |
| 7 |
you can signal that a key/value pair is not required. |
| 8 |
given: |
| 9 |
setup: | |
| 10 |
from strictyaml import Map, Int, Str, Bool, Optional, load |
| 11 |
from ensure import Ensure |
| 12 |
|
| 13 |
schema = Map({"a": Int(), Optional("b"): Bool(), }) |
| 14 |
variations: |
| 15 |
Valid example 1: |
| 16 |
given: |
| 17 |
yaml_snippet: | |
| 18 |
a: 1 |
| 19 |
b: yes |
| 20 |
steps: |
| 21 |
- Run: |
| 22 |
code: | |
| 23 |
Ensure(load(yaml_snippet, schema)).equals({"a": 1, "b": True}) |
| 24 |
|
| 25 |
Valid example 2: |
| 26 |
given: |
| 27 |
yaml_snippet: | |
| 28 |
a: 1 |
| 29 |
b: no |
| 30 |
steps: |
| 31 |
- Run: |
| 32 |
code: | |
| 33 |
Ensure(load(yaml_snippet, schema)).equals({"a": 1, "b": False}) |
| 34 |
|
| 35 |
Valid example missing key: |
| 36 |
given: |
| 37 |
yaml_snippet: 'a: 1' |
| 38 |
steps: |
| 39 |
- Run: |
| 40 |
code: | |
| 41 |
Ensure(load(yaml_snippet, schema)).equals({"a": 1}) |
| 42 |
|
| 43 |
Invalid 1: |
| 44 |
given: |
| 45 |
yaml_snippet: | |
| 46 |
a: 1 |
| 47 |
b: 2 |
| 48 |
steps: |
| 49 |
- Run: |
| 50 |
code: load(yaml_snippet, schema) |
| 51 |
raises: |
| 52 |
type: strictyaml.exceptions.YAMLValidationError |
| 53 |
message: |- |
| 54 |
when expecting a boolean value (one of "yes", "true", "on", "1", "y", "no", "false", "off", "0", "n") |
| 55 |
found an arbitrary integer |
| 56 |
in "<unicode string>", line 2, column 1: |
| 57 |
b: '2' |
| 58 |
^ (line: 2) |
| 59 |
Invalid 2: |
| 60 |
given: |
| 61 |
yaml_snippet: | |
| 62 |
a: 1 |
| 63 |
b: yes |
| 64 |
c: 3 |
| 65 |
steps: |
| 66 |
- Run: |
| 67 |
code: load(yaml_snippet, schema) |
| 68 |
raises: |
| 69 |
type: strictyaml.exceptions.YAMLValidationError |
| 70 |
message: |- |
| 71 |
while parsing a mapping |
| 72 |
unexpected key not in schema 'c' |
| 73 |
in "<unicode string>", line 3, column 1: |
| 74 |
c: '3' |
| 75 |
^ (line: 3) |
| 76 |
|
| 77 |
|
| 78 |
Nested optional validation: |
| 79 |
based on: strictyaml |
| 80 |
given: |
| 81 |
setup: | |
| 82 |
from strictyaml import Map, Int, Str, Bool, Optional, load |
| 83 |
from ensure import Ensure |
| 84 |
|
| 85 |
schema = Map({"a": Int(), Optional("b"): Map({Optional("x"): Str(), Optional("y"): Str()})}) |
| 86 |
variations: |
| 87 |
Valid 1: |
| 88 |
given: |
| 89 |
yaml_snippet: 'a: 1' |
| 90 |
steps: |
| 91 |
- Run: |
| 92 |
code: | |
| 93 |
Ensure(load(yaml_snippet, schema)).equals({"a": 1}) |
| 94 |
|
| 95 |
Valid 2: |
| 96 |
given: |
| 97 |
yaml_snippet: | |
| 98 |
a: 1 |
| 99 |
b: |
| 100 |
x: y |
| 101 |
y: z |
| 102 |
steps: |
| 103 |
- Run: |
| 104 |
code: | |
| 105 |
Ensure(load(yaml_snippet, schema)).equals( |
| 106 |
{"a": 1, "b": {"x": "y", "y": "z"}} |
| 107 |
) |