github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/p2p/host/basic/basic_host_test.go (about)

     1  package basichost_test
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  	"testing"
     7  
     8  	inet "github.com/ipfs/go-ipfs/p2p/net"
     9  	protocol "github.com/ipfs/go-ipfs/p2p/protocol"
    10  	testutil "github.com/ipfs/go-ipfs/p2p/test/util"
    11  
    12  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
    13  )
    14  
    15  func TestHostSimple(t *testing.T) {
    16  
    17  	ctx := context.Background()
    18  	h1 := testutil.GenHostSwarm(t, ctx)
    19  	h2 := testutil.GenHostSwarm(t, ctx)
    20  	defer h1.Close()
    21  	defer h2.Close()
    22  
    23  	h2pi := h2.Peerstore().PeerInfo(h2.ID())
    24  	if err := h1.Connect(ctx, h2pi); err != nil {
    25  		t.Fatal(err)
    26  	}
    27  
    28  	piper, pipew := io.Pipe()
    29  	h2.SetStreamHandler(protocol.TestingID, func(s inet.Stream) {
    30  		defer s.Close()
    31  		w := io.MultiWriter(s, pipew)
    32  		io.Copy(w, s) // mirror everything
    33  	})
    34  
    35  	s, err := h1.NewStream(protocol.TestingID, h2pi.ID)
    36  	if err != nil {
    37  		t.Fatal(err)
    38  	}
    39  
    40  	// write to the stream
    41  	buf1 := []byte("abcdefghijkl")
    42  	if _, err := s.Write(buf1); err != nil {
    43  		t.Fatal(err)
    44  	}
    45  
    46  	// get it from the stream (echoed)
    47  	buf2 := make([]byte, len(buf1))
    48  	if _, err := io.ReadFull(s, buf2); err != nil {
    49  		t.Fatal(err)
    50  	}
    51  	if !bytes.Equal(buf1, buf2) {
    52  		t.Fatal("buf1 != buf2 -- %x != %x", buf1, buf2)
    53  	}
    54  
    55  	// get it from the pipe (tee)
    56  	buf3 := make([]byte, len(buf1))
    57  	if _, err := io.ReadFull(piper, buf3); err != nil {
    58  		t.Fatal(err)
    59  	}
    60  	if !bytes.Equal(buf1, buf3) {
    61  		t.Fatal("buf1 != buf3 -- %x != %x", buf1, buf3)
    62  	}
    63  }