jsoniter_null_test.go 1.8 KB

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