ping_test.go 1.09 KB
Newer Older
vyzo's avatar
vyzo committed
1
package ping_test
Jeromy's avatar
Jeromy committed
2
3

import (
Jeromy's avatar
Jeromy committed
4
	"context"
Jeromy's avatar
Jeromy committed
5
6
7
	"testing"
	"time"

Jeromy's avatar
Jeromy committed
8
9
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
Steven Allen's avatar
Steven Allen committed
10
	swarmt "github.com/libp2p/go-libp2p-swarm/testing"
Jeromy's avatar
Jeromy committed
11
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
vyzo's avatar
vyzo committed
12
	ping "github.com/libp2p/go-libp2p/p2p/protocol/ping"
Jeromy's avatar
Jeromy committed
13
14
15
16
17
)

func TestPing(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Steven Allen's avatar
Steven Allen committed
18
19
	h1 := bhost.New(swarmt.GenSwarm(t, ctx))
	h2 := bhost.New(swarmt.GenSwarm(t, ctx))
Jeromy's avatar
Jeromy committed
20

Jeromy's avatar
Jeromy committed
21
	err := h1.Connect(ctx, pstore.PeerInfo{
Jeromy's avatar
Jeromy committed
22
23
24
25
26
27
28
29
		ID:    h2.ID(),
		Addrs: h2.Addrs(),
	})

	if err != nil {
		t.Fatal(err)
	}

vyzo's avatar
vyzo committed
30
31
	ps1 := ping.NewPingService(h1)
	ps2 := ping.NewPingService(h2)
Jeromy's avatar
Jeromy committed
32
33
34
35
36

	testPing(t, ps1, h2.ID())
	testPing(t, ps2, h1.ID())
}

vyzo's avatar
vyzo committed
37
func testPing(t *testing.T, ps *ping.PingService, p peer.ID) {
Jeromy's avatar
Jeromy committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
	pctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ts, err := ps.Ping(pctx, p)
	if err != nil {
		t.Fatal(err)
	}

	for i := 0; i < 5; i++ {
		select {
		case took := <-ts:
			t.Log("ping took: ", took)
		case <-time.After(time.Second * 4):
			t.Fatal("failed to receive ping")
		}
	}

}