github.com/michael-k/docker@v1.7.0-rc2/pkg/stdcopy/stdcopy_test.go (about) 1 package stdcopy 2 3 import ( 4 "bytes" 5 "io/ioutil" 6 "strings" 7 "testing" 8 ) 9 10 func TestNewStdWriter(t *testing.T) { 11 writer := NewStdWriter(ioutil.Discard, Stdout) 12 if writer == nil { 13 t.Fatalf("NewStdWriter with an invalid StdType should not return nil.") 14 } 15 } 16 17 func TestWriteWithUnitializedStdWriter(t *testing.T) { 18 writer := StdWriter{ 19 Writer: nil, 20 prefix: Stdout, 21 sizeBuf: make([]byte, 4), 22 } 23 n, err := writer.Write([]byte("Something here")) 24 if n != 0 || err == nil { 25 t.Fatalf("Should fail when given an uncomplete or uninitialized StdWriter") 26 } 27 } 28 29 func TestWriteWithNilBytes(t *testing.T) { 30 writer := NewStdWriter(ioutil.Discard, Stdout) 31 n, err := writer.Write(nil) 32 if err != nil { 33 t.Fatalf("Shouldn't have fail when given no data") 34 } 35 if n > 0 { 36 t.Fatalf("Write should have written 0 byte, but has written %d", n) 37 } 38 } 39 40 func TestWrite(t *testing.T) { 41 writer := NewStdWriter(ioutil.Discard, Stdout) 42 data := []byte("Test StdWrite.Write") 43 n, err := writer.Write(data) 44 if err != nil { 45 t.Fatalf("Error while writing with StdWrite") 46 } 47 if n != len(data) { 48 t.Fatalf("Write should have writen %d byte but wrote %d.", len(data), n) 49 } 50 } 51 52 func TestStdCopyWithInvalidInputHeader(t *testing.T) { 53 dstOut := NewStdWriter(ioutil.Discard, Stdout) 54 dstErr := NewStdWriter(ioutil.Discard, Stderr) 55 src := strings.NewReader("Invalid input") 56 _, err := StdCopy(dstOut, dstErr, src) 57 if err == nil { 58 t.Fatal("StdCopy with invalid input header should fail.") 59 } 60 } 61 62 func TestStdCopyWithCorruptedPrefix(t *testing.T) { 63 data := []byte{0x01, 0x02, 0x03} 64 src := bytes.NewReader(data) 65 written, err := StdCopy(nil, nil, src) 66 if err != nil { 67 t.Fatalf("StdCopy should not return an error with corrupted prefix.") 68 } 69 if written != 0 { 70 t.Fatalf("StdCopy should have written 0, but has written %d", written) 71 } 72 } 73 74 func BenchmarkWrite(b *testing.B) { 75 w := NewStdWriter(ioutil.Discard, Stdout) 76 data := []byte("Test line for testing stdwriter performance\n") 77 data = bytes.Repeat(data, 100) 78 b.SetBytes(int64(len(data))) 79 b.ResetTimer() 80 for i := 0; i < b.N; i++ { 81 if _, err := w.Write(data); err != nil { 82 b.Fatal(err) 83 } 84 } 85 }