-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux_test.go
99 lines (78 loc) · 2.08 KB
/
mux_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
package genrpc_test
import (
"testing"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/protocol"
genrpc "github.com/plexsysio/go-libp2p-genrpc"
)
func TestMux(t *testing.T) {
t.Parallel()
t.Run("new", func(t *testing.T) {
t.Parallel()
_ = genrpc.New("test")
})
t.Run("new with version", func(t *testing.T) {
t.Parallel()
t.Run("invalid", func(t *testing.T) {
t.Parallel()
_, err := genrpc.NewWithVersion("test", "testversion")
if err == nil {
t.Fatalf("expected invalid version error")
}
})
t.Run("valid", func(t *testing.T) {
t.Parallel()
_, err := genrpc.NewWithVersion("test", "0.0.1")
if err != nil {
t.Fatalf("unexpected error: got %v", err)
}
})
})
t.Run("handle and register", func(t *testing.T) {
t.Parallel()
m, err := genrpc.NewWithVersion("test", "1.0.0")
if err != nil {
t.Fatal(err)
}
m.Handle("a", func(s network.Stream) {})
host := &testHost{}
genrpc.Register(host, m)
hdlr, found := host.handler("test/1.0.0/a")
if !found {
t.Fatal("handler not found")
}
if !hdlr.matcher(protocol.ID("test/1.0.0/a")) {
t.Fatal("unexpected matcher failure")
}
if !hdlr.matcher(protocol.ID("test/1.0.1/a")) {
t.Fatal("unexpected matcher failure")
}
if hdlr.matcher(protocol.ID("test/2.0.0/a")) {
t.Fatal("expected matcher failure")
}
if hdlr.matcher(protocol.ID("test")) {
t.Fatal("expected matcher failure")
}
if hdlr.matcher(protocol.ID("test/100/a")) {
t.Fatal("expected matcher failure")
}
})
}
type testHandler struct {
matcher func(protocol.ID) bool
handler func(network.Stream)
}
type testHost struct {
handlers map[string]testHandler
}
func (t *testHost) SetStreamHandlerMatch(p protocol.ID, matcher func(check protocol.ID) bool, handler network.StreamHandler) {
if t.handlers == nil {
t.handlers = make(map[string]testHandler)
}
t.handlers[string(p)] = testHandler{matcher: matcher, handler: handler}
return
}
func (t *testHost) handler(path string) (testHandler, bool) {
testHandler, found := t.handlers[path]
return testHandler, found
}