v2 / vlib / toml / tests / reflect_test.v
108 lines · 88 sloc · 1.95 KB · 757929392e0e7a75fc1272116460981e589737d5
Raw
1import toml
2
3const toml_text = '# This TOML can reflect to a struct
4name = "Tom"
5age = 45
6height = 1.97
7
8birthday = 1980-04-23
9
10strings = [
11 "v matures",
12 "like rings",
13 "spread in the",
14 "water"
15]
16
17bools = [true, false, true, true]
18
19bools_br = [
20 true,
21 false,
22 true,
23 true
24]
25
26floats = [0.0, 1.0, 2.0, 3.0]
27
28floats_br = [
29 0.0,
30 1.05,
31 2.025,
32 3.5001
33]
34
35int_map = {"a" = 0, "b" = 1, "c" = 2, "d" = 3}
36
37[bio]
38text = "Tom has done many great things"
39years_of_service = 5
40
41[field_remap]
42txt = "I am remapped"
43uint64 = 100
44
45[config]
46data = [ 1, 2, 3 ]
47levels = { "info" = 1, "warn" = 2, "critical" = 3 }
48'
49
50struct FieldRemap {
51 text string @[toml: 'txt']
52 num u64 @[toml: 'uint64']
53}
54
55struct Bio {
56 text string
57 years_of_service int
58}
59
60struct User {
61 name string
62 age int
63 height f64
64 birthday toml.Date
65 strings []string
66 bools []bool
67 bools_br []bool
68 floats []f32
69 floats_br []f32
70 int_map map[string]int
71
72 config toml.Any
73mut:
74 bio Bio
75 remap FieldRemap
76}
77
78fn test_reflect() {
79 toml_doc := toml.parse_text(toml_text) or { panic(err) }
80
81 mut user := toml_doc.reflect[User]()
82 user.bio = toml_doc.value('bio').reflect[Bio]()
83 user.remap = toml_doc.value('field_remap').reflect[FieldRemap]()
84
85 assert user.name == 'Tom'
86 assert user.age == 45
87 assert user.height == 1.97
88 assert user.birthday.str() == '1980-04-23'
89 assert user.strings == ['v matures', 'like rings', 'spread in the', 'water']
90 assert user.bools == [true, false, true, true]
91 assert user.bools_br == [true, false, true, true]
92 assert user.floats == [f32(0.0), 1.0, 2.0, 3.0]
93 assert user.floats_br == [f32(0.0), 1.05, 2.025, 3.5001]
94 assert user.int_map == {
95 'a': 0
96 'b': 1
97 'c': 2
98 'd': 3
99 }
100 assert user.bio.text == 'Tom has done many great things'
101 assert user.bio.years_of_service == 5
102
103 assert user.remap.text == 'I am remapped'
104 assert user.remap.num == 100
105
106 assert user.config.value('data[0]').int() == 1
107 assert user.config.value('levels.warn').int() == 2
108}
109