stream_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package jsoniter
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. )
  6. func Test_writeByte_should_grow_buffer(t *testing.T) {
  7. should := require.New(t)
  8. stream := NewStream(ConfigDefault, nil, 1)
  9. stream.writeByte('1')
  10. should.Equal("1", string(stream.Buffer()))
  11. should.Equal(1, len(stream.buf))
  12. stream.writeByte('2')
  13. should.Equal("12", string(stream.Buffer()))
  14. should.Equal(2, len(stream.buf))
  15. stream.writeThreeBytes('3', '4', '5')
  16. should.Equal("12345", string(stream.Buffer()))
  17. }
  18. func Test_writeBytes_should_grow_buffer(t *testing.T) {
  19. should := require.New(t)
  20. stream := NewStream(ConfigDefault, nil, 1)
  21. stream.Write([]byte{'1', '2'})
  22. should.Equal("12", string(stream.Buffer()))
  23. should.Equal(2, len(stream.buf))
  24. stream.Write([]byte{'3', '4', '5', '6', '7'})
  25. should.Equal("1234567", string(stream.Buffer()))
  26. should.Equal(7, len(stream.buf))
  27. }
  28. func Test_writeIndention_should_grow_buffer(t *testing.T) {
  29. should := require.New(t)
  30. stream := NewStream(Config{IndentionStep: 2}.Froze(), nil, 1)
  31. stream.WriteVal([]int{1, 2, 3})
  32. should.Equal("[\n 1,\n 2,\n 3\n]", string(stream.Buffer()))
  33. }
  34. func Test_writeRaw_should_grow_buffer(t *testing.T) {
  35. should := require.New(t)
  36. stream := NewStream(ConfigDefault, nil, 1)
  37. stream.WriteRaw("123")
  38. should.Nil(stream.Error)
  39. should.Equal("123", string(stream.Buffer()))
  40. }
  41. func Test_writeString_should_grow_buffer(t *testing.T) {
  42. should := require.New(t)
  43. stream := NewStream(ConfigDefault, nil, 0)
  44. stream.WriteString("123")
  45. should.Nil(stream.Error)
  46. should.Equal(`"123"`, string(stream.Buffer()))
  47. }
  48. type NopWriter struct {
  49. bufferSize int
  50. }
  51. func (w *NopWriter) Write(p []byte) (n int, err error) {
  52. w.bufferSize = cap(p)
  53. return len(p), nil
  54. }
  55. func Test_flush_buffer_should_stop_grow_buffer(t *testing.T) {
  56. // Stream an array of a zillion zeros.
  57. writer := new(NopWriter)
  58. stream := NewStream(ConfigDefault, writer, 512)
  59. stream.WriteArrayStart()
  60. for i := 0; i < 10000000; i++ {
  61. stream.WriteInt(0)
  62. stream.WriteMore()
  63. stream.Flush()
  64. }
  65. stream.WriteInt(0)
  66. stream.WriteArrayEnd()
  67. // Confirm that the buffer didn't have to grow.
  68. should := require.New(t)
  69. // 512 is the internal buffer size set in NewEncoder
  70. //
  71. // Flush is called after each array element, so only the first 8 bytes of it
  72. // is ever used, and it is never extended. Capacity remains 512.
  73. should.Equal(512, writer.bufferSize)
  74. }