readers_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package ioutils // import "github.com/docker/docker/pkg/ioutils"
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "strings"
  7. "testing"
  8. "testing/iotest"
  9. "time"
  10. )
  11. func TestReadCloserWrapperClose(t *testing.T) {
  12. const text = "hello world"
  13. testErr := errors.New("this will be called when closing")
  14. wrapper := NewReadCloserWrapper(strings.NewReader(text), func() error {
  15. return testErr
  16. })
  17. buf, err := io.ReadAll(wrapper)
  18. if err != nil {
  19. t.Errorf("io.ReadAll(wrapper) err = %v", err)
  20. }
  21. if string(buf) != text {
  22. t.Errorf("expected %v, got: %v", text, string(buf))
  23. }
  24. err = wrapper.Close()
  25. if !errors.Is(err, testErr) {
  26. // readCloserWrapper should have called the anonymous func and thus, fail
  27. t.Errorf("expected %v, got: %v", testErr, err)
  28. }
  29. }
  30. func TestReaderErrWrapperReadOnError(t *testing.T) {
  31. called := false
  32. expectedErr := errors.New("error reader always fail")
  33. wrapper := NewReaderErrWrapper(iotest.ErrReader(expectedErr), func() {
  34. called = true
  35. })
  36. _, err := wrapper.Read([]byte{})
  37. if !errors.Is(err, expectedErr) {
  38. t.Errorf("expected %v, got: %v", expectedErr, err)
  39. }
  40. if !called {
  41. t.Fatalf("readErrWrapper should have called the anonymous function on failure")
  42. }
  43. }
  44. func TestReaderErrWrapperRead(t *testing.T) {
  45. const text = "hello world"
  46. wrapper := NewReaderErrWrapper(strings.NewReader(text), func() {
  47. t.Fatalf("readErrWrapper should not have called the anonymous function")
  48. })
  49. num, err := wrapper.Read(make([]byte, len(text)+10))
  50. if err != nil {
  51. t.Error(err)
  52. }
  53. if expected := len(text); num != expected {
  54. t.Errorf("readerErrWrapper should have read %d byte, but read %d", expected, num)
  55. }
  56. }
  57. type perpetualReader struct{}
  58. func (p *perpetualReader) Read(buf []byte) (n int, err error) {
  59. for i := 0; i != len(buf); i++ {
  60. buf[i] = 'a'
  61. }
  62. return len(buf), nil
  63. }
  64. func TestCancelReadCloser(t *testing.T) {
  65. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  66. defer cancel()
  67. crc := NewCancelReadCloser(ctx, io.NopCloser(&perpetualReader{}))
  68. for {
  69. var buf [128]byte
  70. _, err := crc.Read(buf[:])
  71. if err == context.DeadlineExceeded {
  72. break
  73. } else if err != nil {
  74. t.Fatalf("got unexpected error: %v", err)
  75. }
  76. }
  77. }