github.com/aergoio/aergo@v1.3.1/cmd/aergocli/util/encoding/json/stream_test.go (about) 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 "io" 10 "io/ioutil" 11 "log" 12 "net" 13 "net/http" 14 "net/http/httptest" 15 "reflect" 16 "strings" 17 "testing" 18 ) 19 20 // Test values for the stream test. 21 // One of each JSON kind. 22 var streamTest = []interface{}{ 23 0.1, 24 "hello", 25 nil, 26 true, 27 false, 28 []interface{}{"a", "b", "c"}, 29 map[string]interface{}{"K": "Kelvin", "ß": "long s"}, 30 3.14, // another value to make sure something can follow map 31 } 32 33 var streamEncoded = `0.1 34 "hello" 35 null 36 true 37 false 38 ["a","b","c"] 39 {"ß":"long s","K":"Kelvin"} 40 3.14 41 ` 42 43 func TestEncoder(t *testing.T) { 44 for i := 0; i <= len(streamTest); i++ { 45 var buf bytes.Buffer 46 enc := NewEncoder(&buf) 47 // Check that enc.SetIndent("", "") turns off indentation. 48 enc.SetIndent(">", ".") 49 enc.SetIndent("", "") 50 for j, v := range streamTest[0:i] { 51 if err := enc.Encode(v); err != nil { 52 t.Fatalf("encode #%d: %v", j, err) 53 } 54 } 55 if have, want := buf.String(), nlines(streamEncoded, i); have != want { 56 t.Errorf("encoding %d items: mismatch", i) 57 diff(t, []byte(have), []byte(want)) 58 break 59 } 60 } 61 } 62 63 var streamEncodedIndent = `0.1 64 "hello" 65 null 66 true 67 false 68 [ 69 >."a", 70 >."b", 71 >."c" 72 >] 73 { 74 >."ß": "long s", 75 >."K": "Kelvin" 76 >} 77 3.14 78 ` 79 80 func TestEncoderIndent(t *testing.T) { 81 var buf bytes.Buffer 82 enc := NewEncoder(&buf) 83 enc.SetIndent(">", ".") 84 for _, v := range streamTest { 85 enc.Encode(v) 86 } 87 if have, want := buf.String(), streamEncodedIndent; have != want { 88 t.Error("indented encoding mismatch") 89 diff(t, []byte(have), []byte(want)) 90 } 91 } 92 93 func TestEncoderSetEscapeHTML(t *testing.T) { 94 var c C 95 var ct CText 96 var tagStruct struct { 97 Valid int `json:"<>&#! "` 98 Invalid int `json:"\\"` 99 } 100 for _, tt := range []struct { 101 name string 102 v interface{} 103 wantEscape string 104 want string 105 }{ 106 {"c", c, `"\u003c\u0026\u003e"`, `"<&>"`}, 107 {"ct", ct, `"\"\u003c\u0026\u003e\""`, `"\"<&>\""`}, 108 {`"<&>"`, "<&>", `"\u003c\u0026\u003e"`, `"<&>"`}, 109 { 110 "tagStruct", tagStruct, 111 `{"\u003c\u003e\u0026#! ":0,"Invalid":0}`, 112 `{"<>&#! ":0,"Invalid":0}`, 113 }, 114 } { 115 var buf bytes.Buffer 116 enc := NewEncoder(&buf) 117 if err := enc.Encode(tt.v); err != nil { 118 t.Fatalf("Encode(%s): %s", tt.name, err) 119 } 120 if got := strings.TrimSpace(buf.String()); got != tt.wantEscape { 121 t.Errorf("Encode(%s) = %#q, want %#q", tt.name, got, tt.wantEscape) 122 } 123 buf.Reset() 124 enc.SetEscapeHTML(false) 125 if err := enc.Encode(tt.v); err != nil { 126 t.Fatalf("SetEscapeHTML(false) Encode(%s): %s", tt.name, err) 127 } 128 if got := strings.TrimSpace(buf.String()); got != tt.want { 129 t.Errorf("SetEscapeHTML(false) Encode(%s) = %#q, want %#q", 130 tt.name, got, tt.want) 131 } 132 } 133 } 134 135 func TestDecoder(t *testing.T) { 136 for i := 0; i <= len(streamTest); i++ { 137 // Use stream without newlines as input, 138 // just to stress the decoder even more. 139 // Our test input does not include back-to-back numbers. 140 // Otherwise stripping the newlines would 141 // merge two adjacent JSON values. 142 var buf bytes.Buffer 143 for _, c := range nlines(streamEncoded, i) { 144 if c != '\n' { 145 buf.WriteRune(c) 146 } 147 } 148 out := make([]interface{}, i) 149 dec := NewDecoder(&buf) 150 for j := range out { 151 if err := dec.Decode(&out[j]); err != nil { 152 t.Fatalf("decode #%d/%d: %v", j, i, err) 153 } 154 } 155 if !reflect.DeepEqual(out, streamTest[0:i]) { 156 t.Errorf("decoding %d items: mismatch", i) 157 for j := range out { 158 if !reflect.DeepEqual(out[j], streamTest[j]) { 159 t.Errorf("#%d: have %v want %v", j, out[j], streamTest[j]) 160 } 161 } 162 break 163 } 164 } 165 } 166 167 func TestDecoderBuffered(t *testing.T) { 168 r := strings.NewReader(`{"Name": "Gopher"} extra `) 169 var m struct { 170 Name string 171 } 172 d := NewDecoder(r) 173 err := d.Decode(&m) 174 if err != nil { 175 t.Fatal(err) 176 } 177 if m.Name != "Gopher" { 178 t.Errorf("Name = %q; want Gopher", m.Name) 179 } 180 rest, err := ioutil.ReadAll(d.Buffered()) 181 if err != nil { 182 t.Fatal(err) 183 } 184 if g, w := string(rest), " extra "; g != w { 185 t.Errorf("Remaining = %q; want %q", g, w) 186 } 187 } 188 189 func nlines(s string, n int) string { 190 if n <= 0 { 191 return "" 192 } 193 for i, c := range s { 194 if c == '\n' { 195 if n--; n == 0 { 196 return s[0 : i+1] 197 } 198 } 199 } 200 return s 201 } 202 203 func TestRawMessage(t *testing.T) { 204 var data struct { 205 X float64 206 Id RawMessage 207 Y float32 208 } 209 const raw = `["\u0056",null]` 210 const msg = `{"X":0.1,"Id":["\u0056",null],"Y":0.2}` 211 err := Unmarshal([]byte(msg), &data) 212 if err != nil { 213 t.Fatalf("Unmarshal: %v", err) 214 } 215 if string([]byte(data.Id)) != raw { 216 t.Fatalf("Raw mismatch: have %#q want %#q", []byte(data.Id), raw) 217 } 218 b, err := Marshal(&data) 219 if err != nil { 220 t.Fatalf("Marshal: %v", err) 221 } 222 if string(b) != msg { 223 t.Fatalf("Marshal: have %#q want %#q", b, msg) 224 } 225 } 226 227 func TestNullRawMessage(t *testing.T) { 228 var data struct { 229 X float64 230 Id RawMessage 231 IdPtr *RawMessage 232 Y float32 233 } 234 const msg = `{"X":0.1,"Id":null,"IdPtr":null,"Y":0.2}` 235 err := Unmarshal([]byte(msg), &data) 236 if err != nil { 237 t.Fatalf("Unmarshal: %v", err) 238 } 239 if want, got := "null", string(data.Id); want != got { 240 t.Fatalf("Raw mismatch: have %q, want %q", got, want) 241 } 242 if data.IdPtr != nil { 243 t.Fatalf("Raw pointer mismatch: have non-nil, want nil") 244 } 245 b, err := Marshal(&data) 246 if err != nil { 247 t.Fatalf("Marshal: %v", err) 248 } 249 if string(b) != msg { 250 t.Fatalf("Marshal: have %#q want %#q", b, msg) 251 } 252 } 253 254 var blockingTests = []string{ 255 `{"x": 1}`, 256 `[1, 2, 3]`, 257 } 258 259 func TestBlocking(t *testing.T) { 260 for _, enc := range blockingTests { 261 r, w := net.Pipe() 262 go w.Write([]byte(enc)) 263 var val interface{} 264 265 // If Decode reads beyond what w.Write writes above, 266 // it will block, and the test will deadlock. 267 if err := NewDecoder(r).Decode(&val); err != nil { 268 t.Errorf("decoding %s: %v", enc, err) 269 } 270 r.Close() 271 w.Close() 272 } 273 } 274 275 func BenchmarkEncoderEncode(b *testing.B) { 276 b.ReportAllocs() 277 type T struct { 278 X, Y string 279 } 280 v := &T{"foo", "bar"} 281 b.RunParallel(func(pb *testing.PB) { 282 for pb.Next() { 283 if err := NewEncoder(ioutil.Discard).Encode(v); err != nil { 284 b.Fatal(err) 285 } 286 } 287 }) 288 } 289 290 type tokenStreamCase struct { 291 json string 292 expTokens []interface{} 293 } 294 295 type decodeThis struct { 296 v interface{} 297 } 298 299 var tokenStreamCases []tokenStreamCase = []tokenStreamCase{ 300 // streaming token cases 301 {json: `10`, expTokens: []interface{}{float64(10)}}, 302 {json: ` [10] `, expTokens: []interface{}{ 303 Delim('['), float64(10), Delim(']')}}, 304 {json: ` [false,10,"b"] `, expTokens: []interface{}{ 305 Delim('['), false, float64(10), "b", Delim(']')}}, 306 {json: `{ "a": 1 }`, expTokens: []interface{}{ 307 Delim('{'), "a", float64(1), Delim('}')}}, 308 {json: `{"a": 1, "b":"3"}`, expTokens: []interface{}{ 309 Delim('{'), "a", float64(1), "b", "3", Delim('}')}}, 310 {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ 311 Delim('['), 312 Delim('{'), "a", float64(1), Delim('}'), 313 Delim('{'), "a", float64(2), Delim('}'), 314 Delim(']')}}, 315 {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ 316 Delim('{'), "obj", Delim('{'), "a", float64(1), Delim('}'), 317 Delim('}')}}, 318 {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ 319 Delim('{'), "obj", Delim('['), 320 Delim('{'), "a", float64(1), Delim('}'), 321 Delim(']'), Delim('}')}}, 322 323 // streaming tokens with intermittent Decode() 324 {json: `{ "a": 1 }`, expTokens: []interface{}{ 325 Delim('{'), "a", 326 decodeThis{float64(1)}, 327 Delim('}')}}, 328 {json: ` [ { "a" : 1 } ] `, expTokens: []interface{}{ 329 Delim('['), 330 decodeThis{map[string]interface{}{"a": float64(1)}}, 331 Delim(']')}}, 332 {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ 333 Delim('['), 334 decodeThis{map[string]interface{}{"a": float64(1)}}, 335 decodeThis{map[string]interface{}{"a": float64(2)}}, 336 Delim(']')}}, 337 {json: `{ "obj" : [ { "a" : 1 } ] }`, expTokens: []interface{}{ 338 Delim('{'), "obj", Delim('['), 339 decodeThis{map[string]interface{}{"a": float64(1)}}, 340 Delim(']'), Delim('}')}}, 341 342 {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ 343 Delim('{'), "obj", 344 decodeThis{map[string]interface{}{"a": float64(1)}}, 345 Delim('}')}}, 346 {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ 347 Delim('{'), "obj", 348 decodeThis{[]interface{}{ 349 map[string]interface{}{"a": float64(1)}, 350 }}, 351 Delim('}')}}, 352 {json: ` [{"a": 1} {"a": 2}] `, expTokens: []interface{}{ 353 Delim('['), 354 decodeThis{map[string]interface{}{"a": float64(1)}}, 355 decodeThis{&SyntaxError{"expected comma after array element", 11}}, 356 }}, 357 {json: `{ "` + strings.Repeat("a", 513) + `" 1 }`, expTokens: []interface{}{ 358 Delim('{'), strings.Repeat("a", 513), 359 decodeThis{&SyntaxError{"expected colon after object key", 518}}, 360 }}, 361 {json: `{ "\a" }`, expTokens: []interface{}{ 362 Delim('{'), 363 &SyntaxError{"invalid character 'a' in string escape code", 3}, 364 }}, 365 {json: ` \a`, expTokens: []interface{}{ 366 &SyntaxError{"invalid character '\\\\' looking for beginning of value", 1}, 367 }}, 368 } 369 370 func TestDecodeInStream(t *testing.T) { 371 372 for ci, tcase := range tokenStreamCases { 373 374 dec := NewDecoder(strings.NewReader(tcase.json)) 375 for i, etk := range tcase.expTokens { 376 377 var tk interface{} 378 var err error 379 380 if dt, ok := etk.(decodeThis); ok { 381 etk = dt.v 382 err = dec.Decode(&tk) 383 } else { 384 tk, err = dec.Token() 385 } 386 if experr, ok := etk.(error); ok { 387 if err == nil || !reflect.DeepEqual(err, experr) { 388 t.Errorf("case %v: Expected error %#v in %q, but was %#v", ci, experr, tcase.json, err) 389 } 390 break 391 } else if err == io.EOF { 392 t.Errorf("case %v: Unexpected EOF in %q", ci, tcase.json) 393 break 394 } else if err != nil { 395 t.Errorf("case %v: Unexpected error '%#v' in %q", ci, err, tcase.json) 396 break 397 } 398 if !reflect.DeepEqual(tk, etk) { 399 t.Errorf(`case %v: %q @ %v expected %T(%v) was %T(%v)`, ci, tcase.json, i, etk, etk, tk, tk) 400 break 401 } 402 } 403 } 404 405 } 406 407 // Test from golang.org/issue/11893 408 func TestHTTPDecoding(t *testing.T) { 409 const raw = `{ "foo": "bar" }` 410 411 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 412 w.Write([]byte(raw)) 413 })) 414 defer ts.Close() 415 res, err := http.Get(ts.URL) 416 if err != nil { 417 log.Fatalf("GET failed: %v", err) 418 } 419 defer res.Body.Close() 420 421 foo := struct { 422 Foo string 423 }{} 424 425 d := NewDecoder(res.Body) 426 err = d.Decode(&foo) 427 if err != nil { 428 t.Fatalf("Decode: %v", err) 429 } 430 if foo.Foo != "bar" { 431 t.Errorf("decoded %q; want \"bar\"", foo.Foo) 432 } 433 434 // make sure we get the EOF the second time 435 err = d.Decode(&foo) 436 if err != io.EOF { 437 t.Errorf("err = %v; want io.EOF", err) 438 } 439 }