Debian Codegraph @

decode_type_error_test.go

raw
1 package json_test
2
3 import (
4 stdjson "encoding/json"
5 "errors"
6 "fmt"
7 "reflect"
8 "strings"
9 "testing"
10
11 json "github.com/goccy/go-json"
12 )
13
14 // The type errors of the decoding are the ones of encoding/json of the running Go: a value which is not of the
15 // type of its destination is skipped, the decoding goes on, and the first such error is returned, unless the
16 // input has a syntax error, which is returned instead. Its Value, Type, Offset, Struct and Field, and its
17 // message, are the ones of encoding/json, whose rules differ between Go 1.27, which is made of
18 // encoding/json/v2, and the earlier versions.
19
20 type typeErrorInner struct {
21 F int
22 G string
23 H float64
24 }
25
26 type typeErrorEmbedded struct {
27 E int
28 }
29
30 type typeErrorOuter struct {
31 typeErrorEmbedded
32 A typeErrorInner
33 L []typeErrorInner
34 M map[string]typeErrorInner
35 P *typeErrorInner
36 X int
37 U uint8
38 S []int
39 Arr [2]int
40 B bool
41 Str string
42 Bytes []byte
43 C complex128
44 N json.Number
45 Tagged int `json:"tagged"`
46 Q int `json:"q,string"`
47 Q8 int8 `json:"q8,string"`
48 QB bool `json:"qb,string"`
49 QF float32 `json:"qf,string"`
50 QS string `json:"qs,string"`
51 QP *int `json:"qp,string"`
52 Last int
53 }
54
55 // typeErrorValues are the JSON values which are put where a value of each field is.
56 var typeErrorValues = []string{
57 `1`, `-1`, `1.5`, `1e3`, `300`, `"s"`, `"1"`, `""`, `"true"`, `"1.5"`, `"300"`, `"99999999999999999999"`,
58 `true`, `null`, `[1]`, `[]`, `{"F":1}`, `{}`,
59 }
60
61 // typeErrorPlaces are the places of a value in a document of typeErrorOuter, %s being the value.
62 var typeErrorPlaces = []string{
63 `{"X":%s,"Last":1}`,
64 `{"U":%s,"Last":1}`,
65 `{"E":%s,"Last":1}`,
66 `{"A":{"F":%s,"G":"g"},"Last":1}`,
67 `{"A":{"G":%s},"Last":1}`,
68 `{"A":{"H":%s},"Last":1}`,
69 `{"A":%s,"Last":1}`,
70 `{"L":[{"F":1},{"F":%s}],"Last":1}`,
71 `{"L":%s,"Last":1}`,
72 `{"M":{"k":{"G":%s}},"Last":1}`,
73 `{"M":{"k":%s},"Last":1}`,
74 `{"M":%s,"Last":1}`,
75 `{"P":{"F":%s},"Last":1}`,
76 `{"P":%s,"Last":1}`,
77 `{"S":[1,%s,3],"Last":1}`,
78 `{"S":%s,"Last":1}`,
79 `{"Arr":[%s,2],"Last":1}`,
80 `{"Arr":%s,"Last":1}`,
81 `{"B":%s,"Last":1}`,
82 `{"Str":%s,"Last":1}`,
83 `{"Bytes":%s,"Last":1}`,
84 `{"C":%s,"Last":1}`,
85 `{"N":%s,"Last":1}`,
86 `{"tagged":%s,"Last":1}`,
87 `{"q":%s,"Last":1}`,
88 `{"q8":%s,"Last":1}`,
89 `{"qb":%s,"Last":1}`,
90 `{"qf":%s,"Last":1}`,
91 `{"qs":%s,"Last":1}`,
92 `{"qp":%s,"Last":1}`,
93 `{"X":%s,"A":{"F":"first"},"Last":1}`,
94 `{"A":{"F":"first"},"X":%s,"Last":1}`,
95 }
96
97 // describeTypeError returns what the test compares of an error: its kind, and the fields and the message of a
98 // type error.
99 func describeTypeError(err error) string {
100 if err == nil {
101 return "<nil>"
102 }
103 var stdErr *stdjson.UnmarshalTypeError
104 if errors.As(err, &stdErr) {
105 return fmt.Sprintf("UnmarshalTypeError Value=%q Type=%v Offset=%d Struct=%q Field=%q: %s",
106 stdErr.Value, stdErr.Type, stdErr.Offset, stdErr.Struct, stdErr.Field, err)
107 }
108 var goErr *json.UnmarshalTypeError
109 if errors.As(err, &goErr) {
110 return fmt.Sprintf("UnmarshalTypeError Value=%q Type=%v Offset=%d Struct=%q Field=%q: %s",
111 goErr.Value, goErr.Type, goErr.Offset, goErr.Struct, goErr.Field, err)
112 }
113 var stdSyntax *stdjson.SyntaxError
114 var goSyntax *json.SyntaxError
115 if errors.As(err, &stdSyntax) || errors.As(err, &goSyntax) {
116 // the messages of the syntax errors are not compared here
117 return "SyntaxError"
118 }
119 return err.Error()
120 }
121
122 func checkTypeError(t *testing.T, doc string, newValue func() any) {
123 t.Helper()
124 want, got := newValue(), newValue()
125 wantErr := describeTypeError(stdjson.Unmarshal([]byte(doc), want))
126 gotErr := describeTypeError(json.Unmarshal([]byte(doc), got))
127 if gotErr != wantErr {
128 t.Errorf("%s:\n got %s\nwant %s", doc, gotErr, wantErr)
129 return
130 }
131 if wantErr == "SyntaxError" {
132 // encoding/json validates the whole input before it decodes anything, and go-json decodes the values
133 // before a syntax error: the values decoded before it differ.
134 return
135 }
136 if !reflect.DeepEqual(got, want) {
137 t.Errorf("%s: decoded %+v, want %+v", doc, reflect.ValueOf(got).Elem(), reflect.ValueOf(want).Elem())
138 }
139 }
140
141 func TestDecodeTypeErrors(t *testing.T) {
142 for _, place := range typeErrorPlaces {
143 for _, value := range typeErrorValues {
144 checkTypeError(t, fmt.Sprintf(place, value), func() any { return new(typeErrorOuter) })
145 }
146 }
147 }
148
149 func TestDecodeTypeErrorsOfValues(t *testing.T) {
150 // A value which is not in a struct, of each kind, as a value of a slice, of a map and of an interface.
151 targets := []func() any{
152 func() any { return new(int) }, func() any { return new(uint) }, func() any { return new(int8) },
153 func() any { return new(float32) }, func() any { return new(float64) }, func() any { return new(bool) },
154 func() any { return new(string) }, func() any { return new([]int) }, func() any { return new([2]int) },
155 func() any { return new(map[string]int) }, func() any { return new(map[int]int) },
156 func() any { return new(typeErrorInner) }, func() any { return new([]byte) },
157 func() any { return new(complex128) }, func() any { return new(json.Number) },
158 func() any { return new(*int) }, func() any { return new([]typeErrorInner) },
159 func() any { return new(map[string]typeErrorInner) }, func() any { return new(any) },
160 }
161 for _, newValue := range targets {
162 for _, value := range typeErrorValues {
163 checkTypeError(t, value, newValue)
164 checkTypeError(t, " "+value+" ", newValue)
165 }
166 }
167 for _, doc := range []string{
168 `{"x":1}`, `{"1":1,"x":2,"3":3}`, `{"300":1}`, `{"-1":1}`, `{"1.5":1}`, `{"true":1,"false":2}`, `{}`,
169 } {
170 checkTypeError(t, doc, func() any { return new(map[int8]int) })
171 checkTypeError(t, doc, func() any { return new(map[uint]int) })
172 checkTypeError(t, doc, func() any { return new(map[float64]int) })
173 checkTypeError(t, doc, func() any { return new(map[bool]int) })
174 checkTypeError(t, doc, func() any { return new(map[typeErrorEmbedded]int) })
175 }
176 }
177
178 func TestDecodeTypeErrorsBeforeSyntaxErrors(t *testing.T) {
179 // A syntax error anywhere in the input is returned instead of a type error before it.
180 for _, doc := range []string{
181 `{"X":"s","Last":1,}`,
182 `{"X":"s","Last":1} x`,
183 `{"X":"s","A":{"F":1,}}`,
184 `{"X":"s","L":[1 2]}`,
185 `{"X":"s","Str":"\x"}`,
186 `{"A":{"F":"s"},"X":tru}`,
187 } {
188 checkTypeError(t, doc, func() any { return new(typeErrorOuter) })
189 }
190 }
191
192 func TestDecodeTypeErrorsOfStream(t *testing.T) {
193 // The decoder of a stream returns the type error of a value, and decodes the next ones.
194 const input = `{"X":1} {"X":"s","Last":2} {"A":{"F":true}} {"X":3}`
195 std := stdjson.NewDecoder(strings.NewReader(input))
196 dec := json.NewDecoder(strings.NewReader(input))
197 for i := 0; i < 4; i++ {
198 var want, got typeErrorOuter
199 wantErr := describeTypeError(std.Decode(&want))
200 gotErr := describeTypeError(dec.Decode(&got))
201 if gotErr != wantErr {
202 t.Errorf("value %d:\n got %s\nwant %s", i, gotErr, wantErr)
203 }
204 if !reflect.DeepEqual(got, want) {
205 t.Errorf("value %d: decoded %+v, want %+v", i, got, want)
206 }
207 }
208 }
209
210 func TestDecodeTypeErrorsNotKept(t *testing.T) {
211 // A type error of a decoding which fails with a syntax error is not kept for the next decoding, which reuses
212 // the context.
213 for i := 0; i < 100; i++ {
214 var v typeErrorOuter
215 if err := json.Unmarshal([]byte(`{"X":"s","Last":1,}`), &v); err == nil {
216 t.Fatal("expected a syntax error")
217 }
218 if err := json.Unmarshal([]byte(`{"X":1,"Last":1}`), &v); err != nil {
219 t.Fatalf("got %v after a syntax error", err)
220 }
221 if err := json.UnmarshalOf([]byte(`{"X":"s","Last":1} x`), &v); err == nil {
222 t.Fatal("expected a syntax error")
223 }
224 if err := json.UnmarshalOf([]byte(`{"X":1,"Last":1}`), &v); err != nil {
225 t.Fatalf("got %v after a syntax error", err)
226 }
227 }
228 }
229
230 // typeErrorMethods is an interface type with methods, whose value is decoded into what it points to if it is a
231 // pointer, and is kept else.
232 type typeErrorMethods interface {
233 Method()
234 }
235
236 type typeErrorJSONValue struct{ Raw string }
237
238 func (v *typeErrorJSONValue) Method() {}
239
240 func (v *typeErrorJSONValue) UnmarshalJSON(b []byte) error {
241 v.Raw = string(b)
242 return nil
243 }
244
245 type typeErrorTextValue struct{ Text string }
246
247 func (v *typeErrorTextValue) Method() {}
248
249 func (v *typeErrorTextValue) UnmarshalText(b []byte) error {
250 v.Text = string(b)
251 return nil
252 }
253
254 type typeErrorPlainValue struct{ A int }
255
256 func (v *typeErrorPlainValue) Method() {}
257
258 type typeErrorValueType struct{ A int }
259
260 func (v typeErrorValueType) Method() {}
261
262 func TestDecodeTypeErrorsOfInterfaceValues(t *testing.T) {
263 // The value which an interface value holds is decoded into what it points to if it is a pointer, with the
264 // unmarshalers of the pointer type, whatever the interface type is. A value of an interface type with
265 // methods which is not a pointer is kept: null sets it to nil, and anything else is a type error.
266 var nilPlain *typeErrorPlainValue
267 values := []func() typeErrorMethods{
268 func() typeErrorMethods { return nil },
269 func() typeErrorMethods { return &typeErrorJSONValue{} },
270 func() typeErrorMethods { return &typeErrorTextValue{} },
271 func() typeErrorMethods { return &typeErrorPlainValue{A: 9} },
272 func() typeErrorMethods { return typeErrorValueType{A: 9} },
273 func() typeErrorMethods { return nilPlain },
274 }
275 type holder struct {
276 V typeErrorMethods
277 Last int
278 }
279 type anyHolder struct {
280 V any
281 Last int
282 }
283 for round := 0; round < 2; round++ {
284 for _, value := range []string{`{"A":1}`, `null`, `"text"`, `[1]`, `1`, `true`, ` false`, ` 12 `, ` {}`} {
285 for _, newValue := range values {
286 checkTypeError(t, `{"V":`+value+`,"Last":1}`, func() any { return &holder{V: newValue()} })
287 checkTypeError(t, `{"V":`+value+`,"Last":1}`, func() any { return &anyHolder{V: newValue()} })
288 }
289 }
290 }
291 }
292
293 func TestDecodeTypeErrorsOfKeysOfOtherCase(t *testing.T) {
294 // A key which matches a field in another case: encoding/json of Go 1.27 reports the path by the keys as the
295 // input has them.
296 type continent struct{ Name int }
297 type country struct {
298 Continent continent
299 Code int `json:"code"`
300 }
301 for _, doc := range []string{
302 `{"continent":{"name":"x"}}`,
303 `{"CONTINENT":{"NAME":"x"}}`,
304 `{"Continent":{"Name":"x"}}`,
305 `{"CODE":"x"}`,
306 `{"code":"x"}`,
307 } {
308 checkTypeError(t, doc, func() any { return new(country) })
309 }
310 }