Debian Codegraph @

decode_struct_key_test.go

raw
1 package json_test
2
3 import (
4 stdjson "encoding/json"
5 "fmt"
6 "reflect"
7 "strings"
8 "testing"
9
10 json "github.com/goccy/go-json"
11 )
12
13 // The keys of an object are matched with the fields of a struct as encoding/json does: an exact match first,
14 // then a match by case folding, in which the first field of a folded key wins. These tests decode the same
15 // inputs with encoding/json and compare.
16
17 func compareStructKeys[T any](t *testing.T, inputs []string) {
18 t.Helper()
19 for _, in := range inputs {
20 var want, got, gotOf T
21 errStd := stdjson.Unmarshal([]byte(in), &want)
22 err := json.Unmarshal([]byte(in), &got)
23 errOf := json.UnmarshalOf([]byte(in), &gotOf)
24 if (errStd == nil) != (err == nil) || (errStd == nil) != (errOf == nil) {
25 t.Fatalf("%s: encoding/json: %v, Unmarshal: %v, UnmarshalOf: %v", in, errStd, err, errOf)
26 }
27 if errStd != nil {
28 continue
29 }
30 if !reflect.DeepEqual(got, want) {
31 t.Fatalf("%s:\n got %+v\nwant %+v", in, got, want)
32 }
33 if !reflect.DeepEqual(gotOf, want) {
34 t.Fatalf("%s: UnmarshalOf:\n got %+v\nwant %+v", in, gotOf, want)
35 }
36 }
37 }
38
39 // keyVariants returns the key in cases of its letters.
40 func keyVariants(key string) []string {
41 return []string{key, strings.ToLower(key), strings.ToUpper(key), strings.ToUpper(key[:1]) + strings.ToLower(key[1:])}
42 }
43
44 type manyFields struct {
45 F1 string `json:"f1"`
46 F2 string `json:"f2"`
47 F3 string `json:"f3"`
48 F4 string `json:"f4"`
49 F5 string `json:"f5"`
50 F6 string `json:"f6"`
51 F7 string `json:"f7"`
52 F8 string `json:"f8"`
53 F9 string `json:"f9"`
54 F10 string `json:"f10"`
55 F11 string `json:"f11"`
56 F12 string `json:"f12"`
57 F13 string `json:"f13"`
58 F14 string `json:"f14"`
59 F15 string `json:"f15"`
60 F16 string `json:"f16"`
61 F17 string `json:"f17"`
62 F18 string `json:"someLongerFieldName"`
63 F19 string `json:"aVeryLongFieldNameWhichIsLongerThanSixteenBytes"`
64 }
65
66 func TestStructKeyCaseInsensitiveManyFields(t *testing.T) {
67 // A struct of more than 16 fields matches by case folding too ( issues 568 and 427 ).
68 var inputs []string
69 for _, key := range []string{"f1", "f17", "someLongerFieldName", "aVeryLongFieldNameWhichIsLongerThanSixteenBytes"} {
70 for _, v := range keyVariants(key) {
71 inputs = append(inputs, fmt.Sprintf(`{%q:"x"}`, v))
72 }
73 }
74 compareStructKeys[manyFields](t, inputs)
75 }
76
77 type embeddedTagBase struct {
78 B string `json:"bB"`
79 }
80
81 type embeddedTagOuter struct {
82 embeddedTagBase
83 A string `json:"aA"`
84 }
85
86 func TestStructKeyCaseInsensitiveEmbedded(t *testing.T) {
87 // The fields of an embedded struct whose tags have upper case letters match by case folding ( issue 470 ).
88 compareStructKeys[embeddedTagOuter](t, []string{
89 `{"Aa":"111","Bb":"222"}`, `{"aa":"1","bb":"2"}`, `{"AA":"1","BB":"2"}`, `{"aA":"1","bB":"2"}`,
90 })
91 }
92
93 type foldPrecedence struct {
94 Upper string `json:"NAME"`
95 Lower string `json:"name"`
96 Kelvin string `json:"\u212a"` // KELVIN SIGN folds to K
97 Sharp string `json:"ſ"` // LATIN SMALL LETTER LONG S folds to S
98 Uni string `json:"über"`
99 }
100
101 func TestStructKeyPrecedence(t *testing.T) {
102 // An exact match wins over a match by case folding, and the first field wins among the folded matches.
103 compareStructKeys[foldPrecedence](t, []string{
104 `{"NAME":"a"}`, `{"name":"a"}`, `{"Name":"a"}`, `{"nAmE":"a","NAME":"b"}`,
105 `{"k":"kelvin"}`, `{"K":"kelvin"}`, `{"\u212a":"kelvin"}`,
106 `{"s":"sharp"}`, `{"S":"sharp"}`, `{"ſ":"sharp"}`,
107 `{"über":"u"}`, `{"ÜBER":"u"}`, `{"Über":"u"}`,
108 })
109 }
110
111 type escapedKeys struct {
112 Slash string `json:"a/b"`
113 Quote string `json:"q\"uote"`
114 X string `json:"x/"`
115 Plain string `json:"plain"`
116 }
117
118 func TestStructKeyEscaped(t *testing.T) {
119 // Escaped keys are decoded before they are matched ( issues 604, 577, 575, 445 ).
120 compareStructKeys[escapedKeys](t, []string{
121 `{"a\/b":"1"}`, `{"a\/Z":"1"}`, `{"x\/":"4"}`, `{"q\"uote":"q"}`, `{"\u0070lain":"p"}`, `{"PL\u0041IN":"p"}`,
122 `{"\u0000":"z"}`, `{"a\u002fb":"1"}`,
123 // malformed
124 `{"\`, `{"\0d\`, `{"\q":1}`, `{"\0":1}`, `{"a\/`, `{"`, `{"a`, `{"a":`, `{"a":1,}`, `{"a" 1}`, `{1:2}`, `{null:1}`,
125 })
126 }
127
128 func TestStructKeyMalformedSequence(t *testing.T) {
129 // A sequence of malformed inputs never panics ( issue 604 ).
130 type doc struct {
131 ID string `json:"id"`
132 Meta map[string][]string `json:"meta"`
133 ContentMD string `json:"contentMd"`
134 }
135 inputs := []string{`[{"x":1},{"y":`, `{"\`, `{"\0d\`, `{"id`, `{"id":"\`, `{"contentMd":`}
136 for i := 0; i < 100; i++ {
137 var d doc
138 _ = json.Unmarshal([]byte(inputs[i%len(inputs)]), &d)
139 _ = json.UnmarshalOf([]byte(inputs[i%len(inputs)]), &d)
140 _ = json.NewDecoder(strings.NewReader(inputs[i%len(inputs)])).Decode(&d)
141 }
142 }
143
144 func TestStructKeyUnknownFields(t *testing.T) {
145 type small struct {
146 A int
147 B string
148 }
149 compareStructKeys[small](t, []string{
150 `{"unknown":1,"A":2}`, `{"unkn\u006fwn":{"x":[1,2]},"B":"b"}`, `{"a":1,"ab":2,"abc":3,"b":"x","bcd":"y"}`,
151 `{"` + strings.Repeat("long", 20) + `":1,"A":3}`, `{"élan":1,"A":4}`,
152 })
153 // The key of an unknown field is reported decoded.
154 dec := json.NewDecoder(strings.NewReader(`{"unkn\u006fwn":1}`))
155 dec.DisallowUnknownFields()
156 var v small
157 if err := dec.Decode(&v); err == nil || !strings.Contains(err.Error(), `"unknown"`) {
158 t.Fatalf("got %v", err)
159 }
160 }
161
162 func TestStructKeyEveryLength(t *testing.T) {
163 // A struct with a key of every length around the words the keys are read by, decoded from the middle and
164 // from the end of the input, through Unmarshal and through a Decoder. A key differs from the others of its
165 // length in its last byte, and "x" appended or its last byte removed makes a key of another field or of none.
166 var fields []reflect.StructField
167 var keys []string
168 lengths := []int{}
169 for n := 1; n <= 40; n++ {
170 lengths = append(lengths, n)
171 }
172 lengths = append(lengths, 47, 48, 49, 62, 63, 64, 65, 100)
173 for _, n := range lengths {
174 key := strings.Repeat("k", n-1) + string(rune('A'+n%26))
175 keys = append(keys, key)
176 fields = append(fields, reflect.StructField{
177 Name: fmt.Sprintf("F%d", n),
178 Type: reflect.TypeOf(""),
179 Tag: reflect.StructTag(fmt.Sprintf(`json:%q`, key)),
180 })
181 }
182 typ := reflect.StructOf(fields)
183 for _, key := range keys {
184 for _, v := range append(keyVariants(key), key+"x", key[:len(key)-1]) {
185 for _, in := range []string{
186 fmt.Sprintf(`{%q:"v","zzzzzzzzzzzzzzzzzzzz":1}`, v),
187 fmt.Sprintf(`{"a":1,%q:"v"}`, v),
188 } {
189 want := reflect.New(typ)
190 if err := stdjson.Unmarshal([]byte(in), want.Interface()); err != nil {
191 t.Fatal(err)
192 }
193 got := reflect.New(typ)
194 if err := json.Unmarshal([]byte(in), got.Interface()); err != nil {
195 t.Fatal(err)
196 }
197 stream := reflect.New(typ)
198 if err := json.NewDecoder(strings.NewReader(in)).Decode(stream.Interface()); err != nil {
199 t.Fatal(err)
200 }
201 if !reflect.DeepEqual(got.Interface(), want.Interface()) || !reflect.DeepEqual(stream.Interface(), want.Interface()) {
202 t.Fatalf("%s:\n got %+v\n stream %+v\n want %+v", in, got.Elem(), stream.Elem(), want.Elem())
203 }
204 }
205 }
206 }
207 }
208
209 type middleKeys struct {
210 A string `json:"prefix01_first_middle_suffix01"`
211 B string `json:"prefix01_other_middle_suffix01"`
212 C string `json:"prefix01_first_middle_and_more_suffix01"`
213 }
214
215 func TestStructKeyLongDifferInTheMiddle(t *testing.T) {
216 // Keys of more than 16 bytes whose first and last eight bytes are the same match by the bytes between them.
217 compareStructKeys[middleKeys](t, []string{
218 `{"prefix01_first_middle_suffix01":"a"}`, `{"prefix01_other_middle_suffix01":"b"}`,
219 `{"PREFIX01_OTHER_MIDDLE_SUFFIX01":"b"}`, `{"prefix01_third_middle_suffix01":"none"}`,
220 `{"prefix01_first_middle_and_more_suffix01":"c"}`, `{"prefix01_first_middle_and_less_suffix01":"none"}`,
221 `{"Prefix01_First_Middle_And_More_Suffix01":"c"}`,
222 })
223 }
224
225 type nonASCIIKeys struct {
226 Number int `json:"番号"`
227 Name string `json:"名前"`
228 Long string `json:"とても長いフィールドの名前です"`
229 LongToo string `json:"とても長いフィールドの名でした"`
230 Upper string `json:"Ärger"`
231 Lower string `json:"ärger"`
232 K string `json:"k"`
233 Mixed string `json:"user_名前_id"`
234 Accented string `json:"café"`
235 }
236
237 func TestStructKeyNotASCII(t *testing.T) {
238 // A key which is not ASCII is found by its bytes when it is the same as the key of a field, which wins over
239 // a match by case folding, and else by case folding as encoding/json does. A key which is not valid UTF-8 is
240 // of no field. No tag here is invalid UTF-8: encoding/json takes such a tag as the name of its field up to
241 // Go 1.26, and as it is from Go 1.27.
242 compareStructKeys[nonASCIIKeys](t, []string{
243 `{"番号":1,"名前":"a"}`, `{"番号 ":1}`, `{"番":1}`, `{"未知のキー":1,"名前":"b"}`,
244 `{"とても長いフィールドの名前です":"l"}`, `{"とても長いフィールドの名でした":"t"}`, `{"とても長いフィールドの名前でした":"none"}`,
245 `{"Ärger":"u"}`, `{"ärger":"l"}`, `{"ÄRGER":"u"}`, `{"äRGER":"l"}`,
246 `{"K":"kelvin"}`, `{"K":"upper"}`,
247 `{"user_名前_id":"m"}`, `{"USER_名前_ID":"m"}`,
248 "{\"bad\xffkey\":\"i\"}", `{"bad\ufffdkey":"i"}`,
249 `{"café":"c"}`, `{"CAFÉ":"c"}`, `{"caf\u00e9":"c"}`, `{"café`,
250 })
251 }
252
253 type asciiFoldKeys struct {
254 K string `json:"k"`
255 S string `json:"s"`
256 Name string `json:"name"`
257 Kind string `json:"kind"`
258 }
259
260 func TestStructKeyNotASCIIFoldsToASCII(t *testing.T) {
261 // A key of runes which are not ASCII, as they are and not escaped, matches an ASCII key which they fold to:
262 // the Kelvin sign folds to K and the long s to S. Other keys which are not ASCII match none.
263 compareStructKeys[asciiFoldKeys](t, []string{
264 "{\"K\":\"kelvin\"}", "{\"ſ\":\"long s\"}", "{\"Kind\":\"kind\"}", "{\"KKind\":\"none\"}",
265 "{\"nāme\":\"none\"}", "{\"名前\":\"none\",\"name\":\"n\"}", "{\"na\xffme\":\"none\"}",
266 })
267 var v asciiFoldKeys
268 dec := json.NewDecoder(strings.NewReader("{\"名\xff前\":1}"))
269 dec.DisallowUnknownFields()
270 if err := dec.Decode(&v); err == nil || !strings.Contains(err.Error(), "名�前") {
271 t.Fatalf("got %v", err)
272 }
273 }