-
Notifications
You must be signed in to change notification settings - Fork 6
/
p2p_test.go
103 lines (90 loc) · 2.23 KB
/
p2p_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
96
97
98
99
100
101
102
103
package p2p
import (
"context"
"fmt"
"io"
"strconv"
"testing"
"github.com/stretchr/testify/require"
)
func TestBroadcast(t *testing.T) {
runP2P := func(t *testing.T, options ...Option) {
ctx := context.Background()
n := 10
hosts := make([]*Host, n)
for i := 0; i < n; i++ {
opts := []Option{
Port(30000 + i),
SecureIO(),
MasterKey(strconv.Itoa(i)),
}
opts = append(opts, options...)
host, err := NewHost(ctx, opts...)
require.NoError(t, err)
require.NoError(t, host.AddBroadcastPubSub("test", func(ctx context.Context, data []byte) error {
fmt.Print(string(data))
fmt.Printf(", received by %s\n", host.HostIdentity())
return nil
}))
hosts[i] = host
}
bootstrapInfo := hosts[0].Info()
for i := 0; i < n; i++ {
if i != 0 {
require.NoError(t, hosts[i].Connect(ctx, bootstrapInfo))
}
hosts[i].JoinOverlay(ctx)
}
for i := 0; i < n; i++ {
require.NoError(
t,
hosts[i].Broadcast("test", []byte(fmt.Sprintf("msg sent from %s", hosts[i].HostIdentity()))),
)
}
for i := 0; i < n; i++ {
require.NoError(t, hosts[i].Close())
}
}
t.Run("flood", func(t *testing.T) {
runP2P(t)
})
t.Run("gossip", func(t *testing.T) {
runP2P(t, Gossip())
})
}
func TestUnicast(t *testing.T) {
ctx := context.Background()
n := 10
hosts := make([]*Host, n)
for i := 0; i < n; i++ {
host, err := NewHost(ctx, Port(30000+i), SecureIO(), MasterKey(strconv.Itoa(i)))
require.NoError(t, err)
require.NoError(t, host.AddUnicastPubSub("test", func(ctx context.Context, w io.Writer, data []byte) error {
fmt.Print(string(data))
fmt.Printf(", received by %s\n", host.HostIdentity())
return nil
}))
hosts[i] = host
}
bootstrapInfo := hosts[0].Info()
for i := 0; i < n; i++ {
if i != 0 {
require.NoError(t, hosts[i].Connect(ctx, bootstrapInfo))
}
hosts[i].JoinOverlay(ctx)
}
for i, host := range hosts {
neighbors, err := host.Neighbors(ctx)
require.NoError(t, err)
require.True(t, len(neighbors) > 0)
for _, neighbor := range neighbors {
require.NoError(
t,
host.Unicast(ctx, neighbor, "test", []byte(fmt.Sprintf("msg sent from %s", hosts[i].HostIdentity()))),
)
}
}
for i := 0; i < n; i++ {
require.NoError(t, hosts[i].Close())
}
}