Debian Codegraph @

hitch/story/nested-map.story

raw
1 Nested mapping validation:
2 based on: strictyaml
3 description: |
4 Mappings can be nested within one another, which
5 will be parsed as a dict within a dict.
6 given:
7 setup: |
8 from strictyaml import Map, Int, load
9 from ensure import Ensure
10
11 schema = Map({"a": Map({"x": Int(), "y": Int()}), "b": Int(), "c": Int()})
12 variations:
13 Valid nested mapping:
14 given:
15 yaml_snippet: |
16 a:
17 x: 9
18 y: 8
19 b: 2
20 c: 3
21 steps:
22 - Run:
23 code: |
24 Ensure(load(yaml_snippet, schema)).equals({"a": {"x": 9, "y": 8}, "b": 2, "c": 3})
25
26
27 Invalid nested mapping:
28 given:
29 yaml_snippet: |
30 a:
31 x: 9
32 z: 8
33 b: 2
34 d: 3
35 steps:
36 - Run:
37 code: load(yaml_snippet, schema)
38 raises:
39 type: strictyaml.exceptions.YAMLValidationError
40 message: |-
41 while parsing a mapping
42 unexpected key not in schema 'z'
43 in "<unicode string>", line 3, column 1:
44 z: '8'
45 ^ (line: 3)
46
47 No nested mapping where expected:
48 given:
49 yaml_snippet: |
50 a: 11
51 b: 2
52 d: 3
53 steps:
54 - Run:
55 code: load(yaml_snippet, schema)
56 raises:
57 type: strictyaml.exceptions.YAMLValidationError
58 message: |-
59 when expecting a mapping
60 found an arbitrary integer
61 in "<unicode string>", line 1, column 1:
62 a: '11'
63 ^ (line: 1)
64 Modify nested map:
65 given:
66 yaml_snippet: |
67 a:
68 x: 9
69 y:
70 - 1
71 - 2
72 - 3
73 b: 2
74 c: 3
75 setup: |
76 from strictyaml import Map, Int, load, Seq
77 from collections import OrderedDict
78
79 schema = Map({"a": Map({"x": Int(), "y": Seq(Int())}), "b": Int(), "c": Int()})
80
81 yaml = load(yaml_snippet, schema)
82
83 # Non-ordered dict would also work, but would yield an indeterminate order of keys
84 yaml['a'] = OrderedDict([("x", 5), ("y", [4, 5, 6])])
85 yaml['a']['x'] = 99
86 steps:
87 - Run:
88 code: print(yaml.as_yaml())
89 will output: |-
90 a:
91 x: 99
92 y:
93 - 4
94 - 5
95 - 6
96 b: 2
97 c: 3
98