v / vlib / yaml / yaml_test.v
98 lines · 86 sloc · 1.94 KB · d96fe54c0a96fd6d651e9cb3c61b137ccc5c7dbe
Raw
1module yaml
2
3import os
4
5enum Role {
6 worker
7 manager
8}
9
10struct Address {
11 city string
12 zip int
13}
14
15struct AppConfig {
16 name string
17 role Role @[json: 'role']
18 enabled bool
19 ports []int
20 address Address
21 notes string
22}
23
24fn test_parse_doc_queries_and_block_scalars() ! {
25 doc := parse_text('title: Example
26config: { enabled: true, retries: 3 }
27servers:
28 - host: api.local
29 ports: [80, 443]
30 - host: jobs.local
31quoted:
32 "a.b": 7
33notes: |
34 first line
35 second line
36folded: >
37 hello
38 world
39')!
40
41 assert doc.value('title').string() == 'Example'
42 assert doc.value('config.enabled').bool()
43 assert doc.value('config.retries').int() == 3
44 assert doc.value('servers[0].host').string() == 'api.local'
45 assert doc.value('servers[0].ports[1]').int() == 443
46 assert doc.value('quoted."a.b"').int() == 7
47 assert doc.value('notes').string() == 'first line\nsecond line\n'
48 assert doc.value('folded').string() == 'hello world\n'
49}
50
51fn test_generic_encode_decode_with_json_attrs() ! {
52 config := AppConfig{
53 name: 'worker'
54 role: .manager
55 enabled: true
56 ports: [8080, 9090]
57 address: Address{
58 city: 'Springwood'
59 zip: 1428
60 }
61 notes: 'line one\nline two'
62 }
63
64 encoded := encode(config)
65 assert encoded.contains('"role": "manager"')
66 assert encoded.contains('"address":')
67 assert encoded.contains('- 8080')
68
69 decoded := decode[AppConfig](encoded)!
70 assert decoded == config
71}
72
73fn test_file_helpers() ! {
74 path := os.join_path(os.vtmp_dir(), 'yaml_test_${os.getpid()}.yml')
75 defer {
76 os.rm(path) or {}
77 }
78 config := AppConfig{
79 name: 'batch11'
80 role: .worker
81 enabled: false
82 ports: [7000]
83 address: Address{
84 city: 'Moscow'
85 zip: 101000
86 }
87 notes: 'plain'
88 }
89
90 encode_file(path, config)!
91 decoded := decode_file[AppConfig](path)!
92 assert decoded == config
93
94 doc := parse_file(path)!
95 assert doc.value('name').string() == 'batch11'
96 assert doc.value('role').string() == 'worker'
97 assert doc.value('address.city').string() == 'Moscow'
98}
99