| 1 |
Empty key validation: |
| 2 |
docs: scalar/empty |
| 3 |
based on: strictyaml |
| 4 |
description: | |
| 5 |
Sometimes you may wish to not specify a value or specify |
| 6 |
that it does not exist. |
| 7 |
|
| 8 |
Using StrictYAML you can accept this as a valid value and |
| 9 |
have it parsed to one of three things - None, {} (empty dict), |
| 10 |
or [] (empty list). |
| 11 |
given: |
| 12 |
setup: | |
| 13 |
from strictyaml import Map, Str, Enum, EmptyNone, EmptyDict, EmptyList, NullNone, load, as_document |
| 14 |
from ensure import Ensure |
| 15 |
yaml_snippet: 'a:' |
| 16 |
variations: |
| 17 |
EmptyNone with empty value: |
| 18 |
steps: |
| 19 |
- Run: | |
| 20 |
Ensure(load(yaml_snippet, Map({"a": EmptyNone() | Enum(["A", "B",])}))).equals({"a": None}) |
| 21 |
|
| 22 |
EmptyDict: |
| 23 |
steps: |
| 24 |
- Run: | |
| 25 |
Ensure(load(yaml_snippet, Map({"a": EmptyDict() | Enum(["A", "B",])}))).equals({"a": {}}) |
| 26 |
|
| 27 |
EmptyList: |
| 28 |
steps: |
| 29 |
- Run: | |
| 30 |
Ensure(load(yaml_snippet, Map({"a": EmptyList() | Enum(["A", "B",])}))).equals({"a": []}) |
| 31 |
|
| 32 |
NullNone: |
| 33 |
steps: |
| 34 |
- Run: | |
| 35 |
Ensure(load("a: null", Map({"a": NullNone() | Enum(["A", "B",])}))).equals({"a": None}) |
| 36 |
|
| 37 |
EmptyNone no empty value: |
| 38 |
given: |
| 39 |
yaml_snippet: 'a: A' |
| 40 |
steps: |
| 41 |
- Run: | |
| 42 |
Ensure(load(yaml_snippet, Map({"a": EmptyNone() | Enum(["A", "B",])}))).equals({"a": "A"}) |
| 43 |
|
| 44 |
Combine Str with EmptyNone and Str is evaluated first: |
| 45 |
steps: |
| 46 |
- Run: | |
| 47 |
Ensure(load(yaml_snippet, Map({"a": Str() | EmptyNone()}))).equals({"a": ""}) |
| 48 |
|
| 49 |
|
| 50 |
Combine EmptyNone with Str and Str is evaluated last: |
| 51 |
steps: |
| 52 |
- Run: | |
| 53 |
Ensure(load(yaml_snippet, Map({"a": EmptyNone() | Str()}))).equals({"a": None}) |
| 54 |
|
| 55 |
Non-empty value: |
| 56 |
given: |
| 57 |
yaml_snippet: 'a: C' |
| 58 |
steps: |
| 59 |
- Run: |
| 60 |
code: | |
| 61 |
load(yaml_snippet, Map({"a": Enum(["A", "B",]) | EmptyNone()})) |
| 62 |
raises: |
| 63 |
type: strictyaml.exceptions.YAMLValidationError |
| 64 |
message: |- |
| 65 |
when expecting an empty value |
| 66 |
found arbitrary text |
| 67 |
in "<unicode string>", line 1, column 1: |
| 68 |
a: C |
| 69 |
^ (line: 1) |
| 70 |
|
| 71 |
Serialize empty dict: |
| 72 |
steps: |
| 73 |
- Run: |
| 74 |
code: | |
| 75 |
print(as_document({"a": {}}, Map({"a": EmptyDict() | Str()})).as_yaml()) |
| 76 |
will output: 'a:' |
| 77 |
|
| 78 |
Serialize empty list: |
| 79 |
steps: |
| 80 |
- Run: |
| 81 |
code: | |
| 82 |
print(as_document({"a": []}, Map({"a": EmptyList() | Str()})).as_yaml()) |
| 83 |
will output: 'a:' |
| 84 |
|
| 85 |
Serialize None: |
| 86 |
steps: |
| 87 |
- Run: |
| 88 |
code: | |
| 89 |
print(as_document({"a": None}, Map({"a": EmptyNone() | Str()})).as_yaml()) |
| 90 |
will output: 'a:' |