github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/p2p/protocol/ping/ping_test.go (about)

     1  package ping
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
     8  	peer "github.com/ipfs/go-ipfs/p2p/peer"
     9  	netutil "github.com/ipfs/go-ipfs/p2p/test/util"
    10  )
    11  
    12  func TestPing(t *testing.T) {
    13  	ctx, cancel := context.WithCancel(context.Background())
    14  	defer cancel()
    15  	h1 := netutil.GenHostSwarm(t, ctx)
    16  	h2 := netutil.GenHostSwarm(t, ctx)
    17  
    18  	err := h1.Connect(ctx, peer.PeerInfo{
    19  		ID:    h2.ID(),
    20  		Addrs: h2.Addrs(),
    21  	})
    22  
    23  	if err != nil {
    24  		t.Fatal(err)
    25  	}
    26  
    27  	ps1 := NewPingService(h1)
    28  	ps2 := NewPingService(h2)
    29  
    30  	testPing(t, ps1, h2.ID())
    31  	testPing(t, ps2, h1.ID())
    32  }
    33  
    34  func testPing(t *testing.T, ps *PingService, p peer.ID) {
    35  	pctx, cancel := context.WithCancel(context.Background())
    36  	defer cancel()
    37  	ts, err := ps.Ping(pctx, p)
    38  	if err != nil {
    39  		t.Fatal(err)
    40  	}
    41  
    42  	for i := 0; i < 5; i++ {
    43  		select {
    44  		case took := <-ts:
    45  			t.Log("ping took: ", took)
    46  		case <-time.After(time.Second * 4):
    47  			t.Fatal("failed to receive ping")
    48  		}
    49  	}
    50  
    51  }