forked from bitfinexcom/bitfinex-api-go
/
mock_async.go
109 lines (93 loc) · 2.04 KB
/
mock_async.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
104
105
106
107
108
109
package tests
import (
"context"
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/CapTec-Analytics/bitfinex-api-go/v2/websocket"
)
// does not work for reconnect tests
type TestAsyncFactory struct {
Count int
Async websocket.Asynchronous
}
func (t *TestAsyncFactory) Create() websocket.Asynchronous {
t.Count += 1
// if first creation then send given async
if t.Count == 1 {
return t.Async
}
// otherwise create a new async for each new creation
return newTestAsync()
}
func newTestAsyncFactory(async websocket.Asynchronous) websocket.AsynchronousFactory {
return &TestAsyncFactory{Async: async, Count: 0}
}
type TestAsync struct {
done chan error
bridge chan []byte
connected bool
Sent []interface{}
mutex sync.Mutex
}
func (t *TestAsync) SentCount() int {
t.mutex.Lock()
defer t.mutex.Unlock()
return len(t.Sent)
}
func (t *TestAsync) waitForMessage(num int) error {
seconds := 4
loops := 20
delay := time.Duration(float64(time.Second) * float64(seconds) / float64(loops))
for i := 0; i < loops; i++ {
t.mutex.Lock()
len := len(t.Sent)
t.mutex.Unlock()
if num+1 <= len {
return nil
}
time.Sleep(delay)
}
return fmt.Errorf("did not send a message in pos %d", num)
}
func (t *TestAsync) Connect() error {
t.connected = true
return nil
}
func (t *TestAsync) Send(ctx context.Context, msg interface{}) error {
if !t.connected {
return errors.New("must connect before sending")
}
t.mutex.Lock()
defer t.mutex.Unlock()
t.Sent = append(t.Sent, msg)
return nil
}
func (t *TestAsync) DumpSentMessages() {
for i, msg := range t.Sent {
log.Printf("%2d: %#v", i, msg)
}
}
func (t *TestAsync) Listen() <-chan []byte {
return t.bridge
}
func (t *TestAsync) Publish(raw string) {
t.bridge <- []byte(raw)
}
func (t *TestAsync) Close() {
close(t.bridge)
close(t.done)
}
func (t *TestAsync) Done() <-chan error {
return t.done
}
func newTestAsync() *TestAsync {
return &TestAsync{
bridge: make(chan []byte),
connected: false,
Sent: make([]interface{}, 0),
done: make(chan error),
}
}