-
Notifications
You must be signed in to change notification settings - Fork 8
/
query_client_test.go
391 lines (333 loc) · 12.6 KB
/
query_client_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package events_test
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pokt-network/poktroll/pkg/client/events"
"github.com/pokt-network/poktroll/pkg/client/events/websocket"
"github.com/pokt-network/poktroll/pkg/either"
"github.com/pokt-network/poktroll/pkg/observable"
"github.com/pokt-network/poktroll/testutil/mockclient"
"github.com/pokt-network/poktroll/testutil/testchannel"
"github.com/pokt-network/poktroll/testutil/testclient/testeventsquery"
"github.com/pokt-network/poktroll/testutil/testerrors"
)
func TestEventsQueryClient_Subscribe_Succeeds(t *testing.T) {
var (
readObserverEventsTimeout = time.Second
queryCounter int
queryLimit = 5
connMocks = make([]*mockclient.MockConnection, queryLimit)
ctrl = gomock.NewController(t)
rootCtx, cancelRoot = context.WithCancel(context.Background())
)
t.Cleanup(cancelRoot)
dialerMock := mockclient.NewMockDialer(ctrl)
// `Dialer#DialContext()` should be called once for each subscription (subtest).
dialerMock.EXPECT().DialContext(gomock.Any(), gomock.Any()).
DoAndReturn(func(_ context.Context, _ string) (*mockclient.MockConnection, error) {
// Return the connection mock for the subscription with the given query.
// It should've been created in the respective test function.
connMock := connMocks[queryCounter]
queryCounter++
return connMock, nil
}).
Times(queryLimit)
// Set up events query client.
dialerOpt := events.WithDialer(dialerMock)
queryClient := events.NewEventsQueryClient("", dialerOpt)
t.Cleanup(queryClient.Close)
for queryIdx := 0; queryIdx < queryLimit; queryIdx++ {
t.Run(testQuery(queryIdx), func(t *testing.T) {
var (
// ReadEventCounter is the number of eventsBytesAndConns which have been
// received from the connection since the subtest started.
readEventCounter int
// HandleEventsLimit is the total number of eventsBytesAndConns to send and
// receive through the query client's eventsBytes for this subtest.
handleEventsLimit = 250
// delayFirstEvent runs once (per test case) to delay the first event
// published by the mocked connection's Receive method to give the test
// ample time to subscribe to the events bytes observable before it
// starts receiving events, otherwise they will be dropped.
delayFirstEvent sync.Once
connClosed atomic.Bool
queryCtx, cancelQuery = context.WithCancel(rootCtx)
)
// Must set up connection mock before calling EventsBytes()
connMock := mockclient.NewMockConnection(ctrl)
// `Connection#Close()` should be called once for each subscription.
connMock.EXPECT().Close().
DoAndReturn(func() error {
// Simulate closing the connection.
connClosed.CompareAndSwap(false, true)
return nil
}).
Times(1)
// `Connection#Send()` should be called once for each subscription.
connMock.EXPECT().Send(gomock.Any()).
Return(nil).
Times(1)
// `Connection#Receive()` should be called once for each message plus
// one as it blocks in the loop which calls msgHandler after reading the
// last message.
connMock.EXPECT().Receive().
DoAndReturn(func() (any, error) {
delayFirstEvent.Do(func() { time.Sleep(50 * time.Millisecond) })
// Simulate ErrConnClosed if connection is isClosed.
if connClosed.Load() {
return nil, events.ErrEventsConnClosed
}
event := testEvent(int32(readEventCounter))
readEventCounter++
// Simulate IO delay between sequential events.
time.Sleep(10 * time.Microsecond)
return event, nil
}).
MinTimes(handleEventsLimit)
connMocks[queryIdx] = connMock
// Set up events bytes observer for this query.
eventObservable, err := queryClient.EventsBytes(queryCtx, testQuery(queryIdx))
require.NoError(t, err)
eventObserver := eventObservable.Subscribe(queryCtx)
onLimit := func() {
// Cancelling the context should close the connection.
cancelQuery()
// Closing the connection happens asynchronously, so we need to wait a bit
// for the connection to close to satisfy the connection mock expectations.
time.Sleep(10 * time.Millisecond)
// Drain the observer channel and assert that it's isClosed.
err := testchannel.DrainChannel(eventObserver.Ch())
require.NoError(t, err, "eventsBytesAndConns observer channel should be isClosed")
}
// Concurrently consume eventsBytesAndConns from the observer channel.
behavesLikeEitherObserver(
t, eventObserver,
handleEventsLimit,
events.ErrEventsConnClosed,
readObserverEventsTimeout,
onLimit,
)
})
}
}
func TestEventsQueryClient_Subscribe_Close(t *testing.T) {
var (
firstEventDelay = 50 * time.Millisecond
readAllEventsTimeout = 50*time.Millisecond + firstEventDelay
handleEventsLimit = 10
readEventCounter int
// delayFirstEvent runs once (per test case) to delay the first event
// published by the mocked connection's Receive method to give the test
// ample time to subscribe to the events bytes observable before it
// starts receiving events, otherwise they will be dropped.
delayFirstEvent sync.Once
connClosed atomic.Bool
ctx = context.Background()
)
connMock, dialerMock := testeventsquery.NewOneTimeMockConnAndDialer(t)
connMock.EXPECT().Send(gomock.Any()).Return(nil).
Times(1)
connMock.EXPECT().Receive().
DoAndReturn(func() (any, error) {
delayFirstEvent.Do(func() { time.Sleep(firstEventDelay) })
if connClosed.Load() {
return nil, events.ErrEventsConnClosed
}
event := testEvent(int32(readEventCounter))
readEventCounter++
// Simulate IO delay between sequential events.
time.Sleep(10 * time.Microsecond)
return event, nil
}).
MinTimes(handleEventsLimit)
dialerOpt := events.WithDialer(dialerMock)
queryClient := events.NewEventsQueryClient("", dialerOpt)
// set up query observer
eventsObservable, err := queryClient.EventsBytes(ctx, testQuery(0))
require.NoError(t, err)
eventsObserver := eventsObservable.Subscribe(ctx)
onLimit := func() {
// cancelling the context should close the connection
queryClient.Close()
// closing the connection happens asynchronously, so we need to wait a bit
// for the connection to close to satisfy the connection mock expectations.
time.Sleep(10 * time.Millisecond)
}
// concurrently consume eventsBytesAndConns from the observer channel
behavesLikeEitherObserver(
t, eventsObserver,
handleEventsLimit,
events.ErrEventsConnClosed,
readAllEventsTimeout,
onLimit,
)
}
func TestEventsQueryClient_Subscribe_DialError(t *testing.T) {
ctx := context.Background()
eitherErrDial := either.Error[*mockclient.MockConnection](events.ErrEventsDial)
dialerMock := testeventsquery.NewOneTimeMockDialer(t, eitherErrDial)
dialerOpt := events.WithDialer(dialerMock)
queryClient := events.NewEventsQueryClient("", dialerOpt)
eventsObservable, err := queryClient.EventsBytes(ctx, testQuery(0))
require.Nil(t, eventsObservable)
require.True(t, errors.Is(err, events.ErrEventsDial))
}
func TestEventsQueryClient_Subscribe_RequestError(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
connMock, dialerMock := testeventsquery.NewOneTimeMockConnAndDialer(t)
connMock.EXPECT().Send(gomock.Any()).
Return(fmt.Errorf("mock send error")).
Times(1)
dialerOpt := events.WithDialer(dialerMock)
queryClient := events.NewEventsQueryClient("url_ignored", dialerOpt)
eventsObservable, err := queryClient.EventsBytes(ctx, testQuery(0))
require.Nil(t, eventsObservable)
require.True(t, errors.Is(err, events.ErrEventsSubscribe))
// cancelling the context should close the connection
cancel()
// closing the connection happens asynchronously, so we need to wait a bit
// for the connection to close to satisfy the connection mock expectations.
time.Sleep(10 * time.Millisecond)
}
// TODO_INVESTIGATE: why this test fails?
func TestEventsQueryClient_Subscribe_ReceiveError(t *testing.T) {
t.Skip("TODO_INVESTIGATE: why this test fails")
var (
handleEventLimit = 10
readAllEventsTimeout = 100 * time.Millisecond
readEventCounter int
)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
connMock, dialerMock := testeventsquery.NewOneTimeMockConnAndDialer(t)
connMock.EXPECT().Send(gomock.Any()).Return(nil).
Times(1)
connMock.EXPECT().Receive().
DoAndReturn(func() (any, error) {
if readEventCounter >= handleEventLimit {
return nil, websocket.ErrEventsWebsocketReceive
}
event := testEvent(int32(readEventCounter))
readEventCounter++
time.Sleep(10 * time.Microsecond)
return event, nil
}).
MinTimes(handleEventLimit)
dialerOpt := events.WithDialer(dialerMock)
queryClient := events.NewEventsQueryClient("", dialerOpt)
// set up query observer
eventsObservable, err := queryClient.EventsBytes(ctx, testQuery(0))
require.NoError(t, err)
eventsObserver := eventsObservable.Subscribe(ctx)
// concurrently consume eventsBytesAndConns from the observer channel
behavesLikeEitherObserver(
t, eventsObserver,
handleEventLimit,
websocket.ErrEventsWebsocketReceive,
readAllEventsTimeout,
nil,
)
}
// TODO_TECHDEBT: add test coverage for multiple observers with distinct and overlapping queries
func TestEventsQueryClient_EventsBytes_MultipleObservers(t *testing.T) {
t.Skip("TODO_TECHDEBT: add test coverage for multiple observers with distinct and overlapping queries")
}
// behavesLikeEitherObserver asserts that the given observer behaves like an
// observable.Observer[either.Either[V]] by consuming notifications from the
// observer channel and asserting that they match the expected notification.
// It also asserts that the observer channel is isClosed after the expected number
// of eventsBytes have been received.
// If onLimit is not nil, it is called when the expected number of events have
// been received.
// Otherwise, the observer channel is drained and the test fails if it is not
// isClosed after the timeout duration.
func behavesLikeEitherObserver[V any](
t *testing.T,
observer observable.Observer[either.Either[V]],
notificationsLimit int,
expectedErr error,
timeout time.Duration,
onLimit func(),
) {
t.Helper()
var (
// eventsCounter is the number of events which have been received from the
// eventsBytes since this function was called.
eventsCounter int32
// errCh is used to signal when the test completes and/or produces an error
errCh = make(chan error, 1)
)
go func() {
for eitherEvent := range observer.Ch() {
event, err := eitherEvent.ValueOrError()
if err != nil {
switch expectedErr {
case nil:
if !assert.NoError(t, err) {
errCh <- testerrors.ErrAsync
return
}
default:
if !assert.ErrorIs(t, err, expectedErr) {
errCh <- testerrors.ErrAsync
return
}
}
}
currentEventCount := atomic.LoadInt32(&eventsCounter)
if int(currentEventCount) >= notificationsLimit {
// signal completion
errCh <- nil
return
}
// TODO_IMPROVE: to make this test helper more generic, it should accept
// a generic function which generates the expected event for the given
// index. Perhaps this function could use an either type which could be
// used to consolidate the expectedErr and expectedEvent arguments.
expectedEvent := testEvent(currentEventCount)
// Require calls t.Fatal internally, which shouldn't happen in a
// goroutine other than the test function's.
// Use assert instead and stop the test by sending on errCh and
// returning.
if !assert.Equal(t, expectedEvent, event) {
errCh <- testerrors.ErrAsync
return
}
atomic.AddInt32(&eventsCounter, 1)
// unbounded consumption here can result in the condition below never
// being met due to the connection being isClosed before the "last" event
// is received
time.Sleep(10 * time.Microsecond)
}
}()
select {
case err := <-errCh:
require.NoError(t, err)
require.Equal(t, notificationsLimit, int(atomic.LoadInt32(&eventsCounter)))
time.Sleep(10 * time.Millisecond)
if onLimit != nil {
onLimit()
}
case <-time.After(timeout):
t.Fatalf(
"timed out waiting for next event; expected %d events, got %d",
notificationsLimit, atomic.LoadInt32(&eventsCounter),
)
}
err := testchannel.DrainChannel(observer.Ch())
require.NoError(t, err, "eventsBytesAndConns observer should be isClosed")
}
func testEvent(idx int32) []byte {
return []byte(fmt.Sprintf("message_%d", idx))
}
func testQuery(idx int) string {
return fmt.Sprintf("query_%d", idx)
}