-
Notifications
You must be signed in to change notification settings - Fork 41
/
json_test.go
158 lines (152 loc) · 2.4 KB
/
json_test.go
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package jsondiff
import (
"encoding/json"
"os"
"testing"
)
func Test_findKey(t *testing.T) {
for _, tc := range []struct {
json string
key string
want string
}{
{
``,
"foo",
``,
},
{
`{"a":"foo","b":"bar"}`,
"b",
`"bar"`,
},
{
`{"a":[1,2,3],"b":[3,4,5]}`,
"a",
`[1,2,3]`,
},
{
`{"":{"a":"b"}}`,
"",
`{"a":"b"}`,
},
} {
// Valid JSON input and result.
if len(tc.json) != 0 && !json.Valid([]byte(tc.json)) {
t.Errorf("invalid JSON input: %q", tc.json)
}
if len(tc.want) != 0 && !json.Valid([]byte(tc.want)) {
t.Errorf("invalid JSON result: %q", tc.want)
}
s := findKey(tc.json, tc.key)
if s != tc.want {
t.Errorf("got %q, want %q", s, tc.want)
}
}
}
func Test_findIndex(t *testing.T) {
for _, tc := range []struct {
json string
index int
want string
}{
{
``,
1,
``,
},
{
`["a","b","c"]`,
1,
`"b"`,
},
{
`[1,2,3,4,5]`,
3,
`4`,
},
{
`[false,true,"foo","bar"]`,
3,
`"bar"`,
},
{
`[["a","b"],[1,2]]`,
0,
`["a","b"]`,
},
{
`[["a","b"],[1,2]]`,
1,
`[1,2]`,
},
{
`[{"a":"b"},{"c":"d"}]`,
1,
`{"c":"d"}`,
},
{
`["\"a","\\b]","\""]`,
2,
`"\""`,
},
{
`[["\"a"],["\\\b"]]`,
0,
`["\"a"]`,
},
{
`[["\"a"],["fjj\\\"]\""]]`,
1,
`["fjj\\\"]\""]`,
},
{
`[[{"a":"1"},{"b":"2"}],[{"c":"3"},{"d":"4"}]]`,
1,
`[{"c":"3"},{"d":"4"}]`,
},
{
`[[],""]`,
0,
`[]`,
},
{
`[{"a":[1,2,3]},{"b":{"c":[4,5,6]}}]`,
0,
`{"a":[1,2,3]}`,
},
{
`[{"a":[1,2,3]},{"b":{"c":[4,5,6]}}]`,
1,
`{"b":{"c":[4,5,6]}}`,
},
{
`[]`,
0,
``,
},
} {
// Valid JSON input and result.
if len(tc.json) != 0 && !json.Valid([]byte(tc.json)) {
t.Errorf("invalid JSON input: %q", tc.json)
}
if len(tc.want) != 0 && !json.Valid([]byte(tc.want)) {
t.Errorf("invalid JSON result: %q", tc.want)
}
s := findIndex(tc.json, tc.index)
if s != tc.want {
t.Errorf("got %q, want %q", s, tc.want)
}
}
}
func Test_compactInPlace(t *testing.T) {
small, err := os.ReadFile("testdata/benchs/small/source.json")
if err != nil {
t.Fatal(err)
}
b := compactInPlace(small)
const want = `{"pine":true,"silence":{"feathers":"could","lion":false,"provide":["lake",1886677335,"research",false],"ate":"nearest"},"already":true,"it":false}`
if string(b) != want {
t.Errorf("got %q, want %q", b, want)
}
}