1
2
3
4
5 package net
6
7 import (
8 "bytes"
9 "io"
10 "os"
11 "testing"
12 )
13
14 func checkWrite(t *testing.T, w io.Writer, data []byte, c chan int) {
15 n, err := w.Write(data)
16 if err != nil {
17 t.Errorf("write: %v", err)
18 }
19 if n != len(data) {
20 t.Errorf("short write: %d != %d", n, len(data))
21 }
22 c <- 0
23 }
24
25 func checkRead(t *testing.T, r io.Reader, data []byte, wantErr os.Error) {
26 buf := make([]byte, len(data)+10)
27 n, err := r.Read(buf)
28 if err != wantErr {
29 t.Errorf("read: %v", err)
30 return
31 }
32 if n != len(data) || !bytes.Equal(buf[0:n], data) {
33 t.Errorf("bad read: got %q", buf[0:n])
34 return
35 }
36 }
37
38
39
40
41
42 func TestPipe(t *testing.T) {
43 c := make(chan int)
44 cli, srv := Pipe()
45 go checkWrite(t, cli, []byte("hello, world"), c)
46 checkRead(t, srv, []byte("hello, world"), nil)
47 <-c
48 go checkWrite(t, srv, []byte("line 2"), c)
49 checkRead(t, cli, []byte("line 2"), nil)
50 <-c
51 go checkWrite(t, cli, []byte("a third line"), c)
52 checkRead(t, srv, []byte("a third line"), nil)
53 <-c
54 go srv.Close()
55 checkRead(t, cli, nil, os.EOF)
56 cli.Close()
57 }