Springify: Gemeinsame DLQ für Poison Pills und Fachlogik-Fehler konfiguriert
[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.serialization.*;
10 import org.apache.kafka.common.utils.Bytes;
11 import org.junit.jupiter.api.*;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
14 import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
15 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.context.annotation.Import;
19 import org.springframework.context.annotation.Primary;
20 import org.springframework.kafka.support.serializer.JsonSerializer;
21 import org.springframework.kafka.test.context.EmbeddedKafka;
22 import org.springframework.test.context.TestPropertySource;
23 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
24
25 import java.time.Duration;
26 import java.util.*;
27 import java.util.concurrent.ExecutionException;
28 import java.util.function.BiConsumer;
29 import java.util.function.BiFunction;
30 import java.util.function.Consumer;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
33
34 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
35 import static de.juplo.kafka.ApplicationTests.TOPIC;
36 import static org.assertj.core.api.Assertions.*;
37 import static org.awaitility.Awaitility.*;
38
39
40 @SpringJUnitConfig(
41                 initializers = ConfigDataApplicationContextInitializer.class,
42                 classes = {
43                                 EndlessConsumer.class,
44                                 KafkaAutoConfiguration.class,
45                                 ApplicationTests.Configuration.class })
46 @TestPropertySource(
47                 properties = {
48                                 "spring.kafka.consumer.bootstrap-servers=${spring.embedded.kafka.brokers}",
49                                 "spring.kafka.producer.bootstrap-servers=${spring.embedded.kafka.brokers}",
50                                 "consumer.topic=" + TOPIC })
51 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
52 @Slf4j
53 class ApplicationTests
54 {
55         public static final String TOPIC = "FOO";
56         public static final int PARTITIONS = 10;
57
58
59         StringSerializer stringSerializer = new StringSerializer();
60
61         @Autowired
62         Serializer valueSerializer;
63         @Autowired
64         KafkaProducer<String, Bytes> kafkaProducer;
65         @Autowired
66         org.apache.kafka.clients.consumer.Consumer<String, ClientMessage> kafkaConsumer;
67         @Autowired
68         KafkaConsumer<Bytes, Bytes> offsetConsumer;
69         @Autowired
70         ApplicationProperties applicationProperties;
71         @Autowired
72         KafkaProperties kafkaProperties;
73         @Autowired
74         EndlessConsumer endlessConsumer;
75         @Autowired
76         RecordHandler recordHandler;
77
78         Map<TopicPartition, Long> oldOffsets;
79         Map<TopicPartition, Long> newOffsets;
80         Set<ConsumerRecord<String, ClientMessage>> receivedRecords;
81
82
83         /** Tests methods */
84
85         @Test
86         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
87         {
88                 send100Messages((key, counter) -> serialize(key, counter));
89
90                 await("100 records received")
91                                 .atMost(Duration.ofSeconds(30))
92                                 .until(() -> receivedRecords.size() == 100);
93
94                 await("Offsets committed")
95                                 .atMost(Duration.ofSeconds(10))
96                                 .untilAsserted(() ->
97                                 {
98                                         checkSeenOffsetsForProgress();
99                                         compareToCommitedOffsets(newOffsets);
100                                 });
101
102                 assertThat(endlessConsumer.isRunning())
103                                 .describedAs("Consumer should still be running")
104                                 .isTrue();
105         }
106
107         @Test
108         void commitsCurrentOffsetsOnDeserializationError()
109         {
110                 send100Messages((key, counter) ->
111                                 counter == 77
112                                                 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
113                                                 : serialize(key, counter));
114
115                 await("99 records received")
116                                 .atMost(Duration.ofSeconds(30))
117                                 .until(() -> receivedRecords.size() == 99);
118
119                 await("Offsets committed")
120                                 .atMost(Duration.ofSeconds(10))
121                                 .untilAsserted(() ->
122                                 {
123                                         // UNSCHÖN:
124                                         // Funktioniert nur, weil nach der Nachrichten, die den
125                                         // Deserialisierungs-Fehler auslöst noch valide Nachrichten
126                                         // gelesen werden.
127                                         // GRUND:
128                                         // Der MessageHandler sieht den Offset der Fehlerhaften
129                                         // Nachricht nicht!
130                                         checkSeenOffsetsForProgress();
131                                         compareToCommitedOffsets(newOffsets);
132                                 });
133
134                 assertThat(endlessConsumer.isRunning())
135                                 .describedAs("Consumer should still be running")
136                                 .isTrue();
137         }
138
139         @Test
140         void commitsOffsetOnProgramLogicErrorFoo()
141         {
142                 recordHandler.testHandler = (record) ->
143                 {
144                         if (Integer.parseInt(record.value().message)%10 ==0)
145                                 throw new RuntimeException("BOOM: " + record.value().message + "%10 == 0");
146                 };
147
148                 send100Messages((key, counter) -> serialize(key, counter));
149
150                 await("80 records received")
151                                 .atMost(Duration.ofSeconds(30))
152                                 .until(() -> receivedRecords.size() == 100);
153
154                 await("Offsets committed")
155                                 .atMost(Duration.ofSeconds(10))
156                                 .untilAsserted(() ->
157                                 {
158                                         checkSeenOffsetsForProgress();
159                                         compareToCommitedOffsets(newOffsets);
160                                 });
161
162                 assertThat(endlessConsumer.isRunning())
163                                 .describedAs("Consumer should still be running")
164                                 .isTrue();
165         }
166
167
168         /** Helper methods for the verification of expectations */
169
170         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
171         {
172                 doForCurrentOffsets((tp, offset) ->
173                 {
174                         Long expected = offsetsToCheck.get(tp) + 1;
175                         log.debug("TEST: Comparing the expected offset of {} for {} to {}", expected, tp, offset);
176                         assertThat(offset)
177                                         .describedAs("Committed offset corresponds to the offset of the consumer")
178                                         .isEqualTo(expected);
179                 });
180         }
181
182         void checkSeenOffsetsForProgress()
183         {
184                 // Be sure, that some messages were consumed...!
185                 Set<TopicPartition> withProgress = new HashSet<>();
186                 partitions().forEach(tp ->
187                 {
188                         Long oldOffset = oldOffsets.get(tp);
189                         Long newOffset = newOffsets.get(tp);
190                         if (!oldOffset.equals(newOffset))
191                         {
192                                 log.debug("TEST: Progress for {}: {} -> {}", tp, oldOffset, newOffset);
193                                 withProgress.add(tp);
194                         }
195                 });
196                 log.debug("TEST: Offsets with progress: {}", withProgress);
197                 assertThat(withProgress)
198                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
199                                 .isNotEmpty();
200         }
201
202
203         /** Helper methods for setting up and running the tests */
204
205         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
206         {
207                 offsetConsumer.assign(partitions());
208                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
209                 offsetConsumer.unsubscribe();
210         }
211
212         List<TopicPartition> partitions()
213         {
214                 return
215                                 IntStream
216                                                 .range(0, PARTITIONS)
217                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
218                                                 .collect(Collectors.toList());
219         }
220
221
222         void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
223         {
224                 long i = 0;
225
226                 for (int partition = 0; partition < 10; partition++)
227                 {
228                         for (int key = 0; key < 10; key++)
229                         {
230                                 Bytes value = messageGenerator.apply(key, ++i);
231
232                                 ProducerRecord<String, Bytes> record =
233                                                 new ProducerRecord<>(
234                                                                 TOPIC,
235                                                                 partition,
236                                                                 Integer.toString(key%2),
237                                                                 value);
238
239                                 record.headers().add("__TypeId__", "message".getBytes());
240                                 kafkaProducer.send(record, (metadata, e) ->
241                                 {
242                                         if (metadata != null)
243                                         {
244                                                 log.debug(
245                                                                 "TEST: Sending partition={}, offset={} - {}={}",
246                                                                 metadata.partition(),
247                                                                 metadata.offset(),
248                                                                 record.key(),
249                                                                 record.value());
250                                         }
251                                         else
252                                         {
253                                                 log.warn(
254                                                                 "TEST: Exception for {}={}: {}",
255                                                                 record.key(),
256                                                                 record.value(),
257                                                                 e.toString());
258                                         }
259                                 });
260                         }
261                 }
262         }
263
264         Bytes serialize(Integer key, Long value)
265         {
266                 ClientMessage message = new ClientMessage();
267                 message.setClient(key.toString());
268                 message.setMessage(value.toString());
269                 return new Bytes(valueSerializer.serialize(TOPIC, message));
270         }
271
272
273         @BeforeEach
274         public void init()
275         {
276                 recordHandler.testHandler = (record) -> {};
277
278                 oldOffsets = new HashMap<>();
279                 newOffsets = new HashMap<>();
280                 receivedRecords = new HashSet<>();
281
282                 doForCurrentOffsets((tp, offset) ->
283                 {
284                         oldOffsets.put(tp, offset - 1);
285                         newOffsets.put(tp, offset - 1);
286                 });
287
288                 recordHandler.captureOffsets =
289                                 record ->
290                                 {
291                                         receivedRecords.add(record);
292                                         log.debug("TEST: Processing record #{}: {}", receivedRecords.size(), record.value());
293                                         newOffsets.put(
294                                                         new TopicPartition(record.topic(), record.partition()),
295                                                         record.offset());
296                                 };
297
298                 endlessConsumer.start();
299         }
300
301         @AfterEach
302         public void deinit()
303         {
304                 try
305                 {
306                         endlessConsumer.stop();
307                 }
308                 catch (Exception e)
309                 {
310                         log.info("TEST: Exception while stopping the consumer: {}", e.toString());
311                 }
312         }
313
314         public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
315         {
316                 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
317                 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
318
319
320                 @Override
321                 public void accept(ConsumerRecord<String, ClientMessage> record)
322                 {
323                         captureOffsets
324                                         .andThen(testHandler)
325                                         .accept(record);
326                 }
327         }
328
329         @TestConfiguration
330         @Import(ApplicationConfiguration.class)
331         public static class Configuration
332         {
333                 @Primary
334                 @Bean
335                 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
336                 {
337                         return new RecordHandler();
338                 }
339
340                 @Bean
341                 Serializer<ClientMessage> serializer()
342                 {
343                         return new JsonSerializer<>();
344                 }
345
346                 @Bean
347                 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
348                 {
349                         Properties props = new Properties();
350                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
351                         props.put("linger.ms", 100);
352                         props.put("key.serializer", StringSerializer.class.getName());
353                         props.put("value.serializer", BytesSerializer.class.getName());
354
355                         return new KafkaProducer<>(props);
356                 }
357
358                 @Bean
359                 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
360                 {
361                         Properties props = new Properties();
362                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
363                         props.put("client.id", "OFFSET-CONSUMER");
364                         props.put("group.id", properties.getConsumer().getGroupId());
365                         props.put("key.deserializer", BytesDeserializer.class.getName());
366                         props.put("value.deserializer", BytesDeserializer.class.getName());
367
368                         return new KafkaConsumer<>(props);
369                 }
370         }
371 }