github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/cdc/sink/dmlsink/mq/dmlproducer/kafka_dml_mock_producer.go (about) 1 // Copyright 2022 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package dmlproducer 15 16 import ( 17 "context" 18 "fmt" 19 "sync" 20 21 "github.com/pingcap/tiflow/cdc/model" 22 "github.com/pingcap/tiflow/pkg/sink/codec/common" 23 "github.com/pingcap/tiflow/pkg/sink/kafka" 24 ) 25 26 var _ DMLProducer = (*MockDMLProducer)(nil) 27 28 // MockDMLProducer is a mock producer for test. 29 type MockDMLProducer struct { 30 mu sync.Mutex 31 events map[string][]*common.Message 32 33 asyncProducer kafka.AsyncProducer 34 } 35 36 // NewDMLMockProducer creates a mock producer. 37 func NewDMLMockProducer(_ context.Context, _ model.ChangeFeedID, asyncProducer kafka.AsyncProducer, 38 _ kafka.MetricsCollector, 39 _ chan error, 40 _ chan error, 41 ) DMLProducer { 42 return &MockDMLProducer{ 43 events: make(map[string][]*common.Message), 44 asyncProducer: asyncProducer, 45 } 46 } 47 48 // AsyncSendMessage appends a message to the mock producer. 49 func (m *MockDMLProducer) AsyncSendMessage(_ context.Context, topic string, 50 partition int32, message *common.Message, 51 ) error { 52 m.mu.Lock() 53 defer m.mu.Unlock() 54 55 key := fmt.Sprintf("%s-%d", topic, partition) 56 if _, ok := m.events[key]; !ok { 57 m.events[key] = make([]*common.Message, 0) 58 } 59 m.events[key] = append(m.events[key], message) 60 61 message.Callback() 62 63 return nil 64 } 65 66 // Close do nothing. 67 func (m *MockDMLProducer) Close() { 68 if m.asyncProducer != nil { 69 m.asyncProducer.Close() 70 } 71 } 72 73 // GetAllEvents returns the events received by the mock producer. 74 func (m *MockDMLProducer) GetAllEvents() []*common.Message { 75 m.mu.Lock() 76 defer m.mu.Unlock() 77 var events []*common.Message 78 for _, v := range m.events { 79 events = append(events, v...) 80 } 81 return events 82 } 83 84 // GetEvents returns the event filtered by the key. 85 func (m *MockDMLProducer) GetEvents(topic string, partition int32) []*common.Message { 86 m.mu.Lock() 87 defer m.mu.Unlock() 88 key := fmt.Sprintf("%s-%d", topic, partition) 89 return m.events[key] 90 }