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.
14 // Test values for the stream test.
15 // One of each JSON kind.
16 var streamTest = []interface{}{
22 []interface{}{"a", "b", "c"},
23 map[string]interface{}{"K": "Kelvin", "ß": "long s"},
24 3.14, // another value to make sure something can follow map
27 var streamEncoded = `0.1
33 {"ß":"long s","K":"Kelvin"}
37 func TestEncoder(t *testing.T) {
38 for i := 0; i <= len(streamTest); i++ {
40 enc := NewEncoder(&buf)
41 for j, v := range streamTest[0:i] {
42 if err := enc.Encode(v); err != nil {
43 t.Fatalf("encode #%d: %v", j, err)
46 if have, want := buf.String(), nlines(streamEncoded, i); have != want {
47 t.Errorf("encoding %d items: mismatch", i)
48 diff(t, []byte(have), []byte(want))
54 func TestDecoder(t *testing.T) {
55 for i := 0; i <= len(streamTest); i++ {
56 // Use stream without newlines as input,
57 // just to stress the decoder even more.
58 // Our test input does not include back-to-back numbers.
59 // Otherwise stripping the newlines would
60 // merge two adjacent JSON values.
62 for _, c := range nlines(streamEncoded, i) {
67 out := make([]interface{}, i)
68 dec := NewDecoder(&buf)
70 if err := dec.Decode(&out[j]); err != nil {
71 t.Fatalf("decode #%d/%d: %v", j, i, err)
74 if !reflect.DeepEqual(out, streamTest[0:i]) {
75 t.Errorf("decoding %d items: mismatch", i)
77 if !reflect.DeepEqual(out[j], streamTest[j]) {
78 t.Errorf("#%d: have %v want %v", j, out[j], streamTest[j])
86 func nlines(s string, n int) string {
100 func TestRawMessage(t *testing.T) {
101 // TODO(rsc): Should not need the * in *RawMessage
107 const raw = `["\u0056",null]`
108 const msg = `{"X":0.1,"Id":["\u0056",null],"Y":0.2}`
109 err := Unmarshal([]byte(msg), &data)
111 t.Fatalf("Unmarshal: %v", err)
113 if string([]byte(*data.Id)) != raw {
114 t.Fatalf("Raw mismatch: have %#q want %#q", []byte(*data.Id), raw)
116 b, err := Marshal(&data)
118 t.Fatalf("Marshal: %v", err)
120 if string(b) != msg {
121 t.Fatalf("Marshal: have %#q want %#q", b, msg)
125 func TestNullRawMessage(t *testing.T) {
126 // TODO(rsc): Should not need the * in *RawMessage
132 data.Id = new(RawMessage)
133 const msg = `{"X":0.1,"Id":null,"Y":0.2}`
134 err := Unmarshal([]byte(msg), &data)
136 t.Fatalf("Unmarshal: %v", err)
139 t.Fatalf("Raw mismatch: have non-nil, want nil")
141 b, err := Marshal(&data)
143 t.Fatalf("Marshal: %v", err)
145 if string(b) != msg {
146 t.Fatalf("Marshal: have %#q want %#q", b, msg)
150 var blockingTests = []string{
155 func TestBlocking(t *testing.T) {
156 for _, enc := range blockingTests {
158 go w.Write([]byte(enc))
161 // If Decode reads beyond what w.Write writes above,
162 // it will block, and the test will deadlock.
163 if err := NewDecoder(r).Decode(&val); err != nil {
164 t.Errorf("decoding %s: %v", enc, err)