github.com/bitfinexcom/bitfinex-api-go@v0.0.0-20210608095005-9e0b26f200fb/tests/integration/v2/mock_async.go (about) 1 package tests 2 3 import ( 4 "context" 5 "errors" 6 "fmt" 7 "log" 8 "sync" 9 "time" 10 11 "github.com/bitfinexcom/bitfinex-api-go/v2/websocket" 12 ) 13 14 // does not work for reconnect tests 15 type TestAsyncFactory struct { 16 Count int 17 Async websocket.Asynchronous 18 } 19 20 func (t *TestAsyncFactory) Create() websocket.Asynchronous { 21 t.Count += 1 22 // if first creation then send given async 23 if t.Count == 1 { 24 return t.Async 25 } 26 // otherwise create a new async for each new creation 27 return newTestAsync() 28 } 29 30 func newTestAsyncFactory(async websocket.Asynchronous) websocket.AsynchronousFactory { 31 return &TestAsyncFactory{Async: async, Count: 0} 32 } 33 34 type TestAsync struct { 35 done chan error 36 bridge chan []byte 37 connected bool 38 Sent []interface{} 39 mutex sync.Mutex 40 } 41 42 func (t *TestAsync) SentCount() int { 43 t.mutex.Lock() 44 defer t.mutex.Unlock() 45 return len(t.Sent) 46 } 47 48 func (t *TestAsync) waitForMessage(num int) error { 49 seconds := 4 50 loops := 20 51 delay := time.Duration(float64(time.Second) * float64(seconds) / float64(loops)) 52 for i := 0; i < loops; i++ { 53 t.mutex.Lock() 54 len := len(t.Sent) 55 t.mutex.Unlock() 56 if num+1 <= len { 57 return nil 58 } 59 time.Sleep(delay) 60 } 61 return fmt.Errorf("did not send a message in pos %d", num) 62 } 63 64 func (t *TestAsync) Connect() error { 65 t.connected = true 66 return nil 67 } 68 69 func (t *TestAsync) Send(ctx context.Context, msg interface{}) error { 70 if !t.connected { 71 return errors.New("must connect before sending") 72 } 73 t.mutex.Lock() 74 defer t.mutex.Unlock() 75 t.Sent = append(t.Sent, msg) 76 return nil 77 } 78 79 func (t *TestAsync) DumpSentMessages() { 80 for i, msg := range t.Sent { 81 log.Printf("%2d: %#v", i, msg) 82 } 83 } 84 85 func (t *TestAsync) Listen() <-chan []byte { 86 return t.bridge 87 } 88 89 func (t *TestAsync) Publish(raw string) { 90 t.bridge <- []byte(raw) 91 } 92 93 func (t *TestAsync) Close() { 94 close(t.bridge) 95 close(t.done) 96 } 97 98 func (t *TestAsync) Done() <-chan error { 99 return t.done 100 } 101 102 func newTestAsync() *TestAsync { 103 return &TestAsync{ 104 bridge: make(chan []byte), 105 connected: false, 106 Sent: make([]interface{}, 0), 107 done: make(chan error), 108 } 109 }