github.com/ssdev-go/moby@v17.12.1-ce-rc2+incompatible/pkg/ioutils/readers_test.go (about) 1 package ioutils 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "strings" 7 "testing" 8 "time" 9 10 "github.com/stretchr/testify/assert" 11 "golang.org/x/net/context" 12 ) 13 14 // Implement io.Reader 15 type errorReader struct{} 16 17 func (r *errorReader) Read(p []byte) (int, error) { 18 return 0, fmt.Errorf("error reader always fail") 19 } 20 21 func TestReadCloserWrapperClose(t *testing.T) { 22 reader := strings.NewReader("A string reader") 23 wrapper := NewReadCloserWrapper(reader, func() error { 24 return fmt.Errorf("This will be called when closing") 25 }) 26 err := wrapper.Close() 27 if err == nil || !strings.Contains(err.Error(), "This will be called when closing") { 28 t.Fatalf("readCloserWrapper should have call the anonymous func and thus, fail.") 29 } 30 } 31 32 func TestReaderErrWrapperReadOnError(t *testing.T) { 33 called := false 34 reader := &errorReader{} 35 wrapper := NewReaderErrWrapper(reader, func() { 36 called = true 37 }) 38 _, err := wrapper.Read([]byte{}) 39 assert.EqualError(t, err, "error reader always fail") 40 if !called { 41 t.Fatalf("readErrWrapper should have call the anonymous function on failure") 42 } 43 } 44 45 func TestReaderErrWrapperRead(t *testing.T) { 46 reader := strings.NewReader("a string reader.") 47 wrapper := NewReaderErrWrapper(reader, func() { 48 t.Fatalf("readErrWrapper should not have called the anonymous function") 49 }) 50 // Read 20 byte (should be ok with the string above) 51 num, err := wrapper.Read(make([]byte, 20)) 52 if err != nil { 53 t.Fatal(err) 54 } 55 if num != 16 { 56 t.Fatalf("readerErrWrapper should have read 16 byte, but read %d", num) 57 } 58 } 59 60 func TestHashData(t *testing.T) { 61 reader := strings.NewReader("hash-me") 62 actual, err := HashData(reader) 63 if err != nil { 64 t.Fatal(err) 65 } 66 expected := "sha256:4d11186aed035cc624d553e10db358492c84a7cd6b9670d92123c144930450aa" 67 if actual != expected { 68 t.Fatalf("Expecting %s, got %s", expected, actual) 69 } 70 } 71 72 type perpetualReader struct{} 73 74 func (p *perpetualReader) Read(buf []byte) (n int, err error) { 75 for i := 0; i != len(buf); i++ { 76 buf[i] = 'a' 77 } 78 return len(buf), nil 79 } 80 81 func TestCancelReadCloser(t *testing.T) { 82 ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) 83 cancelReadCloser := NewCancelReadCloser(ctx, ioutil.NopCloser(&perpetualReader{})) 84 for { 85 var buf [128]byte 86 _, err := cancelReadCloser.Read(buf[:]) 87 if err == context.DeadlineExceeded { 88 break 89 } else if err != nil { 90 t.Fatalf("got unexpected error: %v", err) 91 } 92 } 93 }