Core

/app/util/json_test.go (2.1 KB)

  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package util_test

import (
"reflect"
"testing"

"{{{ .Package }}}/app/util"
)

func TestToJSON(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input any
want string
}{
{"Simple", map[string]int{"a": 1, "b": 2}, "{\n \"a\": 1,\n \"b\": 2\n}"},
{"Complex", struct {
A int
B string
}{1, "test"}, "{\n \"A\": 1,\n \"B\": \"test\"\n}"},
}

for _, tt := range tests {
x := tt
t.Run(x.name, func(t *testing.T) {
t.Parallel()
if got := util.ToJSON(x.input); got != x.want {
t.Errorf("ToJSON() = %v, want %v", got, x.want)
}
})
}
}

func TestToJSONCompact(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input any
want string
}{
{"Simple", map[string]int{"a": 1, "b": 2}, "{\"a\":1,\"b\":2}"},
{"Complex", struct {
A int
B string
}{1, "test"}, "{\"A\":1,\"B\":\"test\"}"},
}

for _, tt := range tests {
x := tt
t.Run(x.name, func(t *testing.T) {
t.Parallel()
if got := util.ToJSONCompact(x.input); got != x.want {
t.Errorf("ToJSONCompact() = %v, want %v", got, x.want)
}
})
}
}

func TestFromJSON(t *testing.T) {
t.Parallel()
type testStruct struct {
A int
B string
}

tests := []struct {
name string
input []byte
want testStruct
}{
{"Valid", []byte(`{"A":1,"B":"test"}`), testStruct{1, "test"}},
}

for _, tt := range tests {
x := tt
t.Run(x.name, func(t *testing.T) {
t.Parallel()
var got testStruct
if err := util.FromJSON(x.input, &got); err != nil {
t.Errorf("FromJSON() error = %v", err)
}
if !reflect.DeepEqual(got, x.want) {
t.Errorf("FromJSON() = %v, want %v", got, x.want)
}
})
}
}

func TestFromJSONString(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input []byte
want string
}{
{"Valid", []byte(`"test"`), "test"},
}

for _, tt := range tests {
x := tt
t.Run(x.name, func(t *testing.T) {
t.Parallel()
got, err := util.FromJSONString(x.input)
if err != nil {
t.Errorf("FromJSONString() error = %v", err)
}
if got != x.want {
t.Errorf("FromJSONString() = %v, want %v", got, x.want)
}
})
}
}