/pkg/net/pipe_test.go

http://golang-china.googlecode.com/ · Go · 57 lines · 45 code · 6 blank · 6 comment · 13 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. package net
  5. import (
  6. "bytes"
  7. "io"
  8. "os"
  9. "testing"
  10. )
  11. func checkWrite(t *testing.T, w io.Writer, data []byte, c chan int) {
  12. n, err := w.Write(data)
  13. if err != nil {
  14. t.Errorf("write: %v", err)
  15. }
  16. if n != len(data) {
  17. t.Errorf("short write: %d != %d", n, len(data))
  18. }
  19. c <- 0
  20. }
  21. func checkRead(t *testing.T, r io.Reader, data []byte, wantErr os.Error) {
  22. buf := make([]byte, len(data)+10)
  23. n, err := r.Read(buf)
  24. if err != wantErr {
  25. t.Errorf("read: %v", err)
  26. return
  27. }
  28. if n != len(data) || !bytes.Equal(buf[0:n], data) {
  29. t.Errorf("bad read: got %q", buf[0:n])
  30. return
  31. }
  32. }
  33. // Test a simple read/write/close sequence.
  34. // Assumes that the underlying io.Pipe implementation
  35. // is solid and we're just testing the net wrapping.
  36. func TestPipe(t *testing.T) {
  37. c := make(chan int)
  38. cli, srv := Pipe()
  39. go checkWrite(t, cli, []byte("hello, world"), c)
  40. checkRead(t, srv, []byte("hello, world"), nil)
  41. <-c
  42. go checkWrite(t, srv, []byte("line 2"), c)
  43. checkRead(t, cli, []byte("line 2"), nil)
  44. <-c
  45. go checkWrite(t, cli, []byte("a third line"), c)
  46. checkRead(t, srv, []byte("a third line"), nil)
  47. <-c
  48. go srv.Close()
  49. checkRead(t, cli, nil, os.EOF)
  50. cli.Close()
  51. }