-
Notifications
You must be signed in to change notification settings - Fork 215
/
sender_test.go
107 lines (86 loc) · 2.35 KB
/
sender_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
/*
Copyright 2021 The CloudEvents Authors
SPDX-License-Identifier: Apache-2.0
*/
package kafka_sarama
import (
"context"
"sync"
"testing"
"github.com/Shopify/sarama"
"github.com/stretchr/testify/require"
"github.com/cloudevents/sdk-go/v2/test"
)
type syncProducerMock struct {
lock sync.Mutex
sent []*sarama.ProducerMessage
isTransactional bool
status sarama.ProducerTxnStatusFlag
}
func (s *syncProducerMock) SendMessage(msg *sarama.ProducerMessage) (partition int32, offset int64, err error) {
s.lock.Lock()
defer s.lock.Unlock()
s.sent = append(s.sent, msg)
return 0, int64(len(s.sent) - 1), err
}
func (s *syncProducerMock) SendMessages(msgs []*sarama.ProducerMessage) error {
s.lock.Lock()
defer s.lock.Unlock()
s.sent = append(s.sent, msgs...)
return nil
}
func (s *syncProducerMock) Close() error {
s.lock.Lock()
defer s.lock.Unlock()
return nil
}
func (s *syncProducerMock) IsTransactional() bool {
s.lock.Lock()
defer s.lock.Unlock()
return s.isTransactional
}
func (s *syncProducerMock) BeginTxn() error {
s.lock.Lock()
defer s.lock.Unlock()
s.status = sarama.ProducerTxnFlagInTransaction
return nil
}
func (s *syncProducerMock) CommitTxn() error {
s.lock.Lock()
defer s.lock.Unlock()
s.status = sarama.ProducerTxnFlagReady
return nil
}
func (s *syncProducerMock) AbortTxn() error {
s.lock.Lock()
defer s.lock.Unlock()
s.status = sarama.ProducerTxnFlagReady
return nil
}
func (s *syncProducerMock) TxnStatus() sarama.ProducerTxnStatusFlag {
s.lock.Lock()
defer s.lock.Unlock()
return s.status
}
func (s *syncProducerMock) AddOffsetsToTxn(offsets map[string][]*sarama.PartitionOffsetMetadata, groupId string) error {
return nil
}
func (s *syncProducerMock) AddMessageToTxn(msg *sarama.ConsumerMessage, groupId string, metadata *string) error {
return nil
}
func TestSenderWithKey(t *testing.T) {
syncProducerMock := &syncProducerMock{
isTransactional: true,
status: sarama.ProducerTxnFlagReady,
}
topic := "aaa"
sender := &Sender{topic: topic, syncProducer: syncProducerMock}
require.NoError(t, sender.Send(
WithMessageKey(context.TODO(), sarama.StringEncoder("hello")),
test.FullMessage(),
))
require.Len(t, syncProducerMock.sent, 1)
kafkaMsg := syncProducerMock.sent[0]
require.Equal(t, kafkaMsg.Topic, topic)
require.Equal(t, kafkaMsg.Key, sarama.StringEncoder("hello"))
}