Debian Codegraph @

hitch/story/build-yaml-document-from-scratch.story

raw
1 Build a YAML document from scratch in code:
2 docs: howto/build-yaml-document
3 based on: strictyaml
4 description: |
5 YAML documents can be built from combinations of dicts,
6 lists and strings if no schema is used.
7 given:
8 setup: |
9 from ensure import Ensure
10 from strictyaml import as_document
11 from collections import OrderedDict
12
13 # Can also use regular dict if an arbitrary ordering is ok
14 yaml = as_document(OrderedDict(
15 [(u"â", 'yes'), ("b", "hâllo"), ("c", ["1", "2", "3"])]
16 ))
17 variations:
18 Then dump:
19 steps:
20 - Run:
21 code: print(yaml.as_yaml())
22 will output: |-
23 â: yes
24 b: hâllo
25 c:
26 - 1
27 - 2
28 - 3
29
30 However, any type that is not a string, dict or list cannot be parsed without a schema:
31 steps:
32 - run:
33 code: |
34 class RandomClass(object):
35 def __repr__(self):
36 return 'some random object'
37
38 as_document({"x": RandomClass()})
39 raises:
40 type: strictyaml.exceptions.YAMLSerializationError
41 message: |-
42 'some random object' is not a string
43
44 Empty dicts also cannot be serialized without a schema:
45 steps:
46 - run:
47 code: |
48 as_document({'hello': {}})
49 raises:
50 type: strictyaml.exceptions.YAMLSerializationError
51 message: Empty dicts are not serializable to StrictYAML unless schema
52 is used.
53
54 Neither can lists:
55 steps:
56 - run:
57 code: |
58 as_document({'hello': []})
59 raises:
60 type: strictyaml.exceptions.YAMLSerializationError
61 message: Empty lists are not serializable to StrictYAML unless schema
62 is used.
63
64 You can grab line numbers from the object that is serialized:
65 steps:
66 - Run:
67 code: |
68 Ensure(yaml.start_line).equals(1)