Debian Codegraph @

hitch/story/decimal.story

raw
1 Decimal numbers (Decimal):
2 docs: scalar/decimal
3 based on: strictyaml
4 description: |
5 StrictYAML parses to a YAML object representing
6 a decimal, not the value directly to give you more
7 flexibility and control over what you can do with the
8 YAML.
9
10 This is what that can object can do - in many
11 cases if parsed as a decimal, it will behave in
12 the same way.
13
14 To get a python decimal.Decimal object, use .data.
15
16 Parsing and validating as a Decimal is best for
17 values which require precision, like prices.
18 given:
19 setup: |
20 from strictyaml import Map, Decimal, load
21 from decimal import Decimal as Dec
22 from ensure import Ensure
23
24 schema = Map({"a": Decimal(), "b": Decimal()})
25
26 yaml_snippet: |
27 a: 1.00000000000000000001
28 b: 5.4135
29 variations:
30 .data to get Decimal object:
31 steps:
32 - Run: Ensure(type(load(yaml_snippet, schema)["a"].data) is Dec).is_true()
33
34 Valid:
35 steps:
36 - Run: |
37 Ensure(load(yaml_snippet, schema)).equals({"a": Dec('1.00000000000000000001'), "b": Dec('5.4135')})
38
39 Cast to str:
40 steps:
41 - Run:
42 Ensure(str(load(yaml_snippet, schema)['a'])).equals("1.00000000000000000001")
43
44
45 Cast to float:
46 steps:
47 - Run:
48 Ensure(float(load(yaml_snippet, schema)["a"])).equals(1.0)
49
50 Greater than:
51 steps:
52 - Run:
53 Ensure(load(yaml_snippet, schema)["a"] > Dec('1.0')).is_true()
54
55 Less than which would not work for float:
56 steps:
57 - Run:
58 Ensure(load(yaml_snippet, schema)["a"] < Dec('1.00000000000000000002')).is_true()
59
60 Cannot cast to bool:
61 steps:
62 - Run:
63 code: bool(load(yaml_snippet, schema)['a'])
64 raises:
65 message: |-
66 Cannot cast 'YAML(1.00000000000000000001)' to bool.
67 Use bool(yamlobj.data) or bool(yamlobj.text) instead.
68
69 Invalid:
70 given:
71 yaml_snippet: |
72 a: string
73 b: 2
74 steps:
75 - Run:
76 code: load(yaml_snippet, schema)
77 raises:
78 type: strictyaml.exceptions.YAMLValidationError
79 message: |-
80 when expecting a decimal
81 found arbitrary text
82 in "<unicode string>", line 1, column 1:
83 a: string
84 ^ (line: 1)