PageRenderTime 13ms CodeModel.GetById 2ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/pkg/net/pipe_test.go

http://golang-china.googlecode.com/
Go | 57 lines | 45 code | 6 blank | 6 comment | 9 complexity | a0f2d9edff2a529d103f08ee4ad0a488 MD5 | raw file
 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
 5package net
 6
 7import (
 8	"bytes"
 9	"io"
10	"os"
11	"testing"
12)
13
14func 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
25func 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// Test a simple read/write/close sequence.
39// Assumes that the underlying io.Pipe implementation
40// is solid and we're just testing the net wrapping.
41
42func 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}