v2 / vlib / x / json2 / tests / json2_tests / decoder_test.v
75 lines · 63 sloc · 1.69 KB · f94fa74a957971b7fd0a2bcd452ff6453c283f39
Raw
1import x.json2 as json
2
3fn test_raw_decode_string() {
4 str := json.decode[json.Any]('"Hello!"')!
5 assert str.str() == 'Hello!'
6}
7
8fn test_raw_decode_string_escape() {
9 jstr := json.decode[json.Any]('"\u001b"')!
10 str := jstr.str()
11 assert str.len == 1
12 assert str[0] == 27
13}
14
15fn test_raw_decode_number() {
16 num := json.decode[json.Any]('123')!
17 assert num.int() == 123
18}
19
20fn test_raw_decode_array() {
21 raw_arr := json.decode[json.Any]('["Foo", 1]')!
22 arr := raw_arr.as_array()
23 assert arr[0] or { 0 }.str() == 'Foo'
24 assert arr[1] or { 0 }.int() == 1
25}
26
27fn test_raw_decode_bool() {
28 bol := json.decode[json.Any]('false')!
29 assert bol.bool() == false
30}
31
32fn test_raw_decode_map() {
33 raw_mp := json.decode[json.Any]('{"name":"Bob","age":20}')!
34 mp := raw_mp.as_map()
35 assert mp['name'] or { 0 }.str() == 'Bob'
36 assert mp['age'] or { 0 }.int() == 20
37}
38
39fn test_raw_decode_string_with_dollarsign() {
40 str := json.decode[json.Any](r'"Hello $world"')!
41 assert str.str() == r'Hello $world'
42}
43
44fn test_raw_decode_map_with_whitespaces() {
45 raw_mp := json.decode[json.Any](' \n\t{"name":"Bob","age":20}\n\t')!
46 mp := raw_mp.as_map()
47 assert mp['name'] or { 0 }.str() == 'Bob'
48 assert mp['age'] or { 0 }.int() == 20
49}
50
51fn test_raw_decode_map_invalid() {
52 json.decode[json.Any]('{"name","Bob","age":20}') or {
53 if err is json.JsonDecodeError {
54 assert err.line == 1
55 assert err.character == 8
56 assert err.message == 'Syntax: expected `:`, got `,`'
57 }
58
59 return
60 }
61 assert false
62}
63
64fn test_raw_decode_array_invalid() {
65 json.decode[json.Any]('["Foo", 1,}') or {
66 if err is json.JsonDecodeError {
67 assert err.line == 1
68 assert err.character == 11
69 assert err.message == 'Syntax: unknown value kind'
70 }
71
72 return
73 }
74 assert false
75}
76