jsoniter_adapter_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package jsoniter
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/json-iterator/go/require"
  6. "io/ioutil"
  7. "testing"
  8. )
  9. func Test_new_decoder(t *testing.T) {
  10. should := require.New(t)
  11. decoder1 := json.NewDecoder(bytes.NewBufferString(`[1][2]`))
  12. decoder2 := NewDecoder(bytes.NewBufferString(`[1][2]`))
  13. arr1 := []int{}
  14. should.Nil(decoder1.Decode(&arr1))
  15. should.Equal([]int{1}, arr1)
  16. arr2 := []int{}
  17. should.True(decoder1.More())
  18. buffered, _ := ioutil.ReadAll(decoder1.Buffered())
  19. should.Equal("[2]", string(buffered))
  20. should.Nil(decoder2.Decode(&arr2))
  21. should.Equal([]int{1}, arr2)
  22. should.True(decoder2.More())
  23. buffered, _ = ioutil.ReadAll(decoder2.Buffered())
  24. should.Equal("[2]", string(buffered))
  25. should.Nil(decoder1.Decode(&arr1))
  26. should.Equal([]int{2}, arr1)
  27. should.False(decoder1.More())
  28. should.Nil(decoder2.Decode(&arr2))
  29. should.Equal([]int{2}, arr2)
  30. should.False(decoder2.More())
  31. }
  32. func Test_new_encoder(t *testing.T) {
  33. should := require.New(t)
  34. buf1 := &bytes.Buffer{}
  35. encoder1 := json.NewEncoder(buf1)
  36. encoder1.Encode([]int{1})
  37. should.Equal("[1]\n", buf1.String())
  38. buf2 := &bytes.Buffer{}
  39. encoder2 := NewEncoder(buf2)
  40. encoder2.Encode([]int{1})
  41. should.Equal("[1]", buf2.String())
  42. }
  43. func Test_use_number(t *testing.T) {
  44. should := require.New(t)
  45. decoder1 := json.NewDecoder(bytes.NewBufferString(`123`))
  46. decoder1.UseNumber()
  47. decoder2 := NewDecoder(bytes.NewBufferString(`123`))
  48. decoder2.UseNumber()
  49. var obj1 interface{}
  50. should.Nil(decoder1.Decode(&obj1))
  51. should.Equal(json.Number("123"), obj1)
  52. var obj2 interface{}
  53. should.Nil(decoder2.Decode(&obj2))
  54. should.Equal(json.Number("123"), obj2)
  55. }