forked from confluentinc/confluent-kafka-go
/
consumer_test.go
431 lines (369 loc) · 10.9 KB
/
consumer_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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package kafka
/**
* Copyright 2016 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import (
"fmt"
"os"
"reflect"
"sort"
"strings"
"testing"
"time"
)
// TestConsumerAPIs dry-tests most Consumer APIs, no broker is needed.
func TestConsumerAPIs(t *testing.T) {
c, err := NewConsumer(&ConfigMap{})
if err == nil {
t.Fatalf("Expected NewConsumer() to fail without group.id")
}
c, err = NewConsumer(&ConfigMap{
"group.id": "gotest",
"socket.timeout.ms": 10,
"session.timeout.ms": 10,
"enable.auto.offset.store": false, // permit StoreOffsets()
})
if err != nil {
t.Fatalf("%s", err)
}
t.Logf("Consumer %s", c)
err = c.Subscribe("gotest", nil)
if err != nil {
t.Errorf("Subscribe failed: %s", err)
}
err = c.SubscribeTopics([]string{"gotest1", "gotest2"},
func(my_c *Consumer, ev Event) error {
t.Logf("%s", ev)
return nil
})
if err != nil {
t.Errorf("SubscribeTopics failed: %s", err)
}
_, err = c.Commit()
if err != nil && err.(Error).Code() != ErrNoOffset {
t.Errorf("Commit() failed: %s", err)
}
err = c.Unsubscribe()
if err != nil {
t.Errorf("Unsubscribe failed: %s", err)
}
topic := "gotest"
stored, err := c.StoreOffsets([]TopicPartition{{Topic: &topic, Partition: 0, Offset: 1}})
if err != nil && err.(Error).Code() != ErrUnknownPartition {
t.Errorf("StoreOffsets() failed: %s", err)
toppar := stored[0]
if toppar.Error != nil && toppar.Error.(Error).Code() == ErrUnknownPartition {
t.Errorf("StoreOffsets() TopicPartition error: %s", toppar.Error)
}
}
var empty []TopicPartition
stored, err = c.StoreOffsets(empty)
if err != nil {
t.Errorf("StoreOffsets(empty) failed: %s", err)
}
// test StoreMessage doesn't fail either
stored, err = c.StoreMessage(&Message{TopicPartition: TopicPartition{Topic: &topic, Partition: 0, Offset: 1}})
if err != nil && err.(Error).Code() != ErrUnknownPartition {
t.Errorf("StoreMessage() failed: %s", err)
toppar := stored[0]
if toppar.Error != nil && toppar.Error.(Error).Code() == ErrUnknownPartition {
t.Errorf("StoreMessage() TopicPartition error: %s", toppar.Error)
}
}
topic1 := "gotest1"
topic2 := "gotest2"
err = c.Assign([]TopicPartition{{Topic: &topic1, Partition: 2},
{Topic: &topic2, Partition: 1}})
if err != nil {
t.Errorf("Assign failed: %s", err)
}
err = c.Seek(TopicPartition{Topic: &topic1, Partition: 2, Offset: -1}, 1000)
if err != nil {
t.Errorf("Seek failed: %s", err)
}
// Pause & Resume
err = c.Pause([]TopicPartition{{Topic: &topic1, Partition: 2},
{Topic: &topic2, Partition: 1}})
if err != nil {
t.Errorf("Pause failed: %s", err)
}
err = c.Resume([]TopicPartition{{Topic: &topic1, Partition: 2},
{Topic: &topic2, Partition: 1}})
if err != nil {
t.Errorf("Resume failed: %s", err)
}
err = c.Unassign()
if err != nil {
t.Errorf("Unassign failed: %s", err)
}
// Incremental Assign & Unassign
err = c.IncrementalAssign([]TopicPartition{
{Topic: &topic1, Partition: 9, Offset: 1},
{Topic: &topic2, Partition: 40, Offset: OffsetEnd},
{Topic: &topic1, Partition: 10, Offset: OffsetInvalid},
{Topic: &topic2, Partition: 30},
})
if err != nil {
t.Errorf("IncrementalAssign failed: %s", err)
}
err = c.IncrementalUnassign([]TopicPartition{
{Topic: &topic2, Partition: 30},
{Topic: &topic2, Partition: 40},
{Topic: &topic1, Partition: 10},
})
if err != nil {
t.Errorf("IncrementalUnassign failed: %s", err)
}
assignment, err := c.Assignment()
if err != nil {
t.Errorf("Assignment (after incremental) failed: %s", err)
}
t.Logf("(Incremental) Assignment: %s\n", assignment)
if len(assignment) != 1 ||
*assignment[0].Topic != topic1 ||
assignment[0].Partition != 9 {
t.Errorf("(Incremental) Assignment mismatch: %v", assignment)
}
// ConsumerGroupMetadata
_, err = c.GetConsumerGroupMetadata()
if err != nil {
t.Errorf("Expected valid ConsumerGroupMetadata: %v", err)
}
_, err = NewTestConsumerGroupMetadata("mygroup")
if err != nil {
t.Errorf("Expected valid ConsumerGroupMetadata: %v", err)
}
topic = "mytopic"
// OffsetsForTimes
offsets, err := c.OffsetsForTimes([]TopicPartition{{Topic: &topic, Offset: 12345}}, 100)
t.Logf("OffsetsForTimes() returned Offsets %s and error %s\n", offsets, err)
if err == nil {
t.Errorf("OffsetsForTimes() should have failed\n")
}
if offsets != nil {
t.Errorf("OffsetsForTimes() failed but returned non-nil Offsets: %s\n", offsets)
}
// Position
offsets, err = c.Position([]TopicPartition{
{Topic: &topic, Partition: 10},
{Topic: &topic, Partition: 5},
})
t.Logf("Position() returned Offsets %s and error %v\n", offsets, err)
if err != nil {
t.Errorf("Position() should not have failed\n")
}
if offsets == nil {
t.Errorf("Position() should not have returned nil\n")
}
// Committed
offsets, err = c.Committed([]TopicPartition{{Topic: &topic, Partition: 5}}, 10)
t.Logf("Committed() returned Offsets %s and error %s\n", offsets, err)
if err == nil {
t.Errorf("Committed() should have failed\n")
}
if offsets != nil {
t.Errorf("Committed() failed but returned non-nil Offsets: %s\n", offsets)
}
err = c.Close()
if err != nil {
t.Errorf("Close failed: %s", err)
}
}
func TestConsumerSubscription(t *testing.T) {
c, err := NewConsumer(&ConfigMap{"group.id": "gotest"})
if err != nil {
t.Fatalf("%s", err)
}
topics := []string{"gotest1", "gotest2", "gotest3"}
sort.Strings(topics)
err = c.SubscribeTopics(topics, nil)
if err != nil {
t.Fatalf("SubscribeTopics failed: %s", err)
}
subscription, err := c.Subscription()
if err != nil {
t.Fatalf("Subscription() failed: %s", err)
}
sort.Strings(subscription)
t.Logf("Compare Subscription %v to original list of topics %v\n",
subscription, topics)
r := reflect.DeepEqual(topics, subscription)
if r != true {
t.Fatalf("Subscription() %v does not match original topics %v",
subscription, topics)
}
c.Close()
}
func TestConsumerAssignment(t *testing.T) {
c, err := NewConsumer(&ConfigMap{"group.id": "gotest"})
if err != nil {
t.Fatalf("%s", err)
}
topic0 := "topic0"
topic1 := "topic1"
partitions := TopicPartitions{
{Topic: &topic1, Partition: 1},
{Topic: &topic1, Partition: 3},
{Topic: &topic0, Partition: 2}}
sort.Sort(partitions)
err = c.Assign(partitions)
if err != nil {
t.Fatalf("Assign failed: %s", err)
}
assignment, err := c.Assignment()
if err != nil {
t.Fatalf("Assignment() failed: %s", err)
}
sort.Sort(TopicPartitions(assignment))
t.Logf("Compare Assignment %v to original list of partitions %v\n",
assignment, partitions)
// Use Logf instead of Errorf for timeout-checking errors on CI builds
// since CI environments are unreliable timing-wise.
tmoutFunc := t.Errorf
_, onCi := os.LookupEnv("CI")
if onCi {
tmoutFunc = t.Logf
}
// Test ReadMessage()
for _, tmout := range []time.Duration{0, 200 * time.Millisecond} {
start := time.Now()
m, err := c.ReadMessage(tmout)
duration := time.Since(start)
t.Logf("ReadMessage(%v) ret %v and %v in %v", tmout, m, err, duration)
if m != nil || err == nil {
t.Errorf("Expected ReadMessage to fail: %v, %v", m, err)
}
if err.(Error).Code() != ErrTimedOut {
t.Errorf("Expected ReadMessage to fail with ErrTimedOut, not %v", err)
}
if tmout == 0 {
if duration.Seconds() > 0.1 {
tmoutFunc("Expected ReadMessage(%v) to fail after max 100ms, not %v", tmout, duration)
}
} else if tmout > 0 {
if duration.Seconds() < tmout.Seconds()*0.75 || duration.Seconds() > tmout.Seconds()*1.25 {
tmoutFunc("Expected ReadMessage() to fail after %v -+25%%, not %v", tmout, duration)
}
}
}
// reflect.DeepEqual() can't be used since TopicPartition.Topic
// is a pointer to a string rather than a string and the pointer
// will differ between partitions and assignment.
// Instead do a simple stringification + string compare.
if fmt.Sprintf("%v", assignment) != fmt.Sprintf("%v", partitions) {
t.Fatalf("Assignment() %v does not match original partitions %v",
assignment, partitions)
}
c.Close()
}
func TestConsumerOAuthBearerConfig(t *testing.T) {
myOAuthConfig := "scope=myscope principal=gotest"
c, err := NewConsumer(&ConfigMap{
"group.id": "test",
"security.protocol": "SASL_PLAINTEXT",
"go.events.channel.enable": true,
"sasl.mechanisms": "OAUTHBEARER",
"sasl.oauthbearer.config": myOAuthConfig,
})
if err != nil {
t.Fatalf("NewConsumer failed: %s", err)
}
// Wait for initial OAuthBearerTokenRefresh and check
// that its Config string is identical to myOAuthConfig
for {
ev := <-c.Events()
oatr, ok := ev.(OAuthBearerTokenRefresh)
if !ok {
continue
}
t.Logf("Got %s with Config \"%s\"", oatr, oatr.Config)
if oatr.Config != myOAuthConfig {
t.Fatalf("%s: Expected .Config to be %s, not %s",
oatr, myOAuthConfig, oatr.Config)
}
// Verify that we can set a token
err = c.SetOAuthBearerToken(OAuthBearerToken{
TokenValue: "aaaa",
Expiration: time.Now().Add(time.Second * time.Duration(60)),
Principal: "gotest",
})
if err != nil {
t.Fatalf("Failed to set token: %s", err)
}
// Verify that we can set a token refresh failure
err = c.SetOAuthBearerTokenFailure("A token failure test")
if err != nil {
t.Fatalf("Failed to set token failure: %s", err)
}
break
}
c.Close()
}
func TestConsumerLog(t *testing.T) {
logsChan := make(chan LogEvent, 1000)
c, err := NewConsumer(&ConfigMap{
"debug": "all",
"go.logs.channel.enable": true,
"go.logs.channel": logsChan,
"group.id": "gotest"})
if err != nil {
t.Fatalf("%s", err)
}
if c.Logs() != logsChan {
t.Fatalf("Expected c.Logs() %v == logsChan %v", c.Logs(), logsChan)
}
expectedLogs := map[struct {
tag string
message string
}]bool{
{"MEMBERID", "gotest"}: false,
{"CGRPSTATE", "gotest"}: false,
{"CGRPQUERY", "gotest"}: false,
}
go func() {
for {
select {
case log, ok := <-logsChan:
if !ok {
return
}
for expectedLog, found := range expectedLogs {
if found {
continue
}
if log.Tag != expectedLog.tag {
continue
}
if strings.Contains(log.Message, expectedLog.message) {
expectedLogs[expectedLog] = true
}
}
}
}
}()
<-time.After(time.Second * 3)
if err := c.Close(); err != nil {
t.Fatal("Failed to close consumer.")
}
for expectedLog, found := range expectedLogs {
if !found {
t.Errorf(
"Expected to find log with tag `%s' and message containing `%s',"+
" but didn't find any.",
expectedLog.tag,
expectedLog.message)
}
}
}