The Go Programming Language

Source file src/pkg/net/pipe_test.go

     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	
     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	// 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	
    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	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.