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