-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhost_test.go
95 lines (78 loc) · 2.23 KB
/
host_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package p2pnet
import (
"context"
"path"
"testing"
"time"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/stretchr/testify/require"
)
const testMaxMessageSize = 1 << 17
func init() {
_ = logging.SetLogLevel("p2pnet", "debug")
}
func basicTestConfig(t *testing.T, namespaces []string) *Config {
// t.TempDir() is unique on every call. Don't reuse this config with multiple hosts.
tmpDir := t.TempDir()
return &Config{
Ctx: context.Background(),
DataDir: tmpDir,
Port: 0, // OS randomized libp2p port
KeyFile: path.Join(tmpDir, "node.key"),
Bootnodes: nil,
ListenIP: "127.0.0.1",
AdvertisedNamespacesFunc: func() []string {
return namespaces
},
}
}
func newHost(t *testing.T, cfg *Config) *Host {
h, err := NewHost(cfg)
require.NoError(t, err)
t.Cleanup(func() {
err = h.Stop()
require.NoError(t, err)
})
return h
}
func TestNewHost(t *testing.T) {
h := newHost(t, basicTestConfig(t, []string{""}))
err := h.Start()
require.NoError(t, err)
addresses := h.Addresses()
require.NotEmpty(t, addresses)
for _, addr := range h.Addresses() {
t.Log(addr)
}
}
func TestAdvertiseDiscover(t *testing.T) {
nameSpaces := []string{"", "one", "two", "three"}
h1 := newHost(t, basicTestConfig(t, nameSpaces))
err := h1.Start()
require.NoError(t, err)
h1Addresses := h1.Addresses()
require.NotEmpty(t, h1Addresses)
cfgH2 := basicTestConfig(t, nameSpaces)
cfgH2.Bootnodes = []string{h1Addresses[0].String()}
h2 := newHost(t, cfgH2)
err = h2.Start()
require.NoError(t, err)
// h1's first advertisement attempt failed, as h2 was not yet online to
// form a DHT with. Run h1's advertisement loop now instead of waiting.
h1.Advertise()
time.Sleep(testAdvertPropagationDelay)
for _, ns := range nameSpaces {
peerIDs, err := h2.Discover(ns, time.Second*3)
require.NoError(t, err, "namespace=%q", ns)
require.Len(t, peerIDs, 1, "namespace=%q", ns)
require.Equal(t, h1.PeerID(), peerIDs[0], "namespace=%q", ns)
}
}
func TestHost_ConnectToSelf(t *testing.T) {
h := newHost(t, basicTestConfig(t, nil))
err := h.Start()
require.NoError(t, err)
err = h.Connect(context.Background(), peer.AddrInfo{ID: h.PeerID()})
require.ErrorIs(t, err, errCannotConnectToSelf)
}