github.com/coreos/mantle@v0.13.0/network/bufnet/pipe_test.go (about) 1 // Copyright 2010 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 // Licensed under the same terms as Go itself: 5 // https://github.com/golang/go/blob/master/LICENSE 6 7 package bufnet 8 9 import ( 10 "bytes" 11 "io" 12 "testing" 13 ) 14 15 func checkPipeWrite(t *testing.T, w io.Writer, data []byte, c chan int) { 16 n, err := w.Write(data) 17 if err != nil { 18 t.Error(err) 19 } 20 if n != len(data) { 21 t.Errorf("short write: %d != %d", n, len(data)) 22 } 23 c <- 0 24 } 25 26 func checkPipeRead(t *testing.T, r io.Reader, data []byte, wantErr error) { 27 buf := make([]byte, len(data)+10) 28 n, err := r.Read(buf) 29 if err != wantErr { 30 t.Error(err) 31 return 32 } 33 if n != len(data) || !bytes.Equal(buf[0:n], data) { 34 t.Errorf("bad read: got %q", buf[0:n]) 35 return 36 } 37 } 38 39 // TestPipe tests a simple read/write/close sequence. 40 // Assumes that the underlying io.Pipe implementation 41 // is solid and we're just testing the net wrapping. 42 func TestPipe(t *testing.T) { 43 c := make(chan int) 44 cli, srv := Pipe() 45 go checkPipeWrite(t, cli, []byte("hello, world"), c) 46 checkPipeRead(t, srv, []byte("hello, world"), nil) 47 <-c 48 go checkPipeWrite(t, srv, []byte("line 2"), c) 49 checkPipeRead(t, cli, []byte("line 2"), nil) 50 <-c 51 go checkPipeWrite(t, cli, []byte("a third line"), c) 52 checkPipeRead(t, srv, []byte("a third line"), nil) 53 <-c 54 go srv.Close() 55 checkPipeRead(t, cli, nil, io.EOF) 56 cli.Close() 57 }