github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/ioutils/readers_test.go (about) 1 package ioutils // import "github.com/demonoid81/moby/pkg/ioutils" 2 3 import ( 4 "context" 5 "fmt" 6 "io/ioutil" 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 func TestHashData(t *testing.T) { 62 reader := strings.NewReader("hash-me") 63 actual, err := HashData(reader) 64 if err != nil { 65 t.Fatal(err) 66 } 67 expected := "sha256:4d11186aed035cc624d553e10db358492c84a7cd6b9670d92123c144930450aa" 68 if actual != expected { 69 t.Fatalf("Expecting %s, got %s", expected, actual) 70 } 71 } 72 73 type perpetualReader struct{} 74 75 func (p *perpetualReader) Read(buf []byte) (n int, err error) { 76 for i := 0; i != len(buf); i++ { 77 buf[i] = 'a' 78 } 79 return len(buf), nil 80 } 81 82 func TestCancelReadCloser(t *testing.T) { 83 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) 84 defer cancel() 85 cancelReadCloser := NewCancelReadCloser(ctx, ioutil.NopCloser(&perpetualReader{})) 86 for { 87 var buf [128]byte 88 _, err := cancelReadCloser.Read(buf[:]) 89 if err == context.DeadlineExceeded { 90 break 91 } else if err != nil { 92 t.Fatalf("got unexpected error: %v", err) 93 } 94 } 95 }