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.
13 // Test values for the stream test.
14 // One of each JSON kind.
15 var streamTest
= []interface{}{
21 []interface{}{"a", "b", "c"},
22 map[string]interface{}{"K": "Kelvin", "ß": "long s"},
23 float64(3.14), // another value to make sure something can follow map
26 var streamEncoded
= `0.1
32 {"ß":"long s","K":"Kelvin"}
36 func TestEncoder(t
*testing
.T
) {
37 for i
:= 0; i
<= len(streamTest
); i
++ {
39 enc
:= NewEncoder(&buf
)
40 for j
, v
:= range streamTest
[0:i
] {
41 if err
:= enc
.Encode(v
); err
!= nil {
42 t
.Fatalf("encode #%d: %v", j
, err
)
45 if have
, want
:= buf
.String(), nlines(streamEncoded
, i
); have
!= want
{
46 t
.Errorf("encoding %d items: mismatch", i
)
47 diff(t
, []byte(have
), []byte(want
))
53 func TestDecoder(t
*testing
.T
) {
54 for i
:= 0; i
<= len(streamTest
); i
++ {
55 // Use stream without newlines as input,
56 // just to stress the decoder even more.
57 // Our test input does not include back-to-back numbers.
58 // Otherwise stripping the newlines would
59 // merge two adjacent JSON values.
61 for _
, c
:= range nlines(streamEncoded
, i
) {
66 out
:= make([]interface{}, i
)
67 dec
:= NewDecoder(&buf
)
69 if err
:= dec
.Decode(&out
[j
]); err
!= nil {
70 t
.Fatalf("decode #%d/%d: %v", j
, i
, err
)
73 if !reflect
.DeepEqual(out
, streamTest
[0:i
]) {
74 t
.Errorf("decoding %d items: mismatch")
76 if !reflect
.DeepEqual(out
[j
], streamTest
[j
]) {
77 t
.Errorf("#%d: have %v want %v", out
[j
], streamTest
[j
])
85 func nlines(s
string, n
int) string {
99 func TestRawMessage(t
*testing
.T
) {
100 // TODO(rsc): Should not need the * in *RawMessage
106 const raw
= `["\u0056",null]`
107 const msg
= `{"X":0.1,"Id":["\u0056",null],"Y":0.2}`
108 err
:= Unmarshal([]byte(msg
), &data
)
110 t
.Fatalf("Unmarshal: %v", err
)
112 if string([]byte(*data
.Id
)) != raw
{
113 t
.Fatalf("Raw mismatch: have %#q want %#q", []byte(*data
.Id
), raw
)
115 b
, err
:= Marshal(&data
)
117 t
.Fatalf("Marshal: %v", err
)
119 if string(b
) != msg
{
120 t
.Fatalf("Marshal: have %#q want %#q", b
, msg
)