bufreader_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package bufreader
  2. import (
  3. "io"
  4. "strings"
  5. "testing"
  6. "github.com/stretchr/testify/suite"
  7. )
  8. // BufferedReaderTestSuite defines the test suite for the buffered reader
  9. type BufferedReaderTestSuite struct {
  10. suite.Suite
  11. }
  12. func (s *BufferedReaderTestSuite) TestRead() {
  13. data := "hello world"
  14. br := New(strings.NewReader(data))
  15. // First read
  16. p1 := make([]byte, 5)
  17. n1, err1 := br.Read(p1)
  18. s.Require().NoError(err1)
  19. s.Equal(5, n1)
  20. s.Equal("hello", string(p1))
  21. // Second read
  22. p2 := make([]byte, 6)
  23. n2, err2 := br.Read(p2)
  24. s.Require().NoError(err2)
  25. s.Equal(6, n2)
  26. s.Equal(" world", string(p2))
  27. // Verify position
  28. s.Equal(11, br.pos)
  29. }
  30. func (s *BufferedReaderTestSuite) TestEOF() {
  31. data := "hello"
  32. br := New(strings.NewReader(data))
  33. // Read all data
  34. p1 := make([]byte, 5)
  35. n1, err1 := br.Read(p1)
  36. s.Require().NoError(err1)
  37. s.Equal(5, n1)
  38. s.Equal("hello", string(p1))
  39. // Try to read more - should get EOF
  40. p2 := make([]byte, 5)
  41. n2, err2 := br.Read(p2)
  42. s.Equal(io.EOF, err2)
  43. s.Equal(0, n2)
  44. }
  45. func (s *BufferedReaderTestSuite) TestEOF_WhenDataExhausted() {
  46. data := "hello"
  47. br := New(strings.NewReader(data))
  48. // Try to read more than available
  49. p := make([]byte, 10)
  50. n, err := br.Read(p)
  51. s.Require().NoError(err)
  52. s.Equal(5, n)
  53. s.Equal("hello", string(p[:n]))
  54. br.Rewind() // Reset position to 0
  55. // We shouldn't get EOF after rewinding and reading again
  56. n, err = br.Read(p)
  57. s.Require().NoError(err)
  58. s.Equal(5, n)
  59. s.Equal("hello", string(p[:n]))
  60. }
  61. func (s *BufferedReaderTestSuite) TestPeek() {
  62. data := "hello world"
  63. br := New(strings.NewReader(data))
  64. // Peek at first 5 bytes
  65. peeked, err := br.Peek(5)
  66. s.Require().NoError(err)
  67. s.Equal("hello", string(peeked))
  68. s.Equal(0, br.pos) // Position should not change
  69. // Read the same data to verify peek didn't consume it
  70. p := make([]byte, 5)
  71. n, err := br.Read(p)
  72. s.Require().NoError(err)
  73. s.Equal(5, n)
  74. s.Equal("hello", string(p))
  75. s.Equal(5, br.pos) // Position should now be updated
  76. // Peek at the next 7 bytes (which are beyond the EOF)
  77. peeked2, err := br.Peek(7)
  78. s.Require().NoError(err)
  79. s.Equal(" world", string(peeked2))
  80. s.Equal(5, br.pos) // Position should still be 5
  81. }
  82. // TestBufferedReaderSuite runs the test suite
  83. func TestBufferedReader(t *testing.T) {
  84. suite.Run(t, new(BufferedReaderTestSuite))
  85. }