Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/coder_test.go

raw
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package jsontext
6
7 import (
8 "bytes"
9 "errors"
10 "io"
11 "math"
12 "math/rand"
13 "path"
14 "reflect"
15 "strings"
16 "testing"
17
18 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsontest"
19 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
20 )
21
22 func E(err error) *SyntacticError {
23 return &SyntacticError{Err: err}
24 }
25
26 func newInvalidCharacterError(prefix, where string) *SyntacticError {
27 return E(jsonwire.NewInvalidCharacterError(prefix, where))
28 }
29
30 func newInvalidEscapeSequenceError(what string) *SyntacticError {
31 return E(jsonwire.NewInvalidEscapeSequenceError(what))
32 }
33
34 func (e *SyntacticError) withPos(prefix string, pointer Pointer) *SyntacticError {
35 e.ByteOffset = int64(len(prefix))
36 e.JSONPointer = pointer
37 return e
38 }
39
40 func equalError(x, y error) bool {
41 return reflect.DeepEqual(x, y)
42 }
43
44 var (
45 zeroToken Token
46 zeroValue Value
47 )
48
49 // tokOrVal is either a Token or a Value.
50 type tokOrVal interface{ Kind() Kind }
51
52 type coderTestdataEntry struct {
53 name jsontest.CaseName
54 in string
55 outCompacted string
56 outEscaped string // outCompacted if empty; escapes all runes in a string
57 outIndented string // outCompacted if empty; uses " " for indent prefix and "\t" for indent
58 outCanonicalized string // outCompacted if empty
59 tokens []Token
60 pointers []Pointer
61 }
62
63 var coderTestdata = []coderTestdataEntry{{
64 name: jsontest.Name("Null"),
65 in: ` null `,
66 outCompacted: `null`,
67 tokens: []Token{Null},
68 pointers: []Pointer{""},
69 }, {
70 name: jsontest.Name("False"),
71 in: ` false `,
72 outCompacted: `false`,
73 tokens: []Token{False},
74 }, {
75 name: jsontest.Name("True"),
76 in: ` true `,
77 outCompacted: `true`,
78 tokens: []Token{True},
79 }, {
80 name: jsontest.Name("EmptyString"),
81 in: ` "" `,
82 outCompacted: `""`,
83 tokens: []Token{String("")},
84 }, {
85 name: jsontest.Name("SimpleString"),
86 in: ` "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" `,
87 outCompacted: `"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"`,
88 outEscaped: `"\u0061\u0062\u0063\u0064\u0065\u0066\u0067\u0068\u0069\u006a\u006b\u006c\u006d\u006e\u006f\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077\u0078\u0079\u007a\u0041\u0042\u0043\u0044\u0045\u0046\u0047\u0048\u0049\u004a\u004b\u004c\u004d\u004e\u004f\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057\u0058\u0059\u005a"`,
89 tokens: []Token{String("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")},
90 }, {
91 name: jsontest.Name("ComplicatedString"),
92 in: " \"Hello, δΈ–η•Œ πŸŒŸβ˜…β˜†βœ©πŸŒ  " + "\u0080\u00f6\u20ac\ud799\ue000\ufb33\ufffd\U0001f602" + ` \ud800\udead \"\\\/\b\f\n\r\t \u0022\u005c\u002f\u0008\u000c\u000a\u000d\u0009" `,
93 outCompacted: "\"Hello, δΈ–η•Œ πŸŒŸβ˜…β˜†βœ©πŸŒ  " + "\u0080\u00f6\u20ac\ud799\ue000\ufb33\ufffd\U0001f602" + " 𐊭 \\\"\\\\/\\b\\f\\n\\r\\t \\\"\\\\/\\b\\f\\n\\r\\t\"",
94 outEscaped: `"\u0048\u0065\u006c\u006c\u006f\u002c\u0020\u4e16\u754c\u0020\ud83c\udf1f\u2605\u2606\u2729\ud83c\udf20\u0020\u0080\u00f6\u20ac\ud799\ue000\ufb33\ufffd\ud83d\ude02\u0020\ud800\udead\u0020\u0022\u005c\u002f\u0008\u000c\u000a\u000d\u0009\u0020\u0022\u005c\u002f\u0008\u000c\u000a\u000d\u0009"`,
95 outCanonicalized: `"Hello, δΈ–η•Œ πŸŒŸβ˜…β˜†βœ©πŸŒ  Β€ΓΆβ‚¬νž™ξ€€ο¬³οΏ½πŸ˜‚ 𐊭 \"\\/\b\f\n\r\t \"\\/\b\f\n\r\t"`,
96 tokens: []Token{rawToken("\"Hello, δΈ–η•Œ πŸŒŸβ˜…β˜†βœ©πŸŒ  " + "\u0080\u00f6\u20ac\ud799\ue000\ufb33\ufffd\U0001f602" + " 𐊭 \\\"\\\\/\\b\\f\\n\\r\\t \\\"\\\\/\\b\\f\\n\\r\\t\"")},
97 }, {
98 name: jsontest.Name("ZeroNumber"),
99 in: ` 0 `,
100 outCompacted: `0`,
101 tokens: []Token{Uint(0)},
102 }, {
103 name: jsontest.Name("SimpleNumber"),
104 in: ` 123456789 `,
105 outCompacted: `123456789`,
106 tokens: []Token{Uint(123456789)},
107 }, {
108 name: jsontest.Name("NegativeNumber"),
109 in: ` -123456789 `,
110 outCompacted: `-123456789`,
111 tokens: []Token{Int(-123456789)},
112 }, {
113 name: jsontest.Name("FractionalNumber"),
114 in: " 0.123456789 ",
115 outCompacted: `0.123456789`,
116 tokens: []Token{Float(0.123456789)},
117 }, {
118 name: jsontest.Name("ExponentNumber"),
119 in: " 0e12456789 ",
120 outCompacted: `0e12456789`,
121 outCanonicalized: `0`,
122 tokens: []Token{rawToken(`0e12456789`)},
123 }, {
124 name: jsontest.Name("ExponentNumberP"),
125 in: " 0e+12456789 ",
126 outCompacted: `0e+12456789`,
127 outCanonicalized: `0`,
128 tokens: []Token{rawToken(`0e+12456789`)},
129 }, {
130 name: jsontest.Name("ExponentNumberN"),
131 in: " 0e-12456789 ",
132 outCompacted: `0e-12456789`,
133 outCanonicalized: `0`,
134 tokens: []Token{rawToken(`0e-12456789`)},
135 }, {
136 name: jsontest.Name("ComplicatedNumber"),
137 in: ` -123456789.987654321E+0123456789 `,
138 outCompacted: `-123456789.987654321E+0123456789`,
139 outCanonicalized: `-1.7976931348623157e+308`,
140 tokens: []Token{rawToken(`-123456789.987654321E+0123456789`)},
141 }, {
142 name: jsontest.Name("Numbers"),
143 in: ` [
144 0, -0, 0.0, -0.0, 1.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001, 1e1000,
145 -5e-324, 1e+100, 1.7976931348623157e+308,
146 9007199254740990, 9007199254740991, 9007199254740992, 9007199254740993, 9007199254740994,
147 -9223372036854775808, 9223372036854775807, 0, 18446744073709551615
148 ] `,
149 outCompacted: "[0,-0,0.0,-0.0,1.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001,1e1000,-5e-324,1e+100,1.7976931348623157e+308,9007199254740990,9007199254740991,9007199254740992,9007199254740993,9007199254740994,-9223372036854775808,9223372036854775807,0,18446744073709551615]",
150 outIndented: `[
151 0,
152 -0,
153 0.0,
154 -0.0,
155 1.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001,
156 1e1000,
157 -5e-324,
158 1e+100,
159 1.7976931348623157e+308,
160 9007199254740990,
161 9007199254740991,
162 9007199254740992,
163 9007199254740993,
164 9007199254740994,
165 -9223372036854775808,
166 9223372036854775807,
167 0,
168 18446744073709551615
169 ]`,
170 outCanonicalized: `[0,0,0,0,1,1.7976931348623157e+308,-5e-324,1e+100,1.7976931348623157e+308,9007199254740990,9007199254740991,9007199254740992,9007199254740992,9007199254740994,-9223372036854776000,9223372036854776000,0,18446744073709552000]`,
171 tokens: []Token{
172 BeginArray,
173 Float(0), Float(math.Copysign(0, -1)), rawToken(`0.0`), rawToken(`-0.0`), rawToken(`1.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001`), rawToken(`1e1000`),
174 Float(-5e-324), Float(1e100), Float(1.7976931348623157e+308),
175 Float(9007199254740990), Float(9007199254740991), Float(9007199254740992), rawToken(`9007199254740993`), rawToken(`9007199254740994`),
176 Int(minInt64), Int(maxInt64), Uint(minUint64), Uint(maxUint64),
177 EndArray,
178 },
179 pointers: []Pointer{
180 "", "/0", "/1", "/2", "/3", "/4", "/5", "/6", "/7", "/8", "/9", "/10", "/11", "/12", "/13", "/14", "/15", "/16", "/17", "",
181 },
182 }, {
183 name: jsontest.Name("ObjectN0"),
184 in: ` { } `,
185 outCompacted: `{}`,
186 tokens: []Token{BeginObject, EndObject},
187 pointers: []Pointer{"", ""},
188 }, {
189 name: jsontest.Name("ObjectN1"),
190 in: ` { "0" : 0 } `,
191 outCompacted: `{"0":0}`,
192 outEscaped: `{"\u0030":0}`,
193 outIndented: `{
194 "0": 0
195 }`,
196 tokens: []Token{BeginObject, String("0"), Uint(0), EndObject},
197 pointers: []Pointer{"", "/0", "/0", ""},
198 }, {
199 name: jsontest.Name("ObjectN2"),
200 in: ` { "0" : 0 , "1" : 1 } `,
201 outCompacted: `{"0":0,"1":1}`,
202 outEscaped: `{"\u0030":0,"\u0031":1}`,
203 outIndented: `{
204 "0": 0,
205 "1": 1
206 }`,
207 tokens: []Token{BeginObject, String("0"), Uint(0), String("1"), Uint(1), EndObject},
208 pointers: []Pointer{"", "/0", "/0", "/1", "/1", ""},
209 }, {
210 name: jsontest.Name("ObjectNested"),
211 in: ` { "0" : { "1" : { "2" : { "3" : { "4" : { } } } } } } `,
212 outCompacted: `{"0":{"1":{"2":{"3":{"4":{}}}}}}`,
213 outEscaped: `{"\u0030":{"\u0031":{"\u0032":{"\u0033":{"\u0034":{}}}}}}`,
214 outIndented: `{
215 "0": {
216 "1": {
217 "2": {
218 "3": {
219 "4": {}
220 }
221 }
222 }
223 }
224 }`,
225 tokens: []Token{BeginObject, String("0"), BeginObject, String("1"), BeginObject, String("2"), BeginObject, String("3"), BeginObject, String("4"), BeginObject, EndObject, EndObject, EndObject, EndObject, EndObject, EndObject},
226 pointers: []Pointer{
227 "",
228 "/0", "/0",
229 "/0/1", "/0/1",
230 "/0/1/2", "/0/1/2",
231 "/0/1/2/3", "/0/1/2/3",
232 "/0/1/2/3/4", "/0/1/2/3/4",
233 "/0/1/2/3/4",
234 "/0/1/2/3",
235 "/0/1/2",
236 "/0/1",
237 "/0",
238 "",
239 },
240 }, {
241 name: jsontest.Name("ObjectSuperNested"),
242 in: `{"": {
243 "44444": {
244 "6666666": "ccccccc",
245 "77777777": "bb",
246 "555555": "aaaa"
247 },
248 "0": {
249 "3333": "bbb",
250 "11": "",
251 "222": "aaaaa"
252 }
253 }}`,
254 outCompacted: `{"":{"44444":{"6666666":"ccccccc","77777777":"bb","555555":"aaaa"},"0":{"3333":"bbb","11":"","222":"aaaaa"}}}`,
255 outEscaped: `{"":{"\u0034\u0034\u0034\u0034\u0034":{"\u0036\u0036\u0036\u0036\u0036\u0036\u0036":"\u0063\u0063\u0063\u0063\u0063\u0063\u0063","\u0037\u0037\u0037\u0037\u0037\u0037\u0037\u0037":"\u0062\u0062","\u0035\u0035\u0035\u0035\u0035\u0035":"\u0061\u0061\u0061\u0061"},"\u0030":{"\u0033\u0033\u0033\u0033":"\u0062\u0062\u0062","\u0031\u0031":"","\u0032\u0032\u0032":"\u0061\u0061\u0061\u0061\u0061"}}}`,
256 outIndented: `{
257 "": {
258 "44444": {
259 "6666666": "ccccccc",
260 "77777777": "bb",
261 "555555": "aaaa"
262 },
263 "0": {
264 "3333": "bbb",
265 "11": "",
266 "222": "aaaaa"
267 }
268 }
269 }`,
270 outCanonicalized: `{"":{"0":{"11":"","222":"aaaaa","3333":"bbb"},"44444":{"555555":"aaaa","6666666":"ccccccc","77777777":"bb"}}}`,
271 tokens: []Token{
272 BeginObject,
273 String(""),
274 BeginObject,
275 String("44444"),
276 BeginObject,
277 String("6666666"), String("ccccccc"),
278 String("77777777"), String("bb"),
279 String("555555"), String("aaaa"),
280 EndObject,
281 String("0"),
282 BeginObject,
283 String("3333"), String("bbb"),
284 String("11"), String(""),
285 String("222"), String("aaaaa"),
286 EndObject,
287 EndObject,
288 EndObject,
289 },
290 pointers: []Pointer{
291 "",
292 "/", "/",
293 "//44444", "//44444",
294 "//44444/6666666", "//44444/6666666",
295 "//44444/77777777", "//44444/77777777",
296 "//44444/555555", "//44444/555555",
297 "//44444",
298 "//0", "//0",
299 "//0/3333", "//0/3333",
300 "//0/11", "//0/11",
301 "//0/222", "//0/222",
302 "//0",
303 "/",
304 "",
305 },
306 }, {
307 name: jsontest.Name("ArrayN0"),
308 in: ` [ ] `,
309 outCompacted: `[]`,
310 tokens: []Token{BeginArray, EndArray},
311 pointers: []Pointer{"", ""},
312 }, {
313 name: jsontest.Name("ArrayN1"),
314 in: ` [ 0 ] `,
315 outCompacted: `[0]`,
316 outIndented: `[
317 0
318 ]`,
319 tokens: []Token{BeginArray, Uint(0), EndArray},
320 pointers: []Pointer{"", "/0", ""},
321 }, {
322 name: jsontest.Name("ArrayN2"),
323 in: ` [ 0 , 1 ] `,
324 outCompacted: `[0,1]`,
325 outIndented: `[
326 0,
327 1
328 ]`,
329 tokens: []Token{BeginArray, Uint(0), Uint(1), EndArray},
330 }, {
331 name: jsontest.Name("ArrayNested"),
332 in: ` [ [ [ [ [ ] ] ] ] ] `,
333 outCompacted: `[[[[[]]]]]`,
334 outIndented: `[
335 [
336 [
337 [
338 []
339 ]
340 ]
341 ]
342 ]`,
343 tokens: []Token{BeginArray, BeginArray, BeginArray, BeginArray, BeginArray, EndArray, EndArray, EndArray, EndArray, EndArray},
344 pointers: []Pointer{
345 "",
346 "/0",
347 "/0/0",
348 "/0/0/0",
349 "/0/0/0/0",
350 "/0/0/0/0",
351 "/0/0/0",
352 "/0/0",
353 "/0",
354 "",
355 },
356 }, {
357 name: jsontest.Name("Everything"),
358 in: ` {
359 "literals" : [ null , false , true ],
360 "string" : "Hello, δΈ–η•Œ" ,
361 "number" : 3.14159 ,
362 "arrayN0" : [ ] ,
363 "arrayN1" : [ 0 ] ,
364 "arrayN2" : [ 0 , 1 ] ,
365 "objectN0" : { } ,
366 "objectN1" : { "0" : 0 } ,
367 "objectN2" : { "0" : 0 , "1" : 1 }
368 } `,
369 outCompacted: `{"literals":[null,false,true],"string":"Hello, δΈ–η•Œ","number":3.14159,"arrayN0":[],"arrayN1":[0],"arrayN2":[0,1],"objectN0":{},"objectN1":{"0":0},"objectN2":{"0":0,"1":1}}`,
370 outEscaped: `{"\u006c\u0069\u0074\u0065\u0072\u0061\u006c\u0073":[null,false,true],"\u0073\u0074\u0072\u0069\u006e\u0067":"\u0048\u0065\u006c\u006c\u006f\u002c\u0020\u4e16\u754c","\u006e\u0075\u006d\u0062\u0065\u0072":3.14159,"\u0061\u0072\u0072\u0061\u0079\u004e\u0030":[],"\u0061\u0072\u0072\u0061\u0079\u004e\u0031":[0],"\u0061\u0072\u0072\u0061\u0079\u004e\u0032":[0,1],"\u006f\u0062\u006a\u0065\u0063\u0074\u004e\u0030":{},"\u006f\u0062\u006a\u0065\u0063\u0074\u004e\u0031":{"\u0030":0},"\u006f\u0062\u006a\u0065\u0063\u0074\u004e\u0032":{"\u0030":0,"\u0031":1}}`,
371 outIndented: `{
372 "literals": [
373 null,
374 false,
375 true
376 ],
377 "string": "Hello, δΈ–η•Œ",
378 "number": 3.14159,
379 "arrayN0": [],
380 "arrayN1": [
381 0
382 ],
383 "arrayN2": [
384 0,
385 1
386 ],
387 "objectN0": {},
388 "objectN1": {
389 "0": 0
390 },
391 "objectN2": {
392 "0": 0,
393 "1": 1
394 }
395 }`,
396 outCanonicalized: `{"arrayN0":[],"arrayN1":[0],"arrayN2":[0,1],"literals":[null,false,true],"number":3.14159,"objectN0":{},"objectN1":{"0":0},"objectN2":{"0":0,"1":1},"string":"Hello, δΈ–η•Œ"}`,
397 tokens: []Token{
398 BeginObject,
399 String("literals"), BeginArray, Null, False, True, EndArray,
400 String("string"), String("Hello, δΈ–η•Œ"),
401 String("number"), Float(3.14159),
402 String("arrayN0"), BeginArray, EndArray,
403 String("arrayN1"), BeginArray, Uint(0), EndArray,
404 String("arrayN2"), BeginArray, Uint(0), Uint(1), EndArray,
405 String("objectN0"), BeginObject, EndObject,
406 String("objectN1"), BeginObject, String("0"), Uint(0), EndObject,
407 String("objectN2"), BeginObject, String("0"), Uint(0), String("1"), Uint(1), EndObject,
408 EndObject,
409 },
410 pointers: []Pointer{
411 "",
412 "/literals", "/literals",
413 "/literals/0",
414 "/literals/1",
415 "/literals/2",
416 "/literals",
417 "/string", "/string",
418 "/number", "/number",
419 "/arrayN0", "/arrayN0", "/arrayN0",
420 "/arrayN1", "/arrayN1",
421 "/arrayN1/0",
422 "/arrayN1",
423 "/arrayN2", "/arrayN2",
424 "/arrayN2/0",
425 "/arrayN2/1",
426 "/arrayN2",
427 "/objectN0", "/objectN0", "/objectN0",
428 "/objectN1", "/objectN1",
429 "/objectN1/0", "/objectN1/0",
430 "/objectN1",
431 "/objectN2", "/objectN2",
432 "/objectN2/0", "/objectN2/0",
433 "/objectN2/1", "/objectN2/1",
434 "/objectN2",
435 "",
436 },
437 }}
438
439 // TestCoderInterleaved tests that we can interleave calls that operate on
440 // tokens and raw values. The only error condition is trying to operate on a
441 // raw value when the next token is an end of object or array.
442 func TestCoderInterleaved(t *testing.T) {
443 for _, td := range coderTestdata {
444 // In TokenFirst and ValueFirst, alternate between tokens and values.
445 // In TokenDelims, only use tokens for object and array delimiters.
446 for _, modeName := range []string{"TokenFirst", "ValueFirst", "TokenDelims"} {
447 t.Run(path.Join(td.name.Name, modeName), func(t *testing.T) {
448 testCoderInterleaved(t, td.name.Where, modeName, td)
449 })
450 }
451 }
452 }
453 func testCoderInterleaved(t *testing.T, where jsontest.CasePos, modeName string, td coderTestdataEntry) {
454 src := strings.NewReader(td.in)
455 dst := new(bytes.Buffer)
456 dec := NewDecoder(src)
457 enc := NewEncoder(dst)
458 tickTock := modeName == "TokenFirst"
459 for {
460 if modeName == "TokenDelims" {
461 switch dec.PeekKind() {
462 case '{', '}', '[', ']':
463 tickTock = true // as token
464 default:
465 tickTock = false // as value
466 }
467 }
468 if tickTock {
469 tok, err := dec.ReadToken()
470 if err != nil {
471 if err == io.EOF {
472 break
473 }
474 t.Fatalf("%s: Decoder.ReadToken error: %v", where, err)
475 }
476 if err := enc.WriteToken(tok); err != nil {
477 t.Fatalf("%s: Encoder.WriteToken error: %v", where, err)
478 }
479 } else {
480 val, err := dec.ReadValue()
481 if err != nil {
482 // It is a syntactic error to call ReadValue
483 // at the end of an object or array.
484 // Retry as a ReadToken call.
485 expectError := dec.PeekKind() == '}' || dec.PeekKind() == ']'
486 if expectError {
487 if !errors.As(err, new(*SyntacticError)) {
488 t.Fatalf("%s: Decoder.ReadToken error is %T, want %T", where, err, new(SyntacticError))
489 }
490 tickTock = !tickTock
491 continue
492 }
493
494 if err == io.EOF {
495 break
496 }
497 t.Fatalf("%s: Decoder.ReadValue error: %v", where, err)
498 }
499 if err := enc.WriteValue(val); err != nil {
500 t.Fatalf("%s: Encoder.WriteValue error: %v", where, err)
501 }
502 }
503 tickTock = !tickTock
504 }
505
506 got := dst.String()
507 want := td.outCompacted + "\n"
508 if got != want {
509 t.Fatalf("%s: output mismatch:\ngot %q\nwant %q", where, got, want)
510 }
511 }
512
513 func TestCoderStackPointer(t *testing.T) {
514 tests := []struct {
515 token Token
516 want Pointer
517 }{
518 {Null, ""},
519
520 {BeginArray, ""},
521 {EndArray, ""},
522
523 {BeginArray, ""},
524 {Bool(true), "/0"},
525 {EndArray, ""},
526
527 {BeginArray, ""},
528 {String("hello"), "/0"},
529 {String("goodbye"), "/1"},
530 {EndArray, ""},
531
532 {BeginObject, ""},
533 {EndObject, ""},
534
535 {BeginObject, ""},
536 {String("hello"), "/hello"},
537 {String("goodbye"), "/hello"},
538 {EndObject, ""},
539
540 {BeginObject, ""},
541 {String(""), "/"},
542 {Null, "/"},
543 {String("0"), "/0"},
544 {Null, "/0"},
545 {String("~"), "/~0"},
546 {Null, "/~0"},
547 {String("/"), "/~1"},
548 {Null, "/~1"},
549 {String("a//b~/c/~d~~e"), "/a~1~1b~0~1c~1~0d~0~0e"},
550 {Null, "/a~1~1b~0~1c~1~0d~0~0e"},
551 {String(" \r\n\t"), "/ \r\n\t"},
552 {Null, "/ \r\n\t"},
553 {EndObject, ""},
554
555 {BeginArray, ""},
556 {BeginObject, "/0"},
557 {String(""), "/0/"},
558 {BeginArray, "/0/"},
559 {BeginObject, "/0//0"},
560 {String("#"), "/0//0/#"},
561 {Null, "/0//0/#"},
562 {EndObject, "/0//0"},
563 {EndArray, "/0/"},
564 {EndObject, "/0"},
565 {EndArray, ""},
566 }
567
568 for _, allowDupes := range []bool{false, true} {
569 var name string
570 switch allowDupes {
571 case false:
572 name = "RejectDuplicateNames"
573 case true:
574 name = "AllowDuplicateNames"
575 }
576
577 t.Run(name, func(t *testing.T) {
578 bb := new(bytes.Buffer)
579
580 enc := NewEncoder(bb, AllowDuplicateNames(allowDupes))
581 for i, tt := range tests {
582 if err := enc.WriteToken(tt.token); err != nil {
583 t.Fatalf("%d: Encoder.WriteToken error: %v", i, err)
584 }
585 if got := enc.StackPointer(); got != tests[i].want {
586 t.Fatalf("%d: Encoder.StackPointer = %v, want %v", i, got, tests[i].want)
587 }
588 }
589
590 dec := NewDecoder(bb, AllowDuplicateNames(allowDupes))
591 for i := range tests {
592 if _, err := dec.ReadToken(); err != nil {
593 t.Fatalf("%d: Decoder.ReadToken error: %v", i, err)
594 }
595 if got := dec.StackPointer(); got != tests[i].want {
596 t.Fatalf("%d: Decoder.StackPointer = %v, want %v", i, got, tests[i].want)
597 }
598 }
599 })
600 }
601 }
602
603 func TestCoderMaxDepth(t *testing.T) {
604 trimArray := func(b []byte) []byte { return b[len(`[`) : len(b)-len(`]`)] }
605 maxArrays := []byte(strings.Repeat(`[`, maxNestingDepth+1) + strings.Repeat(`]`, maxNestingDepth+1))
606 trimObject := func(b []byte) []byte { return b[len(`{"":`) : len(b)-len(`}`)] }
607 maxObjects := []byte(strings.Repeat(`{"":`, maxNestingDepth+1) + `""` + strings.Repeat(`}`, maxNestingDepth+1))
608
609 t.Run("Decoder", func(t *testing.T) {
610 var dec Decoder
611 checkReadToken := func(t *testing.T, wantKind Kind, wantErr error) {
612 t.Helper()
613 if tok, err := dec.ReadToken(); tok.Kind() != wantKind || !equalError(err, wantErr) {
614 t.Fatalf("Decoder.ReadToken = (%q, %v), want (%q, %v)", byte(tok.Kind()), err, byte(wantKind), wantErr)
615 }
616 }
617 checkReadValue := func(t *testing.T, wantLen int, wantErr error) {
618 t.Helper()
619 if val, err := dec.ReadValue(); len(val) != wantLen || !equalError(err, wantErr) {
620 t.Fatalf("Decoder.ReadValue = (%d, %v), want (%d, %v)", len(val), err, wantLen, wantErr)
621 }
622 }
623
624 t.Run("ArraysValid/SingleValue", func(t *testing.T) {
625 dec.s.reset(trimArray(maxArrays), nil)
626 checkReadValue(t, maxNestingDepth*len(`[]`), nil)
627 })
628 t.Run("ArraysValid/TokenThenValue", func(t *testing.T) {
629 dec.s.reset(trimArray(maxArrays), nil)
630 checkReadToken(t, '[', nil)
631 checkReadValue(t, (maxNestingDepth-1)*len(`[]`), nil)
632 checkReadToken(t, ']', nil)
633 })
634 t.Run("ArraysValid/AllTokens", func(t *testing.T) {
635 dec.s.reset(trimArray(maxArrays), nil)
636 for range maxNestingDepth {
637 checkReadToken(t, '[', nil)
638 }
639 for range maxNestingDepth {
640 checkReadToken(t, ']', nil)
641 }
642 })
643
644 wantErr := &SyntacticError{
645 ByteOffset: maxNestingDepth,
646 JSONPointer: Pointer(strings.Repeat("/0", maxNestingDepth)),
647 Err: errMaxDepth,
648 }
649 t.Run("ArraysInvalid/SingleValue", func(t *testing.T) {
650 dec.s.reset(maxArrays, nil)
651 checkReadValue(t, 0, wantErr)
652 })
653 t.Run("ArraysInvalid/TokenThenValue", func(t *testing.T) {
654 dec.s.reset(maxArrays, nil)
655 checkReadToken(t, '[', nil)
656 checkReadValue(t, 0, wantErr)
657 })
658 t.Run("ArraysInvalid/AllTokens", func(t *testing.T) {
659 dec.s.reset(maxArrays, nil)
660 for range maxNestingDepth {
661 checkReadToken(t, '[', nil)
662 }
663 checkReadValue(t, 0, wantErr)
664 })
665
666 t.Run("ObjectsValid/SingleValue", func(t *testing.T) {
667 dec.s.reset(trimObject(maxObjects), nil)
668 checkReadValue(t, maxNestingDepth*len(`{"":}`)+len(`""`), nil)
669 })
670 t.Run("ObjectsValid/TokenThenValue", func(t *testing.T) {
671 dec.s.reset(trimObject(maxObjects), nil)
672 checkReadToken(t, '{', nil)
673 checkReadToken(t, '"', nil)
674 checkReadValue(t, (maxNestingDepth-1)*len(`{"":}`)+len(`""`), nil)
675 checkReadToken(t, '}', nil)
676 })
677 t.Run("ObjectsValid/AllTokens", func(t *testing.T) {
678 dec.s.reset(trimObject(maxObjects), nil)
679 for range maxNestingDepth {
680 checkReadToken(t, '{', nil)
681 checkReadToken(t, '"', nil)
682 }
683 checkReadToken(t, '"', nil)
684 for range maxNestingDepth {
685 checkReadToken(t, '}', nil)
686 }
687 })
688
689 wantErr = &SyntacticError{
690 ByteOffset: maxNestingDepth * int64(len(`{"":`)),
691 JSONPointer: Pointer(strings.Repeat("/", maxNestingDepth)),
692 Err: errMaxDepth,
693 }
694 t.Run("ObjectsInvalid/SingleValue", func(t *testing.T) {
695 dec.s.reset(maxObjects, nil)
696 checkReadValue(t, 0, wantErr)
697 })
698 t.Run("ObjectsInvalid/TokenThenValue", func(t *testing.T) {
699 dec.s.reset(maxObjects, nil)
700 checkReadToken(t, '{', nil)
701 checkReadToken(t, '"', nil)
702 checkReadValue(t, 0, wantErr)
703 })
704 t.Run("ObjectsInvalid/AllTokens", func(t *testing.T) {
705 dec.s.reset(maxObjects, nil)
706 for range maxNestingDepth {
707 checkReadToken(t, '{', nil)
708 checkReadToken(t, '"', nil)
709 }
710 checkReadToken(t, 0, wantErr)
711 })
712 })
713
714 t.Run("Encoder", func(t *testing.T) {
715 var enc Encoder
716 checkWriteToken := func(t *testing.T, tok Token, wantErr error) {
717 t.Helper()
718 if err := enc.WriteToken(tok); !equalError(err, wantErr) {
719 t.Fatalf("Encoder.WriteToken = %v, want %v", err, wantErr)
720 }
721 }
722 checkWriteValue := func(t *testing.T, val Value, wantErr error) {
723 t.Helper()
724 if err := enc.WriteValue(val); !equalError(err, wantErr) {
725 t.Fatalf("Encoder.WriteValue = %v, want %v", err, wantErr)
726 }
727 }
728
729 wantErr := &SyntacticError{
730 ByteOffset: maxNestingDepth,
731 JSONPointer: Pointer(strings.Repeat("/0", maxNestingDepth)),
732 Err: errMaxDepth,
733 }
734 t.Run("Arrays/SingleValue", func(t *testing.T) {
735 enc.s.reset(enc.s.Buf[:0], nil)
736 checkWriteValue(t, maxArrays, wantErr)
737 checkWriteValue(t, trimArray(maxArrays), nil)
738 })
739 t.Run("Arrays/TokenThenValue", func(t *testing.T) {
740 enc.s.reset(enc.s.Buf[:0], nil)
741 checkWriteToken(t, BeginArray, nil)
742 checkWriteValue(t, trimArray(maxArrays), wantErr)
743 checkWriteValue(t, trimArray(trimArray(maxArrays)), nil)
744 checkWriteToken(t, EndArray, nil)
745 })
746 t.Run("Arrays/AllTokens", func(t *testing.T) {
747 enc.s.reset(enc.s.Buf[:0], nil)
748 for range maxNestingDepth {
749 checkWriteToken(t, BeginArray, nil)
750 }
751 checkWriteToken(t, BeginArray, wantErr)
752 for range maxNestingDepth {
753 checkWriteToken(t, EndArray, nil)
754 }
755 })
756
757 wantErr = &SyntacticError{
758 ByteOffset: maxNestingDepth * int64(len(`{"":`)),
759 JSONPointer: Pointer(strings.Repeat("/", maxNestingDepth)),
760 Err: errMaxDepth,
761 }
762 t.Run("Objects/SingleValue", func(t *testing.T) {
763 enc.s.reset(enc.s.Buf[:0], nil)
764 checkWriteValue(t, maxObjects, wantErr)
765 checkWriteValue(t, trimObject(maxObjects), nil)
766 })
767 t.Run("Objects/TokenThenValue", func(t *testing.T) {
768 enc.s.reset(enc.s.Buf[:0], nil)
769 checkWriteToken(t, BeginObject, nil)
770 checkWriteToken(t, String(""), nil)
771 checkWriteValue(t, trimObject(maxObjects), wantErr)
772 checkWriteValue(t, trimObject(trimObject(maxObjects)), nil)
773 checkWriteToken(t, EndObject, nil)
774 })
775 t.Run("Objects/AllTokens", func(t *testing.T) {
776 enc.s.reset(enc.s.Buf[:0], nil)
777 for range maxNestingDepth - 1 {
778 checkWriteToken(t, BeginObject, nil)
779 checkWriteToken(t, String(""), nil)
780 }
781 checkWriteToken(t, BeginObject, nil)
782 checkWriteToken(t, String(""), nil)
783 checkWriteToken(t, BeginObject, wantErr)
784 checkWriteToken(t, String(""), nil)
785 for range maxNestingDepth {
786 checkWriteToken(t, EndObject, nil)
787 }
788 })
789 })
790 }
791
792 // FaultyBuffer implements io.Reader and io.Writer.
793 // It may process fewer bytes than the provided buffer
794 // and may randomly return an error.
795 type FaultyBuffer struct {
796 B []byte
797
798 // MaxBytes is the maximum number of bytes read/written.
799 // A random number of bytes within [0, MaxBytes] are processed.
800 // A non-positive value is treated as infinity.
801 MaxBytes int
802
803 // MayError specifies whether to randomly provide this error.
804 // Even if an error is returned, no bytes are dropped.
805 MayError error
806
807 // Rand to use for pseudo-random behavior.
808 // If nil, it will be initialized with rand.NewSource(0).
809 Rand rand.Source
810 }
811
812 func (p *FaultyBuffer) Read(b []byte) (int, error) {
813 b = b[:copy(b[:p.mayTruncate(len(b))], p.B)]
814 p.B = p.B[len(b):]
815 if len(p.B) == 0 && (len(b) == 0 || p.randN(2) == 0) {
816 return len(b), io.EOF
817 }
818 return len(b), p.mayError()
819 }
820
821 func (p *FaultyBuffer) Write(b []byte) (int, error) {
822 b2 := b[:p.mayTruncate(len(b))]
823 p.B = append(p.B, b2...)
824 if len(b2) < len(b) {
825 return len(b2), io.ErrShortWrite
826 }
827 return len(b2), p.mayError()
828 }
829
830 // mayTruncate may return a value between [0, n].
831 func (p *FaultyBuffer) mayTruncate(n int) int {
832 if p.MaxBytes > 0 {
833 if n > p.MaxBytes {
834 n = p.MaxBytes
835 }
836 return p.randN(n + 1)
837 }
838 return n
839 }
840
841 // mayError may return a non-nil error.
842 func (p *FaultyBuffer) mayError() error {
843 if p.MayError != nil && p.randN(2) == 0 {
844 return p.MayError
845 }
846 return nil
847 }
848
849 func (p *FaultyBuffer) randN(n int) int {
850 if p.Rand == nil {
851 p.Rand = rand.NewSource(0)
852 }
853 return int(p.Rand.Int63() % int64(n))
854 }