-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathproducer_test.go
75 lines (60 loc) · 1.56 KB
/
producer_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
package gokaf
import (
"context"
"testing"
"time"
)
func TestProducerClose(t *testing.T) {
topicName := "testTopic"
topic := newTopic(context.Background(), mockLogger, topicName, 0)
producer := newProducer(topic, mockLogger)
// Test: Producer close
t.Run("ProducerClose", func(t *testing.T) {
producer.Stop()
// Wait for the producer to finish closing (WaitGroup counter to reach zero)
done := make(chan struct{})
go func() {
defer close(done)
producer.wg.Wait()
}()
select {
case <-done:
// The producer has finished closing
case <-time.After(time.Second):
t.Error("Timed out waiting for producer to close")
}
})
}
func TestProducerPublish(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
topicName := "testTopic"
topic := newTopic(ctx, mockLogger, topicName, 0)
producer := newProducer(topic, mockLogger)
// Use a channel to capture published messages
publishedMessages := make(chan interface{}, 3)
// Start a goroutine to simulate message consumption
go func() {
for msg := range producer.topic.channel.ch {
publishedMessages <- msg
}
}()
message := "testMessage"
// Publish message
err := producer.Publish(message)
if err != nil {
t.Errorf("Error publishing message1: %v", err)
}
producer.Stop()
producer.wg.Wait()
topic.close()
topic.wg.Wait()
select {
case receivedMsg := <-publishedMessages:
if receivedMsg != message {
t.Errorf("Expected message %v, got %v", message, receivedMsg)
}
case <-time.After(time.Second):
t.Error("Timeout waiting for message")
}
}