| 1 |
Either/or schema validation of different, equally valid different kinds of YAML: |
| 2 |
docs: howto/either-or-validation |
| 3 |
description: | |
| 4 |
StrictYAML can be directed to parse two different elements or |
| 5 |
blocks of YAML. |
| 6 |
|
| 7 |
If the first thing does not parse correctly, it attempts to |
| 8 |
parse the second. If the second does not parse correctly, |
| 9 |
it raises an exception. |
| 10 |
based on: strictyaml |
| 11 |
given: |
| 12 |
setup: | |
| 13 |
from strictyaml import Map, Seq, Bool, Int, Str, YAMLValidationError, load |
| 14 |
from ensure import Ensure |
| 15 |
|
| 16 |
schema = Str() | Map({"a": Bool() | Int()}) |
| 17 |
variations: |
| 18 |
Boolean first choice true: |
| 19 |
given: |
| 20 |
yaml_snippet: 'a: yes' |
| 21 |
steps: |
| 22 |
- Run: |
| 23 |
code: | |
| 24 |
Ensure(load(yaml_snippet, schema)).equals({"a": True}) |
| 25 |
|
| 26 |
Boolean first choice false: |
| 27 |
given: |
| 28 |
yaml_snippet: 'a: no' |
| 29 |
steps: |
| 30 |
- Run: |
| 31 |
code: | |
| 32 |
Ensure(load(yaml_snippet, schema)).equals({"a": False}) |
| 33 |
|
| 34 |
Int second choice: |
| 35 |
given: |
| 36 |
yaml_snippet: 'a: 5' |
| 37 |
steps: |
| 38 |
- Run: |
| 39 |
code: | |
| 40 |
Ensure(load(yaml_snippet, schema)).equals({"a": 5}) |
| 41 |
|
| 42 |
Invalid not bool or int: |
| 43 |
given: |
| 44 |
yaml_snippet: 'a: A' |
| 45 |
steps: |
| 46 |
- Run: |
| 47 |
code: load(yaml_snippet, schema) |
| 48 |
raises: |
| 49 |
type: strictyaml.exceptions.YAMLValidationError |
| 50 |
message: |- |
| 51 |
when expecting an integer |
| 52 |
found arbitrary text |
| 53 |
in "<unicode string>", line 1, column 1: |
| 54 |
a: A |
| 55 |
^ (line: 1) |
| 56 |
|
| 57 |
Invalid combinations of more than one map: |
| 58 |
given: |
| 59 |
yaml_snippet: 'a: x' |
| 60 |
steps: |
| 61 |
- Run: |
| 62 |
code: | |
| 63 |
load(yaml_snippet, Map({"a": Str()}) | Map({"b": Str()})) |
| 64 |
raises: |
| 65 |
type: strictyaml.exceptions.InvalidValidatorError |
| 66 |
message: You tried to Or ('|') together 2 Map validators. Try using revalidation |
| 67 |
instead. |
| 68 |
|
| 69 |
Invalid combinations of more than one seq: |
| 70 |
given: |
| 71 |
yaml_snippet: | |
| 72 |
- 1 |
| 73 |
- 2 |
| 74 |
steps: |
| 75 |
- Run: |
| 76 |
code: | |
| 77 |
load(yaml_snippet, Seq(Int()) | Seq(Str())) |
| 78 |
raises: |
| 79 |
type: strictyaml.exceptions.InvalidValidatorError |
| 80 |
message: You tried to Or ('|') together 2 Seq validators. Try using revalidation |
| 81 |
instead. |
| 82 |
|
| 83 |
Change item after validated: |
| 84 |
given: |
| 85 |
yaml_snippet: 'a: yes' |
| 86 |
steps: |
| 87 |
- Run: |
| 88 |
code: | |
| 89 |
yaml = load(yaml_snippet, schema) |
| 90 |
yaml['a'] = 5 |
| 91 |
assert yaml['a'] == 5 |