Imported Upstream version 4.8.1
[platform/upstream/gcc48.git] / libgo / go / encoding / json / decode_test.go
1 // Copyright 2010 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 json
6
7 import (
8         "bytes"
9         "fmt"
10         "image"
11         "reflect"
12         "strings"
13         "testing"
14 )
15
16 type T struct {
17         X string
18         Y int
19         Z int `json:"-"`
20 }
21
22 type U struct {
23         Alphabet string `json:"alpha"`
24 }
25
26 type V struct {
27         F1 interface{}
28         F2 int32
29         F3 Number
30 }
31
32 // ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshalling with and
33 // without UseNumber
34 var ifaceNumAsFloat64 = map[string]interface{}{
35         "k1": float64(1),
36         "k2": "s",
37         "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)},
38         "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)},
39 }
40
41 var ifaceNumAsNumber = map[string]interface{}{
42         "k1": Number("1"),
43         "k2": "s",
44         "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")},
45         "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")},
46 }
47
48 type tx struct {
49         x int
50 }
51
52 var txType = reflect.TypeOf((*tx)(nil)).Elem()
53
54 // A type that can unmarshal itself.
55
56 type unmarshaler struct {
57         T bool
58 }
59
60 func (u *unmarshaler) UnmarshalJSON(b []byte) error {
61         *u = unmarshaler{true} // All we need to see that UnmarshalJson is called.
62         return nil
63 }
64
65 type ustruct struct {
66         M unmarshaler
67 }
68
69 var (
70         um0, um1 unmarshaler // target2 of unmarshaling
71         ump      = &um1
72         umtrue   = unmarshaler{true}
73         umslice  = []unmarshaler{{true}}
74         umslicep = new([]unmarshaler)
75         umstruct = ustruct{unmarshaler{true}}
76 )
77
78 // Test data structures for anonymous fields.
79
80 type Point struct {
81         Z int
82 }
83
84 type Top struct {
85         Level0 int
86         Embed0
87         *Embed0a
88         *Embed0b `json:"e,omitempty"` // treated as named
89         Embed0c  `json:"-"`           // ignored
90         Loop
91         Embed0p // has Point with X, Y, used
92         Embed0q // has Point with Z, used
93 }
94
95 type Embed0 struct {
96         Level1a int // overridden by Embed0a's Level1a with json tag
97         Level1b int // used because Embed0a's Level1b is renamed
98         Level1c int // used because Embed0a's Level1c is ignored
99         Level1d int // annihilated by Embed0a's Level1d
100         Level1e int `json:"x"` // annihilated by Embed0a.Level1e
101 }
102
103 type Embed0a struct {
104         Level1a int `json:"Level1a,omitempty"`
105         Level1b int `json:"LEVEL1B,omitempty"`
106         Level1c int `json:"-"`
107         Level1d int // annihilated by Embed0's Level1d
108         Level1f int `json:"x"` // annihilated by Embed0's Level1e
109 }
110
111 type Embed0b Embed0
112
113 type Embed0c Embed0
114
115 type Embed0p struct {
116         image.Point
117 }
118
119 type Embed0q struct {
120         Point
121 }
122
123 type Loop struct {
124         Loop1 int `json:",omitempty"`
125         Loop2 int `json:",omitempty"`
126         *Loop
127 }
128
129 // From reflect test:
130 // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
131 type S5 struct {
132         S6
133         S7
134         S8
135 }
136
137 type S6 struct {
138         X int
139 }
140
141 type S7 S6
142
143 type S8 struct {
144         S9
145 }
146
147 type S9 struct {
148         X int
149         Y int
150 }
151
152 // From reflect test:
153 // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
154 type S10 struct {
155         S11
156         S12
157         S13
158 }
159
160 type S11 struct {
161         S6
162 }
163
164 type S12 struct {
165         S6
166 }
167
168 type S13 struct {
169         S8
170 }
171
172 type unmarshalTest struct {
173         in        string
174         ptr       interface{}
175         out       interface{}
176         err       error
177         useNumber bool
178 }
179
180 type Ambig struct {
181         // Given "hello", the first match should win.
182         First  int `json:"HELLO"`
183         Second int `json:"Hello"`
184 }
185
186 var unmarshalTests = []unmarshalTest{
187         // basic types
188         {in: `true`, ptr: new(bool), out: true},
189         {in: `1`, ptr: new(int), out: 1},
190         {in: `1.2`, ptr: new(float64), out: 1.2},
191         {in: `-5`, ptr: new(int16), out: int16(-5)},
192         {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true},
193         {in: `2`, ptr: new(Number), out: Number("2")},
194         {in: `2`, ptr: new(interface{}), out: float64(2.0)},
195         {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true},
196         {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"},
197         {in: `"http:\/\/"`, ptr: new(string), out: "http://"},
198         {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"},
199         {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"},
200         {in: "null", ptr: new(interface{}), out: nil},
201         {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf("")}},
202         {in: `{"x": 1}`, ptr: new(tx), out: tx{}},
203         {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}},
204         {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true},
205         {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64},
206         {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true},
207
208         // raw values with whitespace
209         {in: "\n true ", ptr: new(bool), out: true},
210         {in: "\t 1 ", ptr: new(int), out: 1},
211         {in: "\r 1.2 ", ptr: new(float64), out: 1.2},
212         {in: "\t -5 \n", ptr: new(int16), out: int16(-5)},
213         {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"},
214
215         // Z has a "-" tag.
216         {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}},
217
218         {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}},
219         {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}},
220         {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}},
221
222         // syntax errors
223         {in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", 17}},
224         {in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", 9}},
225         {in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true},
226
227         // raw value errors
228         {in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
229         {in: " 42 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 5}},
230         {in: "\x01 true", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
231         {in: " false \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 8}},
232         {in: "\x01 1.2", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
233         {in: " 3.4 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 6}},
234         {in: "\x01 \"string\"", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}},
235         {in: " \"string\" \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 11}},
236
237         // array tests
238         {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}},
239         {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}},
240         {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}},
241
242         // composite tests
243         {in: allValueIndent, ptr: new(All), out: allValue},
244         {in: allValueCompact, ptr: new(All), out: allValue},
245         {in: allValueIndent, ptr: new(*All), out: &allValue},
246         {in: allValueCompact, ptr: new(*All), out: &allValue},
247         {in: pallValueIndent, ptr: new(All), out: pallValue},
248         {in: pallValueCompact, ptr: new(All), out: pallValue},
249         {in: pallValueIndent, ptr: new(*All), out: &pallValue},
250         {in: pallValueCompact, ptr: new(*All), out: &pallValue},
251
252         // unmarshal interface test
253         {in: `{"T":false}`, ptr: &um0, out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called
254         {in: `{"T":false}`, ptr: &ump, out: &umtrue},
255         {in: `[{"T":false}]`, ptr: &umslice, out: umslice},
256         {in: `[{"T":false}]`, ptr: &umslicep, out: &umslice},
257         {in: `{"M":{"T":false}}`, ptr: &umstruct, out: umstruct},
258
259         {
260                 in: `{
261                         "Level0": 1,
262                         "Level1b": 2,
263                         "Level1c": 3,
264                         "x": 4,
265                         "Level1a": 5,
266                         "LEVEL1B": 6,
267                         "e": {
268                                 "Level1a": 8,
269                                 "Level1b": 9,
270                                 "Level1c": 10,
271                                 "Level1d": 11,
272                                 "x": 12
273                         },
274                         "Loop1": 13,
275                         "Loop2": 14,
276                         "X": 15,
277                         "Y": 16,
278                         "Z": 17
279                 }`,
280                 ptr: new(Top),
281                 out: Top{
282                         Level0: 1,
283                         Embed0: Embed0{
284                                 Level1b: 2,
285                                 Level1c: 3,
286                         },
287                         Embed0a: &Embed0a{
288                                 Level1a: 5,
289                                 Level1b: 6,
290                         },
291                         Embed0b: &Embed0b{
292                                 Level1a: 8,
293                                 Level1b: 9,
294                                 Level1c: 10,
295                                 Level1d: 11,
296                                 Level1e: 12,
297                         },
298                         Loop: Loop{
299                                 Loop1: 13,
300                                 Loop2: 14,
301                         },
302                         Embed0p: Embed0p{
303                                 Point: image.Point{X: 15, Y: 16},
304                         },
305                         Embed0q: Embed0q{
306                                 Point: Point{Z: 17},
307                         },
308                 },
309         },
310         {
311                 in:  `{"hello": 1}`,
312                 ptr: new(Ambig),
313                 out: Ambig{First: 1},
314         },
315
316         {
317                 in:  `{"X": 1,"Y":2}`,
318                 ptr: new(S5),
319                 out: S5{S8: S8{S9: S9{Y: 2}}},
320         },
321         {
322                 in:  `{"X": 1,"Y":2}`,
323                 ptr: new(S10),
324                 out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}},
325         },
326 }
327
328 func TestMarshal(t *testing.T) {
329         b, err := Marshal(allValue)
330         if err != nil {
331                 t.Fatalf("Marshal allValue: %v", err)
332         }
333         if string(b) != allValueCompact {
334                 t.Errorf("Marshal allValueCompact")
335                 diff(t, b, []byte(allValueCompact))
336                 return
337         }
338
339         b, err = Marshal(pallValue)
340         if err != nil {
341                 t.Fatalf("Marshal pallValue: %v", err)
342         }
343         if string(b) != pallValueCompact {
344                 t.Errorf("Marshal pallValueCompact")
345                 diff(t, b, []byte(pallValueCompact))
346                 return
347         }
348 }
349
350 func TestMarshalBadUTF8(t *testing.T) {
351         s := "hello\xffworld"
352         b, err := Marshal(s)
353         if err == nil {
354                 t.Fatal("Marshal bad UTF8: no error")
355         }
356         if len(b) != 0 {
357                 t.Fatal("Marshal returned data")
358         }
359         if _, ok := err.(*InvalidUTF8Error); !ok {
360                 t.Fatalf("Marshal did not return InvalidUTF8Error: %T %v", err, err)
361         }
362 }
363
364 func TestMarshalNumberZeroVal(t *testing.T) {
365         var n Number
366         out, err := Marshal(n)
367         if err != nil {
368                 t.Fatal(err)
369         }
370         outStr := string(out)
371         if outStr != "0" {
372                 t.Fatalf("Invalid zero val for Number: %q", outStr)
373         }
374 }
375
376 func TestUnmarshal(t *testing.T) {
377         for i, tt := range unmarshalTests {
378                 var scan scanner
379                 in := []byte(tt.in)
380                 if err := checkValid(in, &scan); err != nil {
381                         if !reflect.DeepEqual(err, tt.err) {
382                                 t.Errorf("#%d: checkValid: %#v", i, err)
383                                 continue
384                         }
385                 }
386                 if tt.ptr == nil {
387                         continue
388                 }
389                 // v = new(right-type)
390                 v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
391                 dec := NewDecoder(bytes.NewBuffer(in))
392                 if tt.useNumber {
393                         dec.UseNumber()
394                 }
395                 if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) {
396                         t.Errorf("#%d: %v want %v", i, err, tt.err)
397                         continue
398                 }
399                 if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
400                         t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out)
401                         data, _ := Marshal(v.Elem().Interface())
402                         println(string(data))
403                         data, _ = Marshal(tt.out)
404                         println(string(data))
405                         continue
406                 }
407
408                 // Check round trip.
409                 if tt.err == nil {
410                         enc, err := Marshal(v.Interface())
411                         if err != nil {
412                                 t.Errorf("#%d: error re-marshaling: %v", i, err)
413                                 continue
414                         }
415                         vv := reflect.New(reflect.TypeOf(tt.ptr).Elem())
416                         dec = NewDecoder(bytes.NewBuffer(enc))
417                         if tt.useNumber {
418                                 dec.UseNumber()
419                         }
420                         if err := dec.Decode(vv.Interface()); err != nil {
421                                 t.Errorf("#%d: error re-unmarshaling: %v", i, err)
422                                 continue
423                         }
424                         if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) {
425                                 t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface())
426                                 continue
427                         }
428                 }
429         }
430 }
431
432 func TestUnmarshalMarshal(t *testing.T) {
433         initBig()
434         var v interface{}
435         if err := Unmarshal(jsonBig, &v); err != nil {
436                 t.Fatalf("Unmarshal: %v", err)
437         }
438         b, err := Marshal(v)
439         if err != nil {
440                 t.Fatalf("Marshal: %v", err)
441         }
442         if !bytes.Equal(jsonBig, b) {
443                 t.Errorf("Marshal jsonBig")
444                 diff(t, b, jsonBig)
445                 return
446         }
447 }
448
449 var numberTests = []struct {
450         in       string
451         i        int64
452         intErr   string
453         f        float64
454         floatErr string
455 }{
456         {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1},
457         {in: "-12", i: -12, f: -12.0},
458         {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"},
459 }
460
461 // Independent of Decode, basic coverage of the accessors in Number
462 func TestNumberAccessors(t *testing.T) {
463         for _, tt := range numberTests {
464                 n := Number(tt.in)
465                 if s := n.String(); s != tt.in {
466                         t.Errorf("Number(%q).String() is %q", tt.in, s)
467                 }
468                 if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i {
469                         t.Errorf("Number(%q).Int64() is %d", tt.in, i)
470                 } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) {
471                         t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err)
472                 }
473                 if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f {
474                         t.Errorf("Number(%q).Float64() is %g", tt.in, f)
475                 } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) {
476                         t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err)
477                 }
478         }
479 }
480
481 func TestLargeByteSlice(t *testing.T) {
482         s0 := make([]byte, 2000)
483         for i := range s0 {
484                 s0[i] = byte(i)
485         }
486         b, err := Marshal(s0)
487         if err != nil {
488                 t.Fatalf("Marshal: %v", err)
489         }
490         var s1 []byte
491         if err := Unmarshal(b, &s1); err != nil {
492                 t.Fatalf("Unmarshal: %v", err)
493         }
494         if !bytes.Equal(s0, s1) {
495                 t.Errorf("Marshal large byte slice")
496                 diff(t, s0, s1)
497         }
498 }
499
500 type Xint struct {
501         X int
502 }
503
504 func TestUnmarshalInterface(t *testing.T) {
505         var xint Xint
506         var i interface{} = &xint
507         if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil {
508                 t.Fatalf("Unmarshal: %v", err)
509         }
510         if xint.X != 1 {
511                 t.Fatalf("Did not write to xint")
512         }
513 }
514
515 func TestUnmarshalPtrPtr(t *testing.T) {
516         var xint Xint
517         pxint := &xint
518         if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil {
519                 t.Fatalf("Unmarshal: %v", err)
520         }
521         if xint.X != 1 {
522                 t.Fatalf("Did not write to xint")
523         }
524 }
525
526 func TestEscape(t *testing.T) {
527         const input = `"foobar"<html>`
528         const expected = `"\"foobar\"\u003chtml\u003e"`
529         b, err := Marshal(input)
530         if err != nil {
531                 t.Fatalf("Marshal error: %v", err)
532         }
533         if s := string(b); s != expected {
534                 t.Errorf("Encoding of [%s] was [%s], want [%s]", input, s, expected)
535         }
536 }
537
538 // WrongString is a struct that's misusing the ,string modifier.
539 type WrongString struct {
540         Message string `json:"result,string"`
541 }
542
543 type wrongStringTest struct {
544         in, err string
545 }
546
547 var wrongStringTests = []wrongStringTest{
548         {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`},
549         {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`},
550         {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`},
551 }
552
553 // If people misuse the ,string modifier, the error message should be
554 // helpful, telling the user that they're doing it wrong.
555 func TestErrorMessageFromMisusedString(t *testing.T) {
556         for n, tt := range wrongStringTests {
557                 r := strings.NewReader(tt.in)
558                 var s WrongString
559                 err := NewDecoder(r).Decode(&s)
560                 got := fmt.Sprintf("%v", err)
561                 if got != tt.err {
562                         t.Errorf("%d. got err = %q, want %q", n, got, tt.err)
563                 }
564         }
565 }
566
567 func noSpace(c rune) rune {
568         if isSpace(c) {
569                 return -1
570         }
571         return c
572 }
573
574 type All struct {
575         Bool    bool
576         Int     int
577         Int8    int8
578         Int16   int16
579         Int32   int32
580         Int64   int64
581         Uint    uint
582         Uint8   uint8
583         Uint16  uint16
584         Uint32  uint32
585         Uint64  uint64
586         Uintptr uintptr
587         Float32 float32
588         Float64 float64
589
590         Foo  string `json:"bar"`
591         Foo2 string `json:"bar2,dummyopt"`
592
593         IntStr int64 `json:",string"`
594
595         PBool    *bool
596         PInt     *int
597         PInt8    *int8
598         PInt16   *int16
599         PInt32   *int32
600         PInt64   *int64
601         PUint    *uint
602         PUint8   *uint8
603         PUint16  *uint16
604         PUint32  *uint32
605         PUint64  *uint64
606         PUintptr *uintptr
607         PFloat32 *float32
608         PFloat64 *float64
609
610         String  string
611         PString *string
612
613         Map   map[string]Small
614         MapP  map[string]*Small
615         PMap  *map[string]Small
616         PMapP *map[string]*Small
617
618         EmptyMap map[string]Small
619         NilMap   map[string]Small
620
621         Slice   []Small
622         SliceP  []*Small
623         PSlice  *[]Small
624         PSliceP *[]*Small
625
626         EmptySlice []Small
627         NilSlice   []Small
628
629         StringSlice []string
630         ByteSlice   []byte
631
632         Small   Small
633         PSmall  *Small
634         PPSmall **Small
635
636         Interface  interface{}
637         PInterface *interface{}
638
639         unexported int
640 }
641
642 type Small struct {
643         Tag string
644 }
645
646 var allValue = All{
647         Bool:    true,
648         Int:     2,
649         Int8:    3,
650         Int16:   4,
651         Int32:   5,
652         Int64:   6,
653         Uint:    7,
654         Uint8:   8,
655         Uint16:  9,
656         Uint32:  10,
657         Uint64:  11,
658         Uintptr: 12,
659         Float32: 14.1,
660         Float64: 15.1,
661         Foo:     "foo",
662         Foo2:    "foo2",
663         IntStr:  42,
664         String:  "16",
665         Map: map[string]Small{
666                 "17": {Tag: "tag17"},
667                 "18": {Tag: "tag18"},
668         },
669         MapP: map[string]*Small{
670                 "19": {Tag: "tag19"},
671                 "20": nil,
672         },
673         EmptyMap:    map[string]Small{},
674         Slice:       []Small{{Tag: "tag20"}, {Tag: "tag21"}},
675         SliceP:      []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}},
676         EmptySlice:  []Small{},
677         StringSlice: []string{"str24", "str25", "str26"},
678         ByteSlice:   []byte{27, 28, 29},
679         Small:       Small{Tag: "tag30"},
680         PSmall:      &Small{Tag: "tag31"},
681         Interface:   5.2,
682 }
683
684 var pallValue = All{
685         PBool:      &allValue.Bool,
686         PInt:       &allValue.Int,
687         PInt8:      &allValue.Int8,
688         PInt16:     &allValue.Int16,
689         PInt32:     &allValue.Int32,
690         PInt64:     &allValue.Int64,
691         PUint:      &allValue.Uint,
692         PUint8:     &allValue.Uint8,
693         PUint16:    &allValue.Uint16,
694         PUint32:    &allValue.Uint32,
695         PUint64:    &allValue.Uint64,
696         PUintptr:   &allValue.Uintptr,
697         PFloat32:   &allValue.Float32,
698         PFloat64:   &allValue.Float64,
699         PString:    &allValue.String,
700         PMap:       &allValue.Map,
701         PMapP:      &allValue.MapP,
702         PSlice:     &allValue.Slice,
703         PSliceP:    &allValue.SliceP,
704         PPSmall:    &allValue.PSmall,
705         PInterface: &allValue.Interface,
706 }
707
708 var allValueIndent = `{
709         "Bool": true,
710         "Int": 2,
711         "Int8": 3,
712         "Int16": 4,
713         "Int32": 5,
714         "Int64": 6,
715         "Uint": 7,
716         "Uint8": 8,
717         "Uint16": 9,
718         "Uint32": 10,
719         "Uint64": 11,
720         "Uintptr": 12,
721         "Float32": 14.1,
722         "Float64": 15.1,
723         "bar": "foo",
724         "bar2": "foo2",
725         "IntStr": "42",
726         "PBool": null,
727         "PInt": null,
728         "PInt8": null,
729         "PInt16": null,
730         "PInt32": null,
731         "PInt64": null,
732         "PUint": null,
733         "PUint8": null,
734         "PUint16": null,
735         "PUint32": null,
736         "PUint64": null,
737         "PUintptr": null,
738         "PFloat32": null,
739         "PFloat64": null,
740         "String": "16",
741         "PString": null,
742         "Map": {
743                 "17": {
744                         "Tag": "tag17"
745                 },
746                 "18": {
747                         "Tag": "tag18"
748                 }
749         },
750         "MapP": {
751                 "19": {
752                         "Tag": "tag19"
753                 },
754                 "20": null
755         },
756         "PMap": null,
757         "PMapP": null,
758         "EmptyMap": {},
759         "NilMap": null,
760         "Slice": [
761                 {
762                         "Tag": "tag20"
763                 },
764                 {
765                         "Tag": "tag21"
766                 }
767         ],
768         "SliceP": [
769                 {
770                         "Tag": "tag22"
771                 },
772                 null,
773                 {
774                         "Tag": "tag23"
775                 }
776         ],
777         "PSlice": null,
778         "PSliceP": null,
779         "EmptySlice": [],
780         "NilSlice": null,
781         "StringSlice": [
782                 "str24",
783                 "str25",
784                 "str26"
785         ],
786         "ByteSlice": "Gxwd",
787         "Small": {
788                 "Tag": "tag30"
789         },
790         "PSmall": {
791                 "Tag": "tag31"
792         },
793         "PPSmall": null,
794         "Interface": 5.2,
795         "PInterface": null
796 }`
797
798 var allValueCompact = strings.Map(noSpace, allValueIndent)
799
800 var pallValueIndent = `{
801         "Bool": false,
802         "Int": 0,
803         "Int8": 0,
804         "Int16": 0,
805         "Int32": 0,
806         "Int64": 0,
807         "Uint": 0,
808         "Uint8": 0,
809         "Uint16": 0,
810         "Uint32": 0,
811         "Uint64": 0,
812         "Uintptr": 0,
813         "Float32": 0,
814         "Float64": 0,
815         "bar": "",
816         "bar2": "",
817         "IntStr": "0",
818         "PBool": true,
819         "PInt": 2,
820         "PInt8": 3,
821         "PInt16": 4,
822         "PInt32": 5,
823         "PInt64": 6,
824         "PUint": 7,
825         "PUint8": 8,
826         "PUint16": 9,
827         "PUint32": 10,
828         "PUint64": 11,
829         "PUintptr": 12,
830         "PFloat32": 14.1,
831         "PFloat64": 15.1,
832         "String": "",
833         "PString": "16",
834         "Map": null,
835         "MapP": null,
836         "PMap": {
837                 "17": {
838                         "Tag": "tag17"
839                 },
840                 "18": {
841                         "Tag": "tag18"
842                 }
843         },
844         "PMapP": {
845                 "19": {
846                         "Tag": "tag19"
847                 },
848                 "20": null
849         },
850         "EmptyMap": null,
851         "NilMap": null,
852         "Slice": null,
853         "SliceP": null,
854         "PSlice": [
855                 {
856                         "Tag": "tag20"
857                 },
858                 {
859                         "Tag": "tag21"
860                 }
861         ],
862         "PSliceP": [
863                 {
864                         "Tag": "tag22"
865                 },
866                 null,
867                 {
868                         "Tag": "tag23"
869                 }
870         ],
871         "EmptySlice": null,
872         "NilSlice": null,
873         "StringSlice": null,
874         "ByteSlice": null,
875         "Small": {
876                 "Tag": ""
877         },
878         "PSmall": null,
879         "PPSmall": {
880                 "Tag": "tag31"
881         },
882         "Interface": null,
883         "PInterface": 5.2
884 }`
885
886 var pallValueCompact = strings.Map(noSpace, pallValueIndent)
887
888 func TestRefUnmarshal(t *testing.T) {
889         type S struct {
890                 // Ref is defined in encode_test.go.
891                 R0 Ref
892                 R1 *Ref
893         }
894         want := S{
895                 R0: 12,
896                 R1: new(Ref),
897         }
898         *want.R1 = 12
899
900         var got S
901         if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref"}`), &got); err != nil {
902                 t.Fatalf("Unmarshal: %v", err)
903         }
904         if !reflect.DeepEqual(got, want) {
905                 t.Errorf("got %+v, want %+v", got, want)
906         }
907 }
908
909 // Test that the empty string doesn't panic decoding when ,string is specified
910 // Issue 3450
911 func TestEmptyString(t *testing.T) {
912         type T2 struct {
913                 Number1 int `json:",string"`
914                 Number2 int `json:",string"`
915         }
916         data := `{"Number1":"1", "Number2":""}`
917         dec := NewDecoder(strings.NewReader(data))
918         var t2 T2
919         err := dec.Decode(&t2)
920         if err == nil {
921                 t.Fatal("Decode: did not return error")
922         }
923         if t2.Number1 != 1 {
924                 t.Fatal("Decode: did not set Number1")
925         }
926 }
927
928 func intp(x int) *int {
929         p := new(int)
930         *p = x
931         return p
932 }
933
934 func intpp(x *int) **int {
935         pp := new(*int)
936         *pp = x
937         return pp
938 }
939
940 var interfaceSetTests = []struct {
941         pre  interface{}
942         json string
943         post interface{}
944 }{
945         {"foo", `"bar"`, "bar"},
946         {"foo", `2`, 2.0},
947         {"foo", `true`, true},
948         {"foo", `null`, nil},
949
950         {nil, `null`, nil},
951         {new(int), `null`, nil},
952         {(*int)(nil), `null`, nil},
953         {new(*int), `null`, new(*int)},
954         {(**int)(nil), `null`, nil},
955         {intp(1), `null`, nil},
956         {intpp(nil), `null`, intpp(nil)},
957         {intpp(intp(1)), `null`, intpp(nil)},
958 }
959
960 func TestInterfaceSet(t *testing.T) {
961         for _, tt := range interfaceSetTests {
962                 b := struct{ X interface{} }{tt.pre}
963                 blob := `{"X":` + tt.json + `}`
964                 if err := Unmarshal([]byte(blob), &b); err != nil {
965                         t.Errorf("Unmarshal %#q: %v", blob, err)
966                         continue
967                 }
968                 if !reflect.DeepEqual(b.X, tt.post) {
969                         t.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob, tt.pre, b.X, tt.post)
970                 }
971         }
972 }
973
974 // JSON null values should be ignored for primitives and string values instead of resulting in an error.
975 // Issue 2540
976 func TestUnmarshalNulls(t *testing.T) {
977         jsonData := []byte(`{
978                 "Bool"    : null, 
979                 "Int"     : null, 
980                 "Int8"    : null,
981                 "Int16"   : null,
982                 "Int32"   : null,
983                 "Int64"   : null,
984                 "Uint"    : null,
985                 "Uint8"   : null,
986                 "Uint16"  : null,
987                 "Uint32"  : null,
988                 "Uint64"  : null,
989                 "Float32" : null,
990                 "Float64" : null,
991                 "String"  : null}`)
992
993         nulls := All{
994                 Bool:    true,
995                 Int:     2,
996                 Int8:    3,
997                 Int16:   4,
998                 Int32:   5,
999                 Int64:   6,
1000                 Uint:    7,
1001                 Uint8:   8,
1002                 Uint16:  9,
1003                 Uint32:  10,
1004                 Uint64:  11,
1005                 Float32: 12.1,
1006                 Float64: 13.1,
1007                 String:  "14"}
1008
1009         err := Unmarshal(jsonData, &nulls)
1010         if err != nil {
1011                 t.Errorf("Unmarshal of null values failed: %v", err)
1012         }
1013         if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 ||
1014                 nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 ||
1015                 nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" {
1016
1017                 t.Errorf("Unmarshal of null values affected primitives")
1018         }
1019 }
1020
1021 func TestStringKind(t *testing.T) {
1022         type stringKind string
1023         type aMap map[stringKind]int
1024
1025         var m1, m2 map[stringKind]int
1026         m1 = map[stringKind]int{
1027                 "foo": 42,
1028         }
1029
1030         data, err := Marshal(m1)
1031         if err != nil {
1032                 t.Errorf("Unexpected error marshalling: %v", err)
1033         }
1034
1035         err = Unmarshal(data, &m2)
1036         if err != nil {
1037                 t.Errorf("Unexpected error unmarshalling: %v", err)
1038         }
1039
1040         if !reflect.DeepEqual(m1, m2) {
1041                 t.Error("Items should be equal after encoding and then decoding")
1042         }
1043
1044 }
1045
1046 var decodeTypeErrorTests = []struct {
1047         dest interface{}
1048         src  string
1049 }{
1050         {new(string), `{"user": "name"}`}, // issue 4628.
1051         {new(error), `{}`},                // issue 4222
1052         {new(error), `[]`},
1053         {new(error), `""`},
1054         {new(error), `123`},
1055         {new(error), `true`},
1056 }
1057
1058 func TestUnmarshalTypeError(t *testing.T) {
1059         for _, item := range decodeTypeErrorTests {
1060                 err := Unmarshal([]byte(item.src), item.dest)
1061                 if _, ok := err.(*UnmarshalTypeError); !ok {
1062                         t.Errorf("expected type error for Unmarshal(%q, type %T): got %T",
1063                                 item.src, item.dest, err)
1064                 }
1065         }
1066 }
1067
1068 var unmarshalSyntaxTests = []string{
1069         "tru",
1070         "fals",
1071         "nul",
1072         "123e",
1073         `"hello`,
1074         `[1,2,3`,
1075         `{"key":1`,
1076         `{"key":1,`,
1077 }
1078
1079 func TestUnmarshalSyntax(t *testing.T) {
1080         var x interface{}
1081         for _, src := range unmarshalSyntaxTests {
1082                 err := Unmarshal([]byte(src), &x)
1083                 if _, ok := err.(*SyntaxError); !ok {
1084                         t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err)
1085                 }
1086         }
1087 }
1088
1089 // Test handling of unexported fields that should be ignored.
1090 // Issue 4660
1091 type unexportedFields struct {
1092         Name string
1093         m    map[string]interface{} `json:"-"`
1094         m2   map[string]interface{} `json:"abcd"`
1095 }
1096
1097 func TestUnmarshalUnexported(t *testing.T) {
1098         input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}}`
1099         want := &unexportedFields{Name: "Bob"}
1100
1101         out := &unexportedFields{}
1102         err := Unmarshal([]byte(input), out)
1103         if err != nil {
1104                 t.Errorf("got error %v, expected nil", err)
1105         }
1106         if !reflect.DeepEqual(out, want) {
1107                 t.Errorf("got %q, want %q", out, want)
1108         }
1109 }