reader_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package buffer // import "github.com/tdewolff/parse/buffer"
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "testing"
  7. "github.com/tdewolff/test"
  8. )
  9. func TestReader(t *testing.T) {
  10. s := []byte("abcde")
  11. r := NewReader(s)
  12. test.Bytes(t, r.Bytes(), s, "reader must return bytes stored")
  13. buf := make([]byte, 3)
  14. n, err := r.Read(buf)
  15. test.T(t, err, nil, "error")
  16. test.That(t, n == 3, "first read must read 3 characters")
  17. test.Bytes(t, buf, []byte("abc"), "first read must match 'abc'")
  18. n, err = r.Read(buf)
  19. test.T(t, err, nil, "error")
  20. test.That(t, n == 2, "second read must read 2 characters")
  21. test.Bytes(t, buf[:n], []byte("de"), "second read must match 'de'")
  22. n, err = r.Read(buf)
  23. test.T(t, err, io.EOF, "error")
  24. test.That(t, n == 0, "third read must read 0 characters")
  25. n, err = r.Read(nil)
  26. test.T(t, err, nil, "error")
  27. test.That(t, n == 0, "read to nil buffer must return 0 characters read")
  28. r.Reset()
  29. n, err = r.Read(buf)
  30. test.T(t, err, nil, "error")
  31. test.That(t, n == 3, "read after reset must read 3 characters")
  32. test.Bytes(t, buf, []byte("abc"), "read after reset must match 'abc'")
  33. }
  34. func ExampleNewReader() {
  35. r := NewReader([]byte("Lorem ipsum"))
  36. w := &bytes.Buffer{}
  37. io.Copy(w, r)
  38. fmt.Println(w.String())
  39. // Output: Lorem ipsum
  40. }