Debian Codegraph @

decode_stream_test.go

raw
1 package json_test
2
3 import (
4 "bytes"
5 "errors"
6 "io"
7 "strings"
8 "testing"
9 "testing/iotest"
10
11 json "github.com/goccy/go-json"
12 )
13
14 // The stream decoder reads a whole value into its buffer before decoding it, so a value
15 // which arrives in pieces is decoded exactly as by Unmarshal, wherever the reads end.
16
17 func TestDecodeStreamMultibyteRuneSplitByRead(t *testing.T) {
18 type Struct struct {
19 Title string `json:"title"`
20 Body string `json:"body"`
21 }
22 body := strings.Repeat("日本語更新テスト ", 320)
23 input := `{"title": "utf8 repro", "body": "` + body + `"}`
24 for _, chunk := range []int{1, 2, 3, 7, 512, 1000} {
25 var out Struct
26 r := &chunkReader{data: []byte(input), chunk: chunk}
27 if err := json.NewDecoder(r).Decode(&out); err != nil {
28 t.Fatalf("chunk %d: %v", chunk, err)
29 }
30 if out.Body != body {
31 t.Fatalf("chunk %d: the body is corrupted: %q", chunk, out.Body)
32 }
33 }
34 // one byte per read, into a plain string
35 var s string
36 if err := json.NewDecoder(iotest.OneByteReader(strings.NewReader(`"é"`))).Decode(&s); err != nil {
37 t.Fatal(err)
38 }
39 if s != "é" {
40 t.Fatalf("got %q", s)
41 }
42 }
43
44 func TestDecodeStreamTruncatedKeyWithInvalidUTF8(t *testing.T) {
45 // {" followed by 1024 bytes of 0xae, no closing quote or brace ( issue 609 ).
46 data := append([]byte(`{"`), bytes.Repeat([]byte{0xae}, 1024)...)
47 var v any
48 err := json.NewDecoder(bytes.NewReader(data)).Decode(&v)
49 if !errors.Is(err, io.ErrUnexpectedEOF) {
50 t.Fatalf("expected io.ErrUnexpectedEOF, got %v", err)
51 }
52 // The same key, complete: every invalid byte becomes U+FFFD, as encoding/json does.
53 data = append(append([]byte(`{"`), bytes.Repeat([]byte{0xae}, 1024)...), []byte(`":1}`)...)
54 if err := json.NewDecoder(bytes.NewReader(data)).Decode(&v); err != nil {
55 t.Fatal(err)
56 }
57 m := v.(map[string]any)
58 if len(m) != 1 {
59 t.Fatalf("got %d keys", len(m))
60 }
61 for k := range m {
62 if k != strings.Repeat("�", 1024) {
63 t.Fatalf("the key is not replaced: %q", k[:12])
64 }
65 }
66 }
67
68 func TestDecodeStreamTokenLongStringWithInvalidUTF8(t *testing.T) {
69 // A string longer than the initial buffer, with invalid bytes ( issue 424 ).
70 input := []byte(`"` + strings.Repeat("0", 1000) + strings.Repeat("\xe2", 100) + `"`)
71 dec := json.NewDecoder(bytes.NewReader(input))
72 tok, err := dec.Token()
73 if err != nil {
74 t.Fatal(err)
75 }
76 want := strings.Repeat("0", 1000) + strings.Repeat("�", 100)
77 if tok != want {
78 t.Fatalf("got %q", tok)
79 }
80 if _, err := dec.Token(); err != io.EOF {
81 t.Fatalf("expected io.EOF, got %v", err)
82 }
83 }
84
85 type failingReader struct {
86 data []byte
87 err error
88 }
89
90 func (r *failingReader) Read(p []byte) (int, error) {
91 if len(r.data) == 0 {
92 return 0, r.err
93 }
94 n := copy(p, r.data)
95 r.data = r.data[n:]
96 return n, nil
97 }
98
99 func TestDecodeStreamReadError(t *testing.T) {
100 // The error of the reader is reported, not io.EOF ( issues 485 and 403 ).
101 errLimit := errors.New("request body too large")
102 var v map[string]string
103 err := json.NewDecoder(&failingReader{data: []byte(`{"a":"b",`), err: errLimit}).Decode(&v)
104 if !errors.Is(err, errLimit) {
105 t.Fatalf("expected the error of the reader, got %v", err)
106 }
107 // The data before the error is decoded.
108 err = json.NewDecoder(&failingReader{data: []byte(`{"a":"b"}`), err: errLimit}).Decode(&v)
109 if err != nil {
110 t.Fatal(err)
111 }
112 if v["a"] != "b" {
113 t.Fatalf("got %v", v)
114 }
115 // io.LimitReader cuts the input: the truncated value is an error, not a value.
116 body := `{"region": "test", "title":"GreatSite.com","status": "suspended"}`
117 r := io.LimitReader(strings.NewReader(body), 40)
118 if err := json.NewDecoder(r).Decode(&v); !errors.Is(err, io.ErrUnexpectedEOF) {
119 t.Fatalf("expected io.ErrUnexpectedEOF, got %v", err)
120 }
121 }
122
123 func TestDecodeStreamInputOffset(t *testing.T) {
124 // The offset counts the bytes of the input, whatever the escapes ( issue 520 ).
125 input := `{"test":"\""} {"a":"é\n"}`
126 dec := json.NewDecoder(strings.NewReader(input))
127 if got := dec.InputOffset(); got != 0 {
128 t.Fatalf("expected 0, got %d", got)
129 }
130 var v map[string]any
131 if err := dec.Decode(&v); err != nil {
132 t.Fatal(err)
133 }
134 if v["test"] != "\"" {
135 t.Fatalf("got %v", v)
136 }
137 if got := dec.InputOffset(); got != 13 {
138 t.Fatalf("expected 13, got %d", got)
139 }
140 if err := dec.Decode(&v); err != nil {
141 t.Fatal(err)
142 }
143 if v["a"] != "é\n" {
144 t.Fatalf("got %v", v)
145 }
146 if got := dec.InputOffset(); got != int64(len(input)) {
147 t.Fatalf("expected %d, got %d", len(input), got)
148 }
149 }
150
151 func TestDecodeStreamErrorOffset(t *testing.T) {
152 // The offset of a syntax error counts from the beginning of the input, not of the buffer.
153 input := strings.Repeat(`{"a":1} `, 100) + `{"a":x}`
154 dec := json.NewDecoder(strings.NewReader(input))
155 var v map[string]any
156 var err error
157 for err == nil {
158 err = dec.Decode(&v)
159 }
160 var syntaxErr *json.SyntaxError
161 if !errors.As(err, &syntaxErr) {
162 t.Fatalf("expected a syntax error, got %v", err)
163 }
164 if syntaxErr.Offset < int64(len(input)-7) || syntaxErr.Offset > int64(len(input)) {
165 t.Fatalf("the offset %d is not in the last value ( %d bytes )", syntaxErr.Offset, len(input))
166 }
167 }
168
169 func TestDecodeStreamValuesBackToBack(t *testing.T) {
170 // Values with nothing between them, and a value cut by the end of the buffer.
171 input := `0.1"hello"null true false {"a":[1,2,3]}[` + strings.Repeat("1,", 1000) + `1]"` + strings.Repeat("x", 2000) + `"`
172 dec := json.NewDecoder(iotest.HalfReader(strings.NewReader(input)))
173 var got []any
174 for {
175 var v any
176 if err := dec.Decode(&v); err != nil {
177 if err == io.EOF {
178 break
179 }
180 t.Fatal(err)
181 }
182 got = append(got, v)
183 }
184 if len(got) != 8 {
185 t.Fatalf("got %d values", len(got))
186 }
187 if got[0] != 0.1 || got[1] != "hello" || got[2] != nil || got[3] != true || got[4] != false {
188 t.Fatalf("got %v", got[:5])
189 }
190 if len(got[6].([]any)) != 1001 || got[7] != strings.Repeat("x", 2000) {
191 t.Fatalf("the large values are wrong")
192 }
193 }
194
195 func TestDecodeStreamNoReadPastValue(t *testing.T) {
196 // Decode returns as soon as the value is complete: the reader is not read past it.
197 pr, pw := io.Pipe()
198 go func() {
199 _, _ = pw.Write([]byte(`{"a": 1} `))
200 // the pipe is left open: a read past the value would block
201 }()
202 dec := json.NewDecoder(pr)
203 var v map[string]int
204 if err := dec.Decode(&v); err != nil {
205 t.Fatal(err)
206 }
207 if v["a"] != 1 {
208 t.Fatalf("got %v", v)
209 }
210 pw.Close()
211 }
212
213 func TestDecodeStreamMore(t *testing.T) {
214 dec := json.NewDecoder(strings.NewReader(`{"a": [1, 2], "b": {}} 3`))
215 var got []any
216 for {
217 tok, err := dec.Token()
218 if err == io.EOF {
219 break
220 }
221 if err != nil {
222 t.Fatal(err)
223 }
224 got = append(got, tok)
225 }
226 want := []any{json.Delim('{'), "a", json.Delim('['), 1.0, 2.0, json.Delim(']'), "b", json.Delim('{'), json.Delim('}'), json.Delim('}'), 3.0}
227 if len(got) != len(want) {
228 t.Fatalf("got %v, want %v", got, want)
229 }
230 for i := range want {
231 if got[i] != want[i] {
232 t.Fatalf("token %d: got %v, want %v", i, got[i], want[i])
233 }
234 }
235 }
236
237 type chunkReader struct {
238 data []byte
239 chunk int
240 }
241
242 func (r *chunkReader) Read(p []byte) (int, error) {
243 if len(r.data) == 0 {
244 return 0, io.EOF
245 }
246 n := min(len(p), r.chunk, len(r.data))
247 copy(p, r.data[:n])
248 r.data = r.data[n:]
249 return n, nil
250 }