v
Зеркало из https://github.com/vlang/v
1import x.json2.decoder2 as json
2import time
3
4const fixed_time = time.new(
5year: 2022
6month: 3
7day: 11
8hour: 13
9minute: 54
10second: 25
11)
12
13type StringAlias = string
14type BoolAlias = bool
15type IntAlias = int
16type TimeAlias = time.Time
17type StructAlias = StructType[int]
18type EnumAlias = Enumerates
19
20type SumTypes = StructType[string] | []SumTypes | []string | bool | string | time.Time | u32
21
22enum Enumerates {
23a
24b
25c
26d
27e = 99
28f
29}
30
31struct StructType[T] {
32mut:
33val T
34}
35
36struct StructTypeOption[T] {
37mut:
38val ?T
39}
40
41struct StructTypePointer[T] {
42mut:
43val &T
44}
45
46fn test_types() {
47assert json.decode[StructType[string]]('{"val": ""}')!.val == ''
48
49assert json.decode[StructType[string]]('{"val": "2"}')!.val == '2'
50
51assert json.decode[StructType[int]]('{"val": 2}')!.val == 2
52
53assert json.decode[StructType[map[string]string]]('{"val": {"val": "test"}}')!.val['val'] == 'test'
54
55assert json.decode[StructType[Enumerates]]('{"val": 0}')!.val == Enumerates.a
56assert json.decode[StructType[Enumerates]]('{"val": 1}')!.val == Enumerates.b
57
58assert json.decode[StructType[IntAlias]]('{"val": 2}')!.val == IntAlias(2)
59assert json.decode[StructType[StringAlias]]('{"val": "2"}')!.val == StringAlias('2')
60
61assert json.decode[StructType[time.Time]]('{"val": "2022-03-11T13:54:25.000Z"}')!.val.year == fixed_time.year
62assert json.decode[StructType[time.Time]]('{"val": "2022-03-11T13:54:25.000Z"}')!.val.month == fixed_time.month
63assert json.decode[StructType[time.Time]]('{"val": "2022-03-11T13:54:25.000Z"}')!.val.day == fixed_time.day
64assert json.decode[StructType[time.Time]]('{"val": "2022-03-11T13:54:25.000Z"}')!.val.hour == fixed_time.hour
65assert json.decode[StructType[time.Time]]('{"val": "2022-03-11T13:54:25.000Z"}')!.val.minute == fixed_time.minute
66assert json.decode[StructType[time.Time]]('{"val": "2022-03-11T13:54:25.000Z"}')!.val.second == fixed_time.second
67assert json.decode[StructType[time.Time]]('{"val": "2022-03-11T13:54:25.000Z"}')!.val.unix() == fixed_time.unix()
68}
69
70fn test_option_types() {
71if x := json.decode[StructTypeOption[string]]('{}')!.val {
72assert false, 'Should return none'
73} else {
74assert err.msg() == ''
75assert true
76}
77
78if x := json.decode[StructTypeOption[string]]('{"val": "2"}')!.val {
79assert x == '2'
80} else {
81assert false, 'Should not return none'
82}
83}
84