v2 / vlib / json / tests / json_option_test.v
68 lines · 54 sloc · 1.14 KB · 8ebbacecd60366ac4ba68aa35f9b0e7a0e56ff61
Raw
1import json
2
3pub struct MyStruct {
4pub mut:
5 valuea int
6}
7
8pub struct MyStruct2 {
9pub mut:
10 valuea int
11 valueb ?MyStruct
12}
13
14struct Node {
15 location NodeLocation @[json: 'loc']
16}
17
18struct NodeLocation {
19 source_file ?SourceFile @[json: 'includedFrom']
20}
21
22struct SourceFile {
23 path string @[json: 'file']
24}
25
26fn test_encode_decode() {
27 assert json.encode(MyStruct2{ valuea: 1 }) == '{"valuea":1}'
28
29 assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{
30 valuea: 1
31 valueb: none
32 }
33}
34
35fn test_encode_decode2() {
36 assert json.encode(MyStruct2{ valuea: 1, valueb: none }) == '{"valuea":1}'
37
38 assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{
39 valuea: 1
40 valueb: none
41 }
42}
43
44fn test_encode_decode3() {
45 assert json.encode(MyStruct2{
46 valuea: 1
47 valueb: MyStruct{
48 valuea: 123
49 }
50 }) == '{"valuea":1,"valueb":{"valuea":123}}'
51
52 assert json.decode(MyStruct2, '{"valuea": 1}')! == MyStruct2{
53 valuea: 1
54 valueb: none
55 }
56}
57
58fn test_main() {
59 node := json.decode(Node, '{"loc": { "includedFrom": { "file": "/bin/foo" } } }')!
60
61 source_file := node.location.source_file or {
62 SourceFile{
63 path: '-'
64 }
65 }
66
67 assert source_file.path == '/bin/foo'
68}
69