jsoniter_null_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package misc_tests
  2. import (
  3. "bytes"
  4. "io"
  5. "testing"
  6. "github.com/json-iterator/go"
  7. "github.com/stretchr/testify/require"
  8. )
  9. func Test_read_null(t *testing.T) {
  10. should := require.New(t)
  11. iter := jsoniter.ParseString(jsoniter.ConfigDefault, `null`)
  12. should.True(iter.ReadNil())
  13. iter = jsoniter.ParseString(jsoniter.ConfigDefault, `null`)
  14. should.Nil(iter.Read())
  15. iter = jsoniter.ParseString(jsoniter.ConfigDefault, `navy`)
  16. iter.Read()
  17. should.True(iter.Error != nil && iter.Error != io.EOF)
  18. iter = jsoniter.ParseString(jsoniter.ConfigDefault, `navy`)
  19. iter.ReadNil()
  20. should.True(iter.Error != nil && iter.Error != io.EOF)
  21. }
  22. func Test_write_null(t *testing.T) {
  23. should := require.New(t)
  24. buf := &bytes.Buffer{}
  25. stream := jsoniter.NewStream(jsoniter.ConfigDefault, buf, 4096)
  26. stream.WriteNil()
  27. stream.Flush()
  28. should.Nil(stream.Error)
  29. should.Equal("null", buf.String())
  30. }
  31. func Test_decode_null_object_field(t *testing.T) {
  32. should := require.New(t)
  33. iter := jsoniter.ParseString(jsoniter.ConfigDefault, `[null,"a"]`)
  34. iter.ReadArray()
  35. if iter.ReadObject() != "" {
  36. t.FailNow()
  37. }
  38. iter.ReadArray()
  39. if iter.ReadString() != "a" {
  40. t.FailNow()
  41. }
  42. type TestObject struct {
  43. Field string
  44. }
  45. objs := []TestObject{}
  46. should.Nil(jsoniter.UnmarshalFromString("[null]", &objs))
  47. should.Len(objs, 1)
  48. }
  49. func Test_decode_null_array_element(t *testing.T) {
  50. should := require.New(t)
  51. iter := jsoniter.ParseString(jsoniter.ConfigDefault, `[null,"a"]`)
  52. should.True(iter.ReadArray())
  53. should.True(iter.ReadNil())
  54. should.True(iter.ReadArray())
  55. should.Equal("a", iter.ReadString())
  56. }
  57. func Test_decode_null_string(t *testing.T) {
  58. should := require.New(t)
  59. iter := jsoniter.ParseString(jsoniter.ConfigDefault, `[null,"a"]`)
  60. should.True(iter.ReadArray())
  61. should.Equal("", iter.ReadString())
  62. should.True(iter.ReadArray())
  63. should.Equal("a", iter.ReadString())
  64. }
  65. func Test_decode_null_skip(t *testing.T) {
  66. iter := jsoniter.ParseString(jsoniter.ConfigDefault, `[null,"a"]`)
  67. iter.ReadArray()
  68. iter.Skip()
  69. iter.ReadArray()
  70. if iter.ReadString() != "a" {
  71. t.FailNow()
  72. }
  73. }