forked from segmentio/kafka-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader_test.go
309 lines (262 loc) · 6.74 KB
/
reader_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
package kafka
import (
"context"
"math/rand"
"strconv"
"sync"
"testing"
"time"
)
func TestReader(t *testing.T) {
t.Parallel()
tests := []struct {
scenario string
function func(*testing.T, context.Context, *Reader)
}{
{
scenario: "calling Read with a context that has been canceled returns an error",
function: testReaderReadCanceled,
},
{
scenario: "all messages of the stream are returned when calling ReadMessage repeatedly",
function: testReaderReadMessages,
},
{
scenario: "setting the offset to random values returns the expected messages when Read is called",
function: testReaderSetRandomOffset,
},
{
scenario: "calling Lag returns the lag of the last message read from kafka",
function: testReaderLag,
},
{
scenario: "calling ReadLag returns the current lag of a reader",
function: testReaderReadLag,
},
{
scenario: "calling Stats returns accurate stats about the reader",
function: testReaderStats,
},
}
for _, test := range tests {
testFunc := test.function
t.Run(test.scenario, func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
r := NewReader(ReaderConfig{
Brokers: []string{"localhost:9092"},
Topic: makeTopic(),
MinBytes: 1,
MaxBytes: 10e6,
MaxWait: 100 * time.Millisecond,
})
defer r.Close()
testFunc(t, ctx, r)
})
}
}
func testReaderReadCanceled(t *testing.T, ctx context.Context, r *Reader) {
ctx, cancel := context.WithCancel(ctx)
cancel()
if _, err := r.ReadMessage(ctx); err != context.Canceled {
t.Error(err)
}
}
func testReaderReadMessages(t *testing.T, ctx context.Context, r *Reader) {
const N = 1000
prepareReader(t, ctx, r, makeTestSequence(N)...)
var offset int64
for i := 0; i != N; i++ {
m, err := r.ReadMessage(ctx)
if err != nil {
t.Error("reading message at offset", offset, "failed:", err)
return
}
offset = m.Offset + 1
v, _ := strconv.Atoi(string(m.Value))
if v != i {
t.Error("message at index", i, "has wrong value:", v)
return
}
}
}
func testReaderSetRandomOffset(t *testing.T, ctx context.Context, r *Reader) {
const N = 10
prepareReader(t, ctx, r, makeTestSequence(N)...)
for i := 0; i != 2*N; i++ {
offset := rand.Intn(N)
r.SetOffset(int64(offset))
m, err := r.ReadMessage(ctx)
if err != nil {
t.Error("seeking to offset", offset, "failed:", err)
return
}
v, _ := strconv.Atoi(string(m.Value))
if v != offset {
t.Error("message at offset", offset, "has wrong value:", v)
return
}
}
}
func testReaderLag(t *testing.T, ctx context.Context, r *Reader) {
const N = 5
prepareReader(t, ctx, r, makeTestSequence(N)...)
if lag := r.Lag(); lag != 0 {
t.Errorf("the initial lag value is %d but was expected to be 0", lag)
}
for i := 0; i != N; i++ {
r.ReadMessage(ctx)
expect := int64(N - (i + 1))
if lag := r.Lag(); lag != expect {
t.Errorf("the lag value at offset %d is %d but was expected to be %d", i, lag, expect)
}
}
}
func testReaderReadLag(t *testing.T, ctx context.Context, r *Reader) {
const N = 5
prepareReader(t, ctx, r, makeTestSequence(N)...)
if lag, err := r.ReadLag(ctx); err != nil {
t.Error(err)
} else if lag != N {
t.Errorf("the initial lag value is %d but was expected to be %d", lag, N)
}
for i := 0; i != N; i++ {
r.ReadMessage(ctx)
expect := int64(N - (i + 1))
if lag, err := r.ReadLag(ctx); err != nil {
t.Error(err)
} else if lag != expect {
t.Errorf("the lag value at offset %d is %d but was expected to be %d", i, lag, expect)
}
}
}
func testReaderStats(t *testing.T, ctx context.Context, r *Reader) {
const N = 10
prepareReader(t, ctx, r, makeTestSequence(N)...)
var offset int64
var bytes int64
for i := 0; i != N; i++ {
m, err := r.ReadMessage(ctx)
if err != nil {
t.Error("reading message at offset", offset, "failed:", err)
return
}
offset = m.Offset + 1
bytes += int64(len(m.Key) + len(m.Value))
}
stats := r.Stats()
// First verify that metrics with unpredictable values are not zero.
if stats.DialTime == (DurationStats{}) {
t.Error("no dial time reported by reader stats")
}
if stats.ReadTime == (DurationStats{}) {
t.Error("no read time reported by reader stats")
}
if stats.WaitTime == (DurationStats{}) {
t.Error("no wait time reported by reader stats")
}
if len(stats.Topic) == 0 {
t.Error("empty topic in reader stats")
}
// Then compare all remaining metrics.
expect := ReaderStats{
Dials: 1,
Fetches: 1,
Messages: 10,
Bytes: 10,
Rebalances: 0,
Timeouts: 0,
Errors: 0,
DialTime: stats.DialTime,
ReadTime: stats.ReadTime,
WaitTime: stats.WaitTime,
FetchSize: SummaryStats{Avg: 10, Min: 10, Max: 10},
FetchBytes: SummaryStats{Avg: 10, Min: 10, Max: 10},
Offset: 10,
Lag: 0,
MinBytes: 1,
MaxBytes: 10000000,
MaxWait: 100 * time.Millisecond,
QueueLength: 0,
QueueCapacity: 100,
ClientID: "",
Topic: stats.Topic,
Partition: "0",
}
if stats != expect {
t.Error("bad stats:")
t.Log("expected:", expect)
t.Log("found: ", stats)
}
}
func makeTestSequence(n int) []Message {
msgs := make([]Message, n)
for i := 0; i != n; i++ {
msgs[i] = Message{
Value: []byte(strconv.Itoa(i)),
}
}
return msgs
}
func prepareReader(t *testing.T, ctx context.Context, r *Reader, msgs ...Message) {
var config = r.Config()
var conn *Conn
var err error
for {
if conn, err = DialLeader(ctx, "tcp", "localhost:9092", config.Topic, config.Partition); err == nil {
break
}
select {
case <-time.After(time.Second):
case <-ctx.Done():
t.Fatal(ctx.Err())
}
}
defer conn.Close()
if _, err := conn.WriteMessages(msgs...); err != nil {
t.Fatal(err)
}
}
var (
benchmarkReaderOnce sync.Once
benchmarkReaderTopic = makeTopic()
benchmarkReaderPayload = make([]byte, 16*1024)
)
func BenchmarkReader(b *testing.B) {
const broker = "localhost:9092"
ctx := context.Background()
benchmarkReaderOnce.Do(func() {
conn, err := DialLeader(ctx, "tcp", broker, benchmarkReaderTopic, 0)
if err != nil {
b.Fatal(err)
}
defer conn.Close()
msgs := make([]Message, 1000)
for i := range msgs {
msgs[i].Value = benchmarkReaderPayload
}
for i := 0; i != 10; i++ { // put 10K messages
if _, err := conn.WriteMessages(msgs...); err != nil {
b.Fatal(err)
}
}
b.ResetTimer()
})
r := NewReader(ReaderConfig{
Brokers: []string{broker},
Topic: benchmarkReaderTopic,
Partition: 0,
MinBytes: 1e3,
MaxBytes: 1e6,
MaxWait: 100 * time.Millisecond,
})
for i := 0; i != b.N; i++ {
if (i % 10000) == 0 {
r.SetOffset(0)
}
r.ReadMessage(ctx)
}
r.Close()
b.SetBytes(int64(len(benchmarkReaderPayload)))
}