bufreader_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. }
  55. func (s *BufferedReaderTestSuite) TestPeek() {
  56. data := "hello world"
  57. br := New(strings.NewReader(data))
  58. // Peek at first 5 bytes
  59. peeked, err := br.Peek(5)
  60. s.Require().NoError(err)
  61. s.Equal("hello", string(peeked))
  62. s.Equal(0, br.pos) // Position should not change
  63. // Read the same data to verify peek didn't consume it
  64. p := make([]byte, 5)
  65. n, err := br.Read(p)
  66. s.Require().NoError(err)
  67. s.Equal(5, n)
  68. s.Equal("hello", string(p))
  69. s.Equal(5, br.pos) // Position should now be updated
  70. // Peek at the next 7 bytes (which are beyond the EOF)
  71. peeked2, err := br.Peek(7)
  72. s.Require().NoError(err)
  73. s.Equal(" world", string(peeked2))
  74. s.Equal(5, br.pos) // Position should still be 5
  75. }
  76. // TestBufferedReaderSuite runs the test suite
  77. func TestBufferedReader(t *testing.T) {
  78. suite.Run(t, new(BufferedReaderTestSuite))
  79. }