Debian Codegraph @

hitch/story/roundtrip.story

raw
1 Reading in YAML, editing it and writing it back out:
2 docs: howto/roundtripping
3 based on: strictyaml
4 description: |
5 Loaded YAML can be modified and dumped out again with
6 comments preserved using .as_yaml().
7
8 Note that due to some bugs in the library (ruamel.yaml)
9 underlying StrictYAML, while the data parsed should
10 be precisely the same, the exact syntax (newlines, comment
11 locations, etc.) may not be identical.
12 given:
13 yaml_snippet: |
14 # Some comment
15
16 a: â # value comment
17
18 # Another comment
19 b:
20 x: 4
21 y: 5
22 c:
23 - a: 1
24 - b: 2
25 setup: |
26 from strictyaml import Map, MapPattern, EmptyDict, Str, Seq, Int, load
27 from ensure import Ensure
28
29 schema = Map({
30 "a": Str(),
31 "b": Map({"x": Int(), "y": Int()}),
32 "c": EmptyDict() | Seq(MapPattern(Str(), Str())),
33 })
34 variations:
35 Commented:
36 steps:
37 - Run:
38 code: |
39 Ensure(load(yaml_snippet, schema).as_yaml()).equals(yaml_snippet)
40
41 Modified with invalid variable:
42 steps:
43 - Run:
44 code: |
45 to_modify = load(yaml_snippet, schema)
46 to_modify['b']['x'] = 2
47 to_modify['c'][0]['a'] = '3'
48 to_modify['b']['x'] = 'not an integer'
49 raises:
50 type: strictyaml.exceptions.YAMLSerializationError
51 message: "'not an integer' not an integer."
52 Modified with float:
53 steps:
54 - run:
55 code: |
56 to_modify = load(yaml_snippet, schema)
57 to_modify['c'][0]['a'] = "1.0001"
58 print(to_modify.as_yaml())
59 will output: |-
60 # Some comment
61
62 a: â # value comment
63
64 # Another comment
65 b:
66 x: 4
67 y: 5
68 c:
69 - a: 1.0001
70 - b: 2
71
72 Modify multi line string:
73 given:
74 yaml_snippet: |
75 a: some
76 b: |
77 text
78 steps:
79 - run:
80 code: |
81 schema = Map({"a": Str(), "b": Str()})
82 to_modify = load(yaml_snippet, schema)
83 to_modify['a'] = 'changed'
84 print(to_modify.as_yaml())
85 will output: |-
86 a: changed
87 b: |
88 text
89
90
91 Modified with one variable:
92 steps:
93 - run:
94 code: |
95 to_modify = load(yaml_snippet, schema)
96 to_modify['b']['x'] = 2
97 to_modify['c'][0]['a'] = '3'
98 print(to_modify.as_yaml())
99 will output: |-
100 # Some comment
101
102 a: â # value comment
103
104 # Another comment
105 b:
106 x: 2
107 y: 5
108 c:
109 - a: 3
110 - b: 2
111
112 Text across lines:
113 steps:
114 - run:
115 code: |
116 to_modify = load(yaml_snippet, schema)
117
118 to_modify['c'][0]['a'] = "text\nacross\nlines"
119 print(to_modify.as_yaml())
120 will output: |-
121 # Some comment
122
123 a: â # value comment
124
125 # Another comment
126 b:
127 x: 4
128 y: 5
129 c:
130 - a: |-
131 text
132 across
133 lines
134 - b: 2
135
136
137 With empty dict:
138 steps:
139 - run:
140 code: |
141 to_modify = load(yaml_snippet, schema)
142
143 to_modify['c'] = {}
144 print(to_modify.as_yaml())
145 will output: |-
146 # Some comment
147
148 a: â # value comment
149
150 # Another comment
151 b:
152 x: 4
153 y: 5
154 c: