Tests: Umbau für einen Commit im Fehlerfall und Anpassung des Tests
[demos/kafka/training] / src / test / java / de / juplo / kafka / ApplicationTests.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRecord;
5 import org.apache.kafka.clients.consumer.KafkaConsumer;
6 import org.apache.kafka.clients.producer.KafkaProducer;
7 import org.apache.kafka.clients.producer.ProducerRecord;
8 import org.apache.kafka.common.TopicPartition;
9 import org.apache.kafka.common.errors.WakeupException;
10 import org.apache.kafka.common.serialization.BytesSerializer;
11 import org.apache.kafka.common.serialization.LongSerializer;
12 import org.apache.kafka.common.serialization.StringSerializer;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.MethodOrderer;
15 import org.junit.jupiter.api.Order;
16 import org.junit.jupiter.api.Test;
17 import org.junit.jupiter.api.TestMethodOrder;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
20 import org.springframework.boot.test.context.TestConfiguration;
21 import org.springframework.context.annotation.Bean;
22 import org.springframework.context.annotation.Import;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26
27 import java.util.*;
28 import java.util.concurrent.ExecutorService;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
34
35 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.ApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.assertThat;
38
39
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
42 @TestPropertySource(
43                 properties = {
44                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45                                 "consumer.topic=" + TOPIC })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
47 @Slf4j
48 class ApplicationTests
49 {
50         public static final String TOPIC = "FOO";
51         public static final int PARTITIONS = 10;
52
53
54         StringSerializer stringSerializer = new StringSerializer();
55         LongSerializer longSerializer = new LongSerializer();
56
57         @Autowired
58         KafkaProducer<String, Bytes> kafkaProducer;
59         @Autowired
60         KafkaConsumer<String, Long> kafkaConsumer;
61         @Autowired
62         ApplicationProperties properties;
63         @Autowired
64         ExecutorService executor;
65
66         Map<TopicPartition, Long> oldOffsets;
67         Map<TopicPartition, Long> newOffsets;
68
69
70         @Test
71         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
72         void commitsCurrentOffsetsOnSuccess()
73         {
74                 send100Messages(i ->  new Bytes(longSerializer.serialize(TOPIC, i)));
75
76                 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
77                 runEndlessConsumer(record ->
78                 {
79                         received.add(record);
80                         if (received.size() == 100)
81                                 throw new WakeupException();
82                 });
83
84                 checkSeenOffsetsForProgress();
85                 compareToCommitedOffsets(newOffsets);
86         }
87
88         @Test
89         @Order(2)
90         void commitsOffsetOfErrorForReprocessingOnError()
91         {
92                 send100Messages(counter ->
93                                 counter == 77
94                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
95                                                 : new Bytes(longSerializer.serialize(TOPIC, counter)));
96
97                 runEndlessConsumer((record) -> {});
98
99                 checkSeenOffsetsForProgress();
100                 compareToCommitedOffsets(newOffsets);
101         }
102
103
104         void send100Messages(Function<Long, Bytes> messageGenerator)
105         {
106                 long i = 0;
107
108                 for (int partition = 0; partition < 10; partition++)
109                 {
110                         for (int key = 0; key < 10; key++)
111                         {
112                                 Bytes value = messageGenerator.apply(++i);
113
114                                 ProducerRecord<String, Bytes> record =
115                                                 new ProducerRecord<>(
116                                                                 TOPIC,
117                                                                 partition,
118                                                                 Integer.toString(key%2),
119                                                                 value);
120
121                                 kafkaProducer.send(record, (metadata, e) ->
122                                 {
123                                         if (metadata != null)
124                                         {
125                                                 log.debug(
126                                                                 "{}|{} - {}={}",
127                                                                 metadata.partition(),
128                                                                 metadata.offset(),
129                                                                 record.key(),
130                                                                 record.value());
131                                         }
132                                         else
133                                         {
134                                                 log.warn(
135                                                                 "Exception for {}={}: {}",
136                                                                 record.key(),
137                                                                 record.value(),
138                                                                 e.toString());
139                                         }
140                                 });
141                         }
142                 }
143         }
144
145         EndlessConsumer<String, Long> runEndlessConsumer(Consumer<ConsumerRecord<String, Long>> consumer)
146         {
147                 oldOffsets = new HashMap<>();
148                 newOffsets = new HashMap<>();
149
150                 doForCurrentOffsets((tp, offset) ->
151                 {
152                         oldOffsets.put(tp, offset - 1);
153                         newOffsets.put(tp, offset - 1);
154                 });
155
156                 Consumer<ConsumerRecord<String, Long>> captureOffset =
157                                 record ->
158                                                 newOffsets.put(
159                                                                 new TopicPartition(record.topic(), record.partition()),
160                                                                 record.offset());
161
162                 EndlessConsumer<String, Long> endlessConsumer =
163                                 new EndlessConsumer<>(
164                                                 executor,
165                                                 properties.getClientId(),
166                                                 properties.getTopic(),
167                                                 kafkaConsumer,
168                                                 captureOffset.andThen(consumer));
169
170                 endlessConsumer.run();
171
172                 return endlessConsumer;
173         }
174
175         List<TopicPartition> partitions()
176         {
177                 return
178                                 IntStream
179                                                 .range(0, PARTITIONS)
180                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
181                                                 .collect(Collectors.toList());
182         }
183
184         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
185         {
186                 kafkaConsumer.assign(partitions());
187                 partitions().forEach(tp -> consumer.accept(tp, kafkaConsumer.position(tp)));
188                 kafkaConsumer.unsubscribe();
189         }
190
191         void checkSeenOffsetsForProgress()
192         {
193                 // Be sure, that some messages were consumed...!
194                 Set<TopicPartition> withProgress = new HashSet<>();
195                 partitions().forEach(tp ->
196                 {
197                         Long oldOffset = oldOffsets.get(tp);
198                         Long newOffset = newOffsets.get(tp);
199                         if (!oldOffset.equals(newOffset))
200                         {
201                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
202                                 withProgress.add(tp);
203                         }
204                 });
205                 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
206         }
207
208         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
209         {
210                 doForCurrentOffsets((tp, offset) ->
211                 {
212                         Long expected = offsetsToCheck.get(tp) + 1;
213                         log.debug("Checking, if the offset for {} is {}", tp, expected);
214                         assertThat(offset).isEqualTo(expected);
215                 });
216         }
217
218
219         @TestConfiguration
220         @Import(ApplicationConfiguration.class)
221         public static class Configuration
222         {
223                 @Bean
224                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
225                 {
226                         Properties props = new Properties();
227                         props.put("bootstrap.servers", properties.getBootstrapServer());
228                         props.put("linger.ms", 100);
229                         props.put("key.serializer", StringSerializer.class.getName());
230                         props.put("value.serializer", BytesSerializer.class.getName());
231
232                         return new KafkaProducer<>(props);
233                 }
234         }
235 }