forked from umbracle/ethgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubscribe_test.go
70 lines (57 loc) · 1.21 KB
/
subscribe_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
package jsonrpc
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/umbracle/ethgo"
"github.com/umbracle/ethgo/testutil"
)
func TestSubscribeNewHead(t *testing.T) {
testutil.MultiAddr(t, func(s *testutil.TestServer, addr string) {
if strings.HasPrefix(addr, "http") {
return
}
c, _ := NewClient(addr)
defer c.Close()
data := make(chan []byte)
cancel, err := c.Subscribe("newHeads", func(b []byte) {
data <- b
})
if err != nil {
t.Fatal(err)
}
var lastBlock *ethgo.Block
recv := func(ok bool) {
select {
case buf := <-data:
if !ok {
t.Fatal("unexpected value")
}
var block ethgo.Block
if err := block.UnmarshalJSON(buf); err != nil {
t.Fatal(err)
}
if lastBlock != nil {
if lastBlock.Number+1 != block.Number {
t.Fatalf("bad sequence %d %d", lastBlock.Number, block.Number)
}
}
lastBlock = &block
case <-time.After(1 * time.Second):
if ok {
t.Fatal("timeout for new head")
}
}
}
s.ProcessBlock()
recv(true)
s.ProcessBlock()
recv(true)
assert.NoError(t, cancel())
s.ProcessBlock()
recv(false)
// subscription already closed
assert.Error(t, cancel())
})
}