Debian Codegraph @

encode_test.go

raw symbols SCIP
1 // Copyright 2016 Richard Gibson. All rights reserved.
2 // Copyright 2011 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package canonicaljson
7
8 import (
9 "bytes"
10 "encoding/json"
11 "fmt"
12 "math"
13 "reflect"
14 "strconv"
15 "testing"
16 "unicode"
17 )
18
19 type Optionals struct {
20 Sr string `json:"sr"`
21 So string `json:"so,omitempty"`
22 Sw string `json:"-"`
23
24 Ir int `json:"omitempty"` // actually named omitempty, not an option
25 Io int `json:"io,omitempty"`
26
27 Slr []string `json:"slr,random"`
28 Slo []string `json:"slo,omitempty"`
29
30 Mr map[string]interface{} `json:"mr"`
31 Mo map[string]interface{} `json:",omitempty"`
32
33 Fr float64 `json:"fr"`
34 Fo float64 `json:"fo,omitempty"`
35
36 Br bool `json:"br"`
37 Bo bool `json:"bo,omitempty"`
38
39 Ur uint `json:"ur"`
40 Uo uint `json:"uo,omitempty"`
41
42 Str struct{} `json:"str"`
43 Sto struct{} `json:"sto,omitempty"`
44 }
45
46 var optionalsExpected = `{
47 "br": false,
48 "fr": 0,
49 "mr": {},
50 "omitempty": 0,
51 "slr": null,
52 "sr": "",
53 "sto": {},
54 "str": {},
55 "ur": 0
56 }`
57
58 func TestOmitEmpty(t *testing.T) {
59 var o Optionals
60 o.Sw = "something"
61 o.Mr = map[string]interface{}{}
62 o.Mo = map[string]interface{}{}
63
64 got, err := MarshalIndent(&o, "", " ")
65 if err != nil {
66 t.Fatal(err)
67 }
68 if got := string(got); got != optionalsExpected {
69 t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected)
70 }
71 }
72
73 type StringTag struct {
74 BoolStr bool `json:",string"`
75 IntStr int64 `json:",string"`
76 StrStr string `json:",string"`
77 }
78
79 var stringTagExpected = `{
80 "BoolStr": "true",
81 "IntStr": "42",
82 "StrStr": "\"xzbit\""
83 }`
84
85 func TestStringTag(t *testing.T) {
86 var s StringTag
87 s.BoolStr = true
88 s.IntStr = 42
89 s.StrStr = "xzbit"
90 got, err := MarshalIndent(&s, "", " ")
91 if err != nil {
92 t.Fatal(err)
93 }
94 if got := string(got); got != stringTagExpected {
95 t.Fatalf(" got: %s\nwant: %s\n", got, stringTagExpected)
96 }
97
98 // Verify that it round-trips with the standard package.
99 var s2 StringTag
100 err = json.NewDecoder(bytes.NewReader(got)).Decode(&s2)
101 if err != nil {
102 t.Fatalf("Decode: %v", err)
103 }
104 if !reflect.DeepEqual(s, s2) {
105 t.Fatalf("decode didn't match.\nsource: %#v\nEncoded as:\n%s\ndecode: %#v", s, string(got), s2)
106 }
107 }
108
109 // byte slices are special even if they're renamed types.
110 type renamedByte byte
111 type renamedByteSlice []byte
112 type renamedRenamedByteSlice []renamedByte
113
114 func TestEncodeRenamedByteSlice(t *testing.T) {
115 s := renamedByteSlice("abc")
116 result, err := Marshal(s)
117 if err != nil {
118 t.Fatal(err)
119 }
120 expect := `"YWJj"`
121 if string(result) != expect {
122 t.Errorf(" got %s want %s", result, expect)
123 }
124 r := renamedRenamedByteSlice("abc")
125 result, err = Marshal(r)
126 if err != nil {
127 t.Fatal(err)
128 }
129 if string(result) != expect {
130 t.Errorf(" got %s want %s", result, expect)
131 }
132 }
133
134 var unsupportedValues = []interface{}{
135 math.NaN(),
136 math.Inf(-1),
137 math.Inf(1),
138 // Ill-formed UTF-8
139 "\x80",
140 "\xcf",
141 "\xed",
142 "\xed\xa0",
143 "\xed\xa0\x7e",
144 "\xed\xa0\xc0",
145 "\xf8\x82\x83\x84",
146 "\xed\xa0\x80\xed\xbf\xbf",
147 "\xed\xa0\x80\xed",
148 "hello\xffworld",
149 "\xff",
150 "\xff\xff",
151 "a\xffb",
152 "\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e",
153 }
154
155 func TestUnsupportedValues(t *testing.T) {
156 for i, v := range unsupportedValues {
157 label := fmt.Sprintf("#%d [%#v]", i, v)
158 if _, err := Marshal(v); err != nil {
159 if _, ok := err.(*UnsupportedValueError); !ok {
160 t.Errorf("%s: got %T, want UnsupportedValueError", label, err)
161 }
162 } else {
163 t.Errorf("%s: expected error", label)
164 }
165 }
166 }
167
168 // Ref has Marshaler and Unmarshaler methods with pointer receiver.
169 type Ref int
170
171 func (*Ref) MarshalJSON() ([]byte, error) {
172 return []byte(`"ref"`), nil
173 }
174
175 func (r *Ref) UnmarshalJSON([]byte) error {
176 *r = 12
177 return nil
178 }
179
180 // Val has Marshaler methods with value receiver.
181 type Val int
182
183 func (Val) MarshalJSON() ([]byte, error) {
184 return []byte(`"val"`), nil
185 }
186
187 // RefText has Marshaler and Unmarshaler methods with pointer receiver.
188 type RefText int
189
190 func (*RefText) MarshalText() ([]byte, error) {
191 return []byte(`"ref"`), nil
192 }
193
194 func (r *RefText) UnmarshalText([]byte) error {
195 *r = 13
196 return nil
197 }
198
199 // ValText has Marshaler methods with value receiver.
200 type ValText int
201
202 func (ValText) MarshalText() ([]byte, error) {
203 return []byte(`"val"`), nil
204 }
205
206 func TestRefValMarshal(t *testing.T) {
207 var s = struct {
208 R0 Ref
209 R1 *Ref
210 R2 RefText
211 R3 *RefText
212 V0 Val
213 V1 *Val
214 V2 ValText
215 V3 *ValText
216 }{
217 R0: 12,
218 R1: new(Ref),
219 R2: 14,
220 R3: new(RefText),
221 V0: 13,
222 V1: new(Val),
223 V2: 15,
224 V3: new(ValText),
225 }
226 const want = `{"R0":"ref","R1":"ref","R2":"\"ref\"","R3":"\"ref\"","V0":"val","V1":"val","V2":"\"val\"","V3":"\"val\""}`
227 b, err := Marshal(&s)
228 if err != nil {
229 t.Fatalf("Marshal: %v", err)
230 }
231 if got := string(b); got != want {
232 t.Errorf("got %q, want %q", got, want)
233 }
234 }
235
236 // C implements Marshaler and returns unescaped JSON.
237 type C int
238
239 func (C) MarshalJSON() ([]byte, error) {
240 return []byte(`"<&>"`), nil
241 }
242
243 // CText implements Marshaler and returns unescaped text.
244 type CText int
245
246 func (CText) MarshalText() ([]byte, error) {
247 return []byte(`"<&>"`), nil
248 }
249
250 func TestMarshalerEscaping(t *testing.T) {
251 var c C
252 want := `"<&>"`
253 b, err := Marshal(c)
254 if err != nil {
255 t.Fatalf("Marshal(c): %v", err)
256 }
257 if got := string(b); got != want {
258 t.Errorf("Marshal(c) = %#q, want %#q", got, want)
259 }
260
261 var ct CText
262 want = `"\"<&>\""`
263 b, err = Marshal(ct)
264 if err != nil {
265 t.Fatalf("Marshal(ct): %v", err)
266 }
267 if got := string(b); got != want {
268 t.Errorf("Marshal(ct) = %#q, want %#q", got, want)
269 }
270 }
271
272 type IntType int
273
274 type MyStruct struct {
275 IntType
276 }
277
278 func TestAnonymousNonstruct(t *testing.T) {
279 var i IntType = 11
280 a := MyStruct{i}
281 const want = `{"IntType":11}`
282
283 b, err := Marshal(a)
284 if err != nil {
285 t.Fatalf("Marshal: %v", err)
286 }
287 if got := string(b); got != want {
288 t.Errorf("got %q, want %q", got, want)
289 }
290 }
291
292 type BugA struct {
293 S string
294 }
295
296 type BugB struct {
297 BugA
298 S string
299 }
300
301 type BugC struct {
302 S string
303 }
304
305 // Legal Go: We never use the repeated embedded field (S).
306 type BugX struct {
307 A int
308 BugA
309 BugB
310 }
311
312 // Issue 5245.
313 func TestEmbeddedBug(t *testing.T) {
314 v := BugB{
315 BugA{"A"},
316 "B",
317 }
318 b, err := Marshal(v)
319 if err != nil {
320 t.Fatal("Marshal:", err)
321 }
322 want := `{"S":"B"}`
323 got := string(b)
324 if got != want {
325 t.Fatalf("Marshal: got %s want %s", got, want)
326 }
327 // Now check that the duplicate field, S, does not appear.
328 x := BugX{
329 A: 23,
330 }
331 b, err = Marshal(x)
332 if err != nil {
333 t.Fatal("Marshal:", err)
334 }
335 want = `{"A":23}`
336 got = string(b)
337 if got != want {
338 t.Fatalf("Marshal: got %s want %s", got, want)
339 }
340 }
341
342 type BugD struct { // Same as BugA after tagging.
343 XXX string `json:"S"`
344 }
345
346 // BugD's tagged S field should dominate BugA's.
347 type BugY struct {
348 BugA
349 BugD
350 }
351
352 // Test that a field with a tag dominates untagged fields.
353 func TestTaggedFieldDominates(t *testing.T) {
354 v := BugY{
355 BugA{"BugA"},
356 BugD{"BugD"},
357 }
358 b, err := Marshal(v)
359 if err != nil {
360 t.Fatal("Marshal:", err)
361 }
362 want := `{"S":"BugD"}`
363 got := string(b)
364 if got != want {
365 t.Fatalf("Marshal: got %s want %s", got, want)
366 }
367 }
368
369 // There are no tags here, so S should not appear.
370 type BugZ struct {
371 BugA
372 BugC
373 BugY // Contains a tagged S field through BugD; should not dominate.
374 }
375
376 func TestDuplicatedFieldDisappears(t *testing.T) {
377 v := BugZ{
378 BugA{"BugA"},
379 BugC{"BugC"},
380 BugY{
381 BugA{"nested BugA"},
382 BugD{"nested BugD"},
383 },
384 }
385 b, err := Marshal(v)
386 if err != nil {
387 t.Fatal("Marshal:", err)
388 }
389 want := `{}`
390 got := string(b)
391 if got != want {
392 t.Fatalf("Marshal: got %s want %s", got, want)
393 }
394 }
395
396 func TestStringBytes(t *testing.T) {
397 // Test that encodeState.stringBytes and encodeState.string use the same encoding.
398 es := &encodeState{}
399 var r []rune
400 for i := '\u0000'; i <= unicode.MaxRune; i++ {
401 r = append(r, i)
402 }
403 // Include some valid non-UTF-8 sequences.
404 s := string(r) + "\xed\xbf\xbf\xed\xa0\x80"
405 es.string(s)
406
407 esBytes := &encodeState{}
408 esBytes.stringBytes([]byte(s))
409
410 enc := es.Buffer.String()
411 encBytes := esBytes.Buffer.String()
412 if enc != encBytes {
413 i := 0
414 for i < len(enc) && i < len(encBytes) && enc[i] == encBytes[i] {
415 i++
416 }
417 enc = enc[i:]
418 encBytes = encBytes[i:]
419 i = 0
420 for i < len(enc) && i < len(encBytes) && enc[len(enc)-i-1] == encBytes[len(encBytes)-i-1] {
421 i++
422 }
423 enc = enc[:len(enc)-i]
424 encBytes = encBytes[:len(encBytes)-i]
425
426 if len(enc) > 20 {
427 enc = enc[:20] + "..."
428 }
429 if len(encBytes) > 20 {
430 encBytes = encBytes[:20] + "..."
431 }
432
433 t.Errorf("encodings differ at %#q vs %#q", enc, encBytes)
434 }
435 }
436
437 func TestIssue6458(t *testing.T) {
438 type Foo struct {
439 M RawMessage
440 }
441 x := Foo{RawMessage(`"foo"`)}
442
443 b, err := Marshal(&x)
444 if err != nil {
445 t.Fatal(err)
446 }
447 if want := `{"M":"foo"}`; string(b) != want {
448 t.Errorf("Marshal(&x) = %#q; want %#q", b, want)
449 }
450
451 b, err = Marshal(x)
452 if err != nil {
453 t.Fatal(err)
454 }
455
456 if want := `{"M":"ImZvbyI="}`; string(b) != want {
457 t.Errorf("Marshal(x) = %#q; want %#q", b, want)
458 }
459 }
460
461 func TestIssue10281(t *testing.T) {
462 type Foo struct {
463 N json.Number
464 }
465 x := Foo{json.Number(`invalid`)}
466
467 b, err := Marshal(&x)
468 if err == nil {
469 t.Errorf("Marshal(&x) = %#q; want error", b)
470 }
471 }
472
473 // golang.org/issue/8582
474 func TestEncodePointerString(t *testing.T) {
475 type stringPointer struct {
476 N *int64 `json:"n,string"`
477 }
478 var n int64 = 42
479 b, err := Marshal(stringPointer{N: &n})
480 if err != nil {
481 t.Fatalf("Marshal: %v", err)
482 }
483 if got, want := string(b), `{"n":"42"}`; got != want {
484 t.Errorf("Marshal = %s, want %s", got, want)
485 }
486 var back stringPointer
487 err = json.Unmarshal(b, &back)
488 if err != nil {
489 t.Fatalf("Unmarshal: %v", err)
490 }
491 if back.N == nil {
492 t.Fatalf("Unmarshalled nil N field")
493 }
494 if *back.N != 42 {
495 t.Fatalf("*N = %d; want 42", *back.N)
496 }
497 }
498
499 var encodeStringTests = []struct {
500 in string
501 out string
502 }{
503 {"", `""`},
504 {"\x00", `"\u0000"`},
505 {"\x01", `"\u0001"`},
506 {"\x02", `"\u0002"`},
507 {"\x03", `"\u0003"`},
508 {"\x04", `"\u0004"`},
509 {"\x05", `"\u0005"`},
510 {"\x06", `"\u0006"`},
511 {"\x07", `"\u0007"`},
512 {"\x08", `"\b"`},
513 {"\x09", `"\t"`},
514 {"\x0a", `"\n"`},
515 {"\x0b", `"\u000B"`},
516 {"\x0c", `"\f"`},
517 {"\x0d", `"\r"`},
518 {"\x0e", `"\u000E"`},
519 {"\x0f", `"\u000F"`},
520 {"\x10", `"\u0010"`},
521 {"\x11", `"\u0011"`},
522 {"\x12", `"\u0012"`},
523 {"\x13", `"\u0013"`},
524 {"\x14", `"\u0014"`},
525 {"\x15", `"\u0015"`},
526 {"\x16", `"\u0016"`},
527 {"\x17", `"\u0017"`},
528 {"\x18", `"\u0018"`},
529 {"\x19", `"\u0019"`},
530 {"\x1a", `"\u001A"`},
531 {"\x1b", `"\u001B"`},
532 {"\x1c", `"\u001C"`},
533 {"\x1d", `"\u001D"`},
534 {"\x1e", `"\u001E"`},
535 {"\x1f", `"\u001F"`},
536 {"\x7f", "\"\x7f\""},
537 {"\xe6\x97\xa5\xe6\x9c\xac", `"日本"`},
538 {"\xed\xa0\x80", `"\uD800"`},
539 {"\xed\xa0\x80a", `"\uD800a"`},
540 {"\xed\xbf\xbf", `"\uDFFF"`},
541 {"\xed\xbf\xbfa", `"\uDFFFa"`},
542 {"\xed\xbf\xbf\xed\xa0\x80", `"\uDFFF\uD800"`},
543 {"\xed\xbf\xbf\xed\xa0\x80a", `"\uDFFF\uD800a"`},
544 }
545
546 func TestEncodeString(t *testing.T) {
547 for _, tt := range encodeStringTests {
548 b, err := Marshal(tt.in)
549 if err != nil {
550 t.Errorf("Marshal(%q): %v", tt.in, err)
551 continue
552 }
553 out := string(b)
554 if out != tt.out {
555 t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out)
556 }
557 }
558 }
559
560 var named = map[string]interface{}{
561 "\x08": nil,
562 "\x09": nil,
563 "\x0a": nil,
564 "\x0c": nil,
565 "\x0d": nil,
566 "\x00": nil,
567 "\x01": nil,
568 "\x02": nil,
569 "\x03": nil,
570 "\x04": nil,
571 "\x05": nil,
572 "\x06": nil,
573 "\x07": nil,
574 "\x0b": nil,
575 "\x0e": nil,
576 "\x0f": nil,
577 "\x10": nil,
578 "\x11": nil,
579 "\x12": nil,
580 "\x13": nil,
581 "\x14": nil,
582 "\x15": nil,
583 "\x16": nil,
584 "\x17": nil,
585 "\x18": nil,
586 "\x19": nil,
587 "\x1a": nil,
588 "\x1b": nil,
589 "\x1c": nil,
590 "\x1d": nil,
591 "\x1e": nil,
592 "\x1f": nil,
593 "\x7f": nil,
594 }
595
596 var namedExpected = `{
597 "\u0000": null,
598 "\u0001": null,
599 "\u0002": null,
600 "\u0003": null,
601 "\u0004": null,
602 "\u0005": null,
603 "\u0006": null,
604 "\u0007": null,
605 "\b": null,
606 "\t": null,
607 "\n": null,
608 "\u000B": null,
609 "\f": null,
610 "\r": null,
611 "\u000E": null,
612 "\u000F": null,
613 "\u0010": null,
614 "\u0011": null,
615 "\u0012": null,
616 "\u0013": null,
617 "\u0014": null,
618 "\u0015": null,
619 "\u0016": null,
620 "\u0017": null,
621 "\u0018": null,
622 "\u0019": null,
623 "\u001A": null,
624 "\u001B": null,
625 "\u001C": null,
626 "\u001D": null,
627 "\u001E": null,
628 "\u001F": null,
629 "` + "\x7f" + `": null
630 }`
631
632 func TestEncodeKey(t *testing.T) {
633 result, err := MarshalIndent(named, "", " ")
634 if err != nil {
635 t.Fatal(err)
636 }
637 if result := string(result); result != namedExpected {
638 t.Errorf(" got: %s\nwant: %s\n", result, namedExpected)
639 }
640 }
641
642 var floats = map[string][]string{
643 "2.5E-3": []string{
644 "0.025e-1", "0.0250e-1", "0.02500e-1",
645 "0.25e-2", "0.250e-2", "0.2500e-2",
646 },
647 "2.5E-2": []string{
648 "0.025e0", "0.0250e0", "0.02500e0",
649 "0.025", "0.0250", "0.02500",
650 "0.25e-1", "0.250e-1", "0.2500e-1",
651 "2.5e-2", "2.50e-2", "2.500e-2",
652 },
653 "2.5E-1": []string{
654 "0.025e1", "0.0250e1", "0.02500e1",
655 "0.25e0", "0.250e0", "0.2500e0",
656 "0.25", "0.250", "0.2500",
657 "2.5e-1", "2.50e-1", "2.500e-1",
658 "25e-2", "25.0e-2", "25.00e-2",
659 },
660 "2.5E0": []string{
661 "0.025e2", "0.0250e2", "0.02500e2",
662 "0.25e1", "0.250e1", "0.2500e1",
663 "2.5e0", "2.50e0", "2.500e0",
664 "2.5", "2.50", "2.500",
665 "25e-1", "25.0e-1", "25.00e-1",
666 "250e-2", "250.0e-2", "250.00e-2",
667 },
668 "25": []string{
669 "0.25e2", "0.250e2", "0.2500e2",
670 "2.5e1", "2.50e1", "2.500e1",
671 "25e0", "25.0e0", "25.00e0",
672 "25", "25.0", "25.00",
673 "250e-1", "250.0e-1", "250.00e-1",
674 },
675 "250": []string{
676 "2.5e2", "2.50e2", "2.500e2",
677 "25e1", "25.0e1", "25.00e1",
678 "250e0", "250.0e0", "250.00e0",
679 "250", "250.0", "250.00",
680 },
681 "2500": []string{
682 "25e2", "25.0e2", "25.00e2",
683 "250e1", "250.0e1", "250.00e1",
684 },
685 }
686
687 func TestFloat(t *testing.T) {
688 for expected, inputs := range floats {
689 for _, input := range inputs {
690 inputFloat, _ := strconv.ParseFloat(input, 64)
691 result, err := Marshal(inputFloat)
692 if err != nil {
693 t.Fatal(err)
694 }
695 if string(result) != expected {
696 t.Errorf(" float(%s)\n got: %s\n want: %s\n", input, result, expected)
697 }
698
699 inputNumber := Number(input)
700 result, err = Marshal(inputNumber)
701 if err != nil {
702 t.Fatal(err)
703 }
704 if string(result) != expected {
705 t.Errorf(" Number(%s)\n got: %s\n want: %s\n", input, result, expected)
706 }
707
708 inputJsonNumber := json.Number(input)
709 result, err = Marshal(inputJsonNumber)
710 if err != nil {
711 t.Fatal(err)
712 }
713 if string(result) != expected {
714 t.Errorf(" json.Number(%s)\n got: %s\n want: %s\n", input, result, expected)
715 }
716 }
717 }
718 }