go.opentelemetry.io/contrib/instrumentation/github.com/Shopify/sarama/otelsarama@v0.43.0/consumer_test.go (about) 1 // Copyright The OpenTelemetry Authors 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 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package otelsarama 16 17 import ( 18 "testing" 19 20 "github.com/Shopify/sarama" 21 "github.com/Shopify/sarama/mocks" 22 "github.com/stretchr/testify/assert" 23 "github.com/stretchr/testify/require" 24 25 "go.opentelemetry.io/otel/trace" 26 ) 27 28 const ( 29 topic = "test-topic" 30 ) 31 32 func TestConsumerConsumePartitionWithError(t *testing.T) { 33 // Mock partition consumer controller 34 mockConsumer := mocks.NewConsumer(t, sarama.NewConfig()) 35 mockConsumer.ExpectConsumePartition(topic, 0, 0) 36 37 consumer := WrapConsumer(mockConsumer) 38 _, err := consumer.ConsumePartition(topic, 0, 0) 39 assert.NoError(t, err) 40 // Consume twice 41 _, err = consumer.ConsumePartition(topic, 0, 0) 42 assert.Error(t, err) 43 } 44 45 func BenchmarkWrapPartitionConsumer(b *testing.B) { 46 // Mock provider 47 provider := trace.NewNoopTracerProvider() 48 49 mockPartitionConsumer, partitionConsumer := createMockPartitionConsumer(b) 50 51 partitionConsumer = WrapPartitionConsumer(partitionConsumer, WithTracerProvider(provider)) 52 message := sarama.ConsumerMessage{Key: []byte("foo")} 53 54 b.ReportAllocs() 55 b.ResetTimer() 56 57 for i := 0; i < b.N; i++ { 58 mockPartitionConsumer.YieldMessage(&message) 59 <-partitionConsumer.Messages() 60 } 61 } 62 63 func BenchmarkMockPartitionConsumer(b *testing.B) { 64 mockPartitionConsumer, partitionConsumer := createMockPartitionConsumer(b) 65 66 message := sarama.ConsumerMessage{Key: []byte("foo")} 67 68 b.ReportAllocs() 69 b.ResetTimer() 70 71 for i := 0; i < b.N; i++ { 72 mockPartitionConsumer.YieldMessage(&message) 73 <-partitionConsumer.Messages() 74 } 75 } 76 77 func createMockPartitionConsumer(b *testing.B) (*mocks.PartitionConsumer, sarama.PartitionConsumer) { 78 // Mock partition consumer controller 79 consumer := mocks.NewConsumer(b, sarama.NewConfig()) 80 mockPartitionConsumer := consumer.ExpectConsumePartition(topic, 0, 0) 81 82 // Create partition consumer 83 partitionConsumer, err := consumer.ConsumePartition(topic, 0, 0) 84 require.NoError(b, err) 85 return mockPartitionConsumer, partitionConsumer 86 }