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