Sporadische Timing-Fehler in dem Test ausgeschlossen
[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                                 .pollDelay(Duration.ofSeconds(1))
157                                 .untilAsserted(() ->
158                                 {
159                                         checkSeenOffsetsForProgress();
160                                         compareToCommitedOffsets(newOffsets);
161                                 });
162
163                 assertThat(endlessConsumer.isRunning())
164                                 .describedAs("Consumer should still be running")
165                                 .isTrue();
166         }
167
168
169         /** Helper methods for the verification of expectations */
170
171         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
172         {
173                 doForCurrentOffsets((tp, offset) ->
174                 {
175                         Long expected = offsetsToCheck.get(tp) + 1;
176                         log.debug("TEST: Comparing the expected offset of {} for {} to {}", expected, tp, offset);
177                         assertThat(offset)
178                                         .describedAs("Committed offset corresponds to the offset of the consumer")
179                                         .isEqualTo(expected);
180                 });
181         }
182
183         void checkSeenOffsetsForProgress()
184         {
185                 // Be sure, that some messages were consumed...!
186                 Set<TopicPartition> withProgress = new HashSet<>();
187                 partitions().forEach(tp ->
188                 {
189                         Long oldOffset = oldOffsets.get(tp);
190                         Long newOffset = newOffsets.get(tp);
191                         if (!oldOffset.equals(newOffset))
192                         {
193                                 log.debug("TEST: Progress for {}: {} -> {}", tp, oldOffset, newOffset);
194                                 withProgress.add(tp);
195                         }
196                 });
197                 log.debug("TEST: Offsets with progress: {}", withProgress);
198                 assertThat(withProgress)
199                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
200                                 .isNotEmpty();
201         }
202
203
204         /** Helper methods for setting up and running the tests */
205
206         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
207         {
208                 offsetConsumer.assign(partitions());
209                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
210                 offsetConsumer.unsubscribe();
211         }
212
213         List<TopicPartition> partitions()
214         {
215                 return
216                                 IntStream
217                                                 .range(0, PARTITIONS)
218                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
219                                                 .collect(Collectors.toList());
220         }
221
222
223         void send100Messages(BiFunction<Integer, Long, Bytes> messageGenerator)
224         {
225                 long i = 0;
226
227                 for (int partition = 0; partition < 10; partition++)
228                 {
229                         for (int key = 0; key < 10; key++)
230                         {
231                                 Bytes value = messageGenerator.apply(key, ++i);
232
233                                 ProducerRecord<String, Bytes> record =
234                                                 new ProducerRecord<>(
235                                                                 TOPIC,
236                                                                 partition,
237                                                                 Integer.toString(key%2),
238                                                                 value);
239
240                                 record.headers().add("__TypeId__", "message".getBytes());
241                                 kafkaProducer.send(record, (metadata, e) ->
242                                 {
243                                         if (metadata != null)
244                                         {
245                                                 log.debug(
246                                                                 "TEST: Sending partition={}, offset={} - {}={}",
247                                                                 metadata.partition(),
248                                                                 metadata.offset(),
249                                                                 record.key(),
250                                                                 record.value());
251                                         }
252                                         else
253                                         {
254                                                 log.warn(
255                                                                 "TEST: Exception for {}={}: {}",
256                                                                 record.key(),
257                                                                 record.value(),
258                                                                 e.toString());
259                                         }
260                                 });
261                         }
262                 }
263         }
264
265         Bytes serialize(Integer key, Long value)
266         {
267                 ClientMessage message = new ClientMessage();
268                 message.setClient(key.toString());
269                 message.setMessage(value.toString());
270                 return new Bytes(valueSerializer.serialize(TOPIC, message));
271         }
272
273
274         @BeforeEach
275         public void init()
276         {
277                 recordHandler.testHandler = (record) -> {};
278
279                 oldOffsets = new HashMap<>();
280                 newOffsets = new HashMap<>();
281                 receivedRecords = new HashSet<>();
282
283                 doForCurrentOffsets((tp, offset) ->
284                 {
285                         oldOffsets.put(tp, offset - 1);
286                         newOffsets.put(tp, offset - 1);
287                 });
288
289                 recordHandler.captureOffsets =
290                                 record ->
291                                 {
292                                         receivedRecords.add(record);
293                                         log.debug("TEST: Processing record #{}: {}", receivedRecords.size(), record.value());
294                                         newOffsets.put(
295                                                         new TopicPartition(record.topic(), record.partition()),
296                                                         record.offset());
297                                 };
298
299                 endlessConsumer.start();
300         }
301
302         @AfterEach
303         public void deinit()
304         {
305                 try
306                 {
307                         endlessConsumer.stop();
308                 }
309                 catch (Exception e)
310                 {
311                         log.info("TEST: Exception while stopping the consumer: {}", e.toString());
312                 }
313         }
314
315         public static class RecordHandler implements Consumer<ConsumerRecord<String, ClientMessage>>
316         {
317                 Consumer<ConsumerRecord<String, ClientMessage>> captureOffsets;
318                 Consumer<ConsumerRecord<String, ClientMessage>> testHandler;
319
320
321                 @Override
322                 public void accept(ConsumerRecord<String, ClientMessage> record)
323                 {
324                         captureOffsets
325                                         .andThen(testHandler)
326                                         .accept(record);
327                 }
328         }
329
330         @TestConfiguration
331         @Import(ApplicationConfiguration.class)
332         public static class Configuration
333         {
334                 @Primary
335                 @Bean
336                 public Consumer<ConsumerRecord<String, ClientMessage>> testHandler()
337                 {
338                         return new RecordHandler();
339                 }
340
341                 @Bean
342                 Serializer<ClientMessage> serializer()
343                 {
344                         return new JsonSerializer<>();
345                 }
346
347                 @Bean
348                 KafkaProducer<String, Bytes> kafkaProducer(KafkaProperties properties)
349                 {
350                         Properties props = new Properties();
351                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
352                         props.put("linger.ms", 100);
353                         props.put("key.serializer", StringSerializer.class.getName());
354                         props.put("value.serializer", BytesSerializer.class.getName());
355
356                         return new KafkaProducer<>(props);
357                 }
358
359                 @Bean
360                 KafkaConsumer<Bytes, Bytes> offsetConsumer(KafkaProperties properties)
361                 {
362                         Properties props = new Properties();
363                         props.put("bootstrap.servers", properties.getConsumer().getBootstrapServers());
364                         props.put("client.id", "OFFSET-CONSUMER");
365                         props.put("group.id", properties.getConsumer().getGroupId());
366                         props.put("key.deserializer", BytesDeserializer.class.getName());
367                         props.put("value.deserializer", BytesDeserializer.class.getName());
368
369                         return new KafkaConsumer<>(props);
370                 }
371         }
372 }