Debian Codegraph @

hitch/story/map-with-key-validator.story

raw
1 Mapping with defined keys and a custom key validator (Map):
2 docs: compound/mapping-with-slug-keys
3 based on: strictyaml
4 experimental: yes
5 description: |
6 A typical mapping except that the key values are determined
7 by the value provided by the validator.
8 given:
9 setup: |
10 from collections import OrderedDict
11 from strictyaml import Map, Optional, Str, Seq, load, ScalarValidator
12 from ensure import Ensure
13
14 # This example uses slugify from the "python-slugify" package
15 from slugify import slugify
16
17 class Slug(ScalarValidator):
18 def validate_scalar(self, chunk):
19 return slugify(unicode(chunk.contents))
20
21 schema = Map({
22 "name": Str(),
23 Optional("country-code"): Str(),
24 "dial-code": Str(),
25 "official-languages": Seq(Str())
26 }, key_validator=Slug())
27 yaml_snippet: |
28 Name: United Kingdom
29 country-code: GB
30 DIAL CODE: +44
31 official languages:
32 - English
33 - Welsh
34 steps:
35 - Run: |
36 Ensure(load(yaml_snippet, schema).data).equals(
37 {
38 "name": "United Kingdom",
39 "country-code": "GB",
40 "dial-code": "+44",
41 "official-languages": ["English", "Welsh"],
42 }
43 )
44
45
46 Slug key validator revalidation bug:
47 based on: Mapping with defined keys and a custom key validator (Map)
48 steps:
49 - Run: |
50 yaml = load(yaml_snippet, schema)
51 yaml.revalidate(schema)
52
53
54 Slug key validation getitem setitem and delitem:
55 description: |
56 You can set properties on slug key validated by
57 using a key that turns into the same slug as the text
58 key. E.g.
59
60 DIAL CODE -> dial-code
61 dial code -> dial-code
62
63 Therefore treated as the same key.
64 based on: Mapping with defined keys and a custom key validator (Map)
65 variations:
66 Getting:
67 steps:
68 - Run:
69 code: |
70 yaml = load(yaml_snippet, schema)
71 Ensure(yaml['dial code']).equals("+44")
72
73 Setting:
74 steps:
75 - Run:
76 code: |
77 yaml = load(yaml_snippet, schema)
78 yaml.revalidate(schema)
79 yaml['dial-code'] = "+48"
80 print(yaml.as_yaml())
81 will output: |-
82 Name: United Kingdom
83 country-code: GB
84 DIAL CODE: +48
85 official languages:
86 - English
87 - Welsh
88
89 Deleting:
90 steps:
91 - Run:
92 code: |
93 yaml = load(yaml_snippet, schema)
94 del yaml['dial code']
95 print(yaml.as_yaml())
96 will output: |-
97 Name: United Kingdom
98 country-code: GB
99 official languages:
100 - English
101 - Welsh