Debian Codegraph @

hitch/story/boolean.story

raw
1 Boolean (Bool):
2 based on: strictyaml
3 docs: scalar/boolean
4 description: |
5 Boolean values can be parsed using a Bool validator.
6
7 It case-insensitively interprets "yes", "true", "1", "on" as "True", "y"
8 and their opposites as False.
9
10 Different values will trigger a validation error.
11
12 When updating boolean values on a YAML object with True or False, the roundtripped
13 string version is set to "yes" and "no".
14
15 To have your boolean values updated to a different yes/no string, update
16 with a string instead - e.g. "on" or "off".
17 given:
18 setup: |
19 from strictyaml import Bool, Str, MapPattern, load
20 from ensure import Ensure
21
22 schema = MapPattern(Str(), Bool())
23
24 yaml_snippet: |
25 a: yes
26 b: true
27 c: on
28 d: 1
29 e: True
30 f: Y
31
32 u: n
33 v: False
34 w: 0
35 x: Off
36 y: FALSE
37 z: no
38 variations:
39 Parse to YAML object:
40 steps:
41 - Run:
42 code: |
43 Ensure(load(yaml_snippet, schema)).equals({
44 "a": True, "b": True, "c": True, "d": True, "e": True, "f": True,
45 "u": False, "v": False, "w": False, "x": False, "y": False, "z": False,
46 })
47
48 YAML object should resolve to True or False:
49 steps:
50 - Run:
51 code: |
52 Ensure(load(yaml_snippet, schema)["w"]).equals(False)
53
54 Using .data you can get the actual boolean value parsed:
55 steps:
56 - Run:
57 code: |
58 assert load(yaml_snippet, schema)["a"].data is True
59
60 .text returns the text of the boolean YAML:
61 steps:
62 - Run:
63 code: |
64 Ensure(load(yaml_snippet, schema)["y"].text).equals("FALSE")
65
66 Update boolean values with string and bool type:
67 steps:
68 - Run:
69 code: |
70 yaml = load(yaml_snippet, schema)
71 yaml['a'] = 'no'
72 yaml['b'] = False
73 yaml['c'] = True
74 print(yaml.as_yaml())
75 will output: |-
76 a: no
77 b: no
78 c: yes
79 d: 1
80 e: True
81 f: Y
82
83 u: n
84 v: False
85 w: 0
86 x: Off
87 y: FALSE
88 z: no
89
90 Cannot cast boolean to string:
91 steps:
92 - Run:
93 code: str(load(yaml_snippet, schema)["y"])
94 raises:
95 type:
96 in python 2: exceptions.TypeError
97 in python 3: builtins.TypeError
98 message: |-
99 Cannot cast 'YAML(False)' to str.
100 Use str(yamlobj.data) or str(yamlobj.text) instead.
101
102 Different uninterpretable values raise validation error:
103 steps:
104 - Run:
105 code: |
106 load('a: yâs', schema)
107 raises:
108 type: strictyaml.exceptions.YAMLValidationError
109 message: |-
110 when expecting a boolean value (one of "yes", "true", "on", "1", "y", "no", "false", "off", "0", "n")
111 found arbitrary text
112 in "<unicode string>", line 1, column 1:
113 a: "y\xE2s"
114 ^ (line: 1)