Deserialisierung von Nachrichten unterschiedlichen Typs
[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.test.context.ConfigDataApplicationContextInitializer;
15 import org.springframework.boot.test.context.TestConfiguration;
16 import org.springframework.context.annotation.Bean;
17 import org.springframework.context.annotation.Import;
18 import org.springframework.kafka.support.serializer.JsonSerializer;
19 import org.springframework.kafka.test.context.EmbeddedKafka;
20 import org.springframework.test.context.TestPropertySource;
21 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
22
23 import java.time.Duration;
24 import java.time.LocalDateTime;
25 import java.util.*;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.function.BiConsumer;
29 import java.util.function.Consumer;
30 import java.util.stream.Collectors;
31 import java.util.stream.IntStream;
32
33 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
34 import static de.juplo.kafka.ApplicationTests.TOPIC;
35 import static org.assertj.core.api.Assertions.*;
36 import static org.awaitility.Awaitility.*;
37
38
39 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
40 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
41 @TestPropertySource(
42                 properties = {
43                                 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
44                                 "consumer.topic=" + TOPIC })
45 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
46 @Slf4j
47 class ApplicationTests
48 {
49         public static final String TOPIC = "FOO";
50         public static final int PARTITIONS = 10;
51
52
53         StringSerializer stringSerializer = new StringSerializer();
54
55         @Autowired
56         Serializer valueSerializer;
57         @Autowired
58         KafkaProducer<String, Bytes> kafkaProducer;
59         @Autowired
60         KafkaConsumer<String, ValidMessage> kafkaConsumer;
61         @Autowired
62         KafkaConsumer<Bytes, Bytes> offsetConsumer;
63         @Autowired
64         ApplicationProperties properties;
65         @Autowired
66         ExecutorService executor;
67
68         Consumer<ConsumerRecord<String, ValidMessage>> testHandler;
69         EndlessConsumer<String, ValidMessage> endlessConsumer;
70         Map<TopicPartition, Long> oldOffsets;
71         Map<TopicPartition, Long> newOffsets;
72         Set<ConsumerRecord<String, ValidMessage>> receivedRecords;
73
74
75         /** Tests methods */
76
77         @Test
78         @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
79         void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
80         {
81                 send100Messages((partition, key, counter) ->
82                 {
83                         Bytes value;
84                         String type;
85
86                         if (counter%3 != 0)
87                         {
88                                 value = serializeClientMessage(key, counter);
89                                 type = "message";
90                         }
91                         else {
92                                 value = serializeGreeting(key, counter);
93                                 type = "greeting";
94                         }
95
96                         return toRecord(partition, key, value, type);
97                 });
98
99                 await("100 records received")
100                                 .atMost(Duration.ofSeconds(30))
101                                 .until(() -> receivedRecords.size() >= 100);
102
103                 await("Offsets committed")
104                                 .atMost(Duration.ofSeconds(10))
105                                 .untilAsserted(() ->
106                                 {
107                                         checkSeenOffsetsForProgress();
108                                         compareToCommitedOffsets(newOffsets);
109                                 });
110
111                 assertThatExceptionOfType(IllegalStateException.class)
112                                 .isThrownBy(() -> endlessConsumer.exitStatus())
113                                 .describedAs("Consumer should still be running");
114         }
115
116         @Test
117         @Order(2)
118         void commitsOffsetOfErrorForReprocessingOnError()
119         {
120                 send100Messages((partition, key, counter) ->
121                 {
122                         Bytes value;
123                         String type;
124
125                         if (counter == 77)
126                         {
127                                 value = serializeFooMessage(key, counter);
128                                 type = "foo";
129                         }
130                         else
131                         {
132                                 if (counter%3 != 0)
133                                 {
134                                         value = serializeClientMessage(key, counter);
135                                         type = "message";
136                                 }
137                                 else {
138                                         value = serializeGreeting(key, counter);
139                                         type = "greeting";
140                                 }
141                         }
142
143                         return toRecord(partition, key, value, type);
144                 });
145
146                 await("Consumer failed")
147                                 .atMost(Duration.ofSeconds(30))
148                                 .until(() -> !endlessConsumer.running());
149
150                 checkSeenOffsetsForProgress();
151                 compareToCommitedOffsets(newOffsets);
152
153                 endlessConsumer.start();
154                 await("Consumer failed")
155                                 .atMost(Duration.ofSeconds(30))
156                                 .until(() -> !endlessConsumer.running());
157
158                 checkSeenOffsetsForProgress();
159                 compareToCommitedOffsets(newOffsets);
160                 assertThat(receivedRecords.size())
161                                 .describedAs("Received not all sent events")
162                                 .isLessThan(100);
163
164                 assertThatNoException()
165                                 .describedAs("Consumer should not be running")
166                                 .isThrownBy(() -> endlessConsumer.exitStatus());
167                 assertThat(endlessConsumer.exitStatus())
168                                 .describedAs("Consumer should have exited abnormally")
169                                 .containsInstanceOf(RecordDeserializationException.class);
170         }
171
172
173         /** Helper methods for the verification of expectations */
174
175         void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
176         {
177                 doForCurrentOffsets((tp, offset) ->
178                 {
179                         Long expected = offsetsToCheck.get(tp) + 1;
180                         log.debug("Checking, if the offset for {} is {}", tp, expected);
181                         assertThat(offset)
182                                         .describedAs("Committed offset corresponds to the offset of the consumer")
183                                         .isEqualTo(expected);
184                 });
185         }
186
187         void checkSeenOffsetsForProgress()
188         {
189                 // Be sure, that some messages were consumed...!
190                 Set<TopicPartition> withProgress = new HashSet<>();
191                 partitions().forEach(tp ->
192                 {
193                         Long oldOffset = oldOffsets.get(tp);
194                         Long newOffset = newOffsets.get(tp);
195                         if (!oldOffset.equals(newOffset))
196                         {
197                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
198                                 withProgress.add(tp);
199                         }
200                 });
201                 assertThat(withProgress)
202                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
203                                 .isNotEmpty();
204         }
205
206
207         /** Helper methods for setting up and running the tests */
208
209         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
210         {
211                 offsetConsumer.assign(partitions());
212                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
213                 offsetConsumer.unsubscribe();
214         }
215
216         List<TopicPartition> partitions()
217         {
218                 return
219                                 IntStream
220                                                 .range(0, PARTITIONS)
221                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
222                                                 .collect(Collectors.toList());
223         }
224
225
226         public interface RecordGenerator<K, V>
227         {
228                 public ProducerRecord<String, Bytes> generate(int partition, String key, long counter);
229         }
230
231         void send100Messages(RecordGenerator recordGenerator)
232         {
233                 long i = 0;
234
235                 for (int partition = 0; partition < 10; partition++)
236                 {
237                         for (int key = 0; key < 10; key++)
238                         {
239                                 ProducerRecord<String, Bytes> record =
240                                                 recordGenerator.generate(partition, Integer.toString(partition*10+key%2), ++i);
241
242                                 kafkaProducer.send(record, (metadata, e) ->
243                                 {
244                                         if (metadata != null)
245                                         {
246                                                 log.debug(
247                                                                 "{}|{} - {}={}",
248                                                                 metadata.partition(),
249                                                                 metadata.offset(),
250                                                                 record.key(),
251                                                                 record.value());
252                                         }
253                                         else
254                                         {
255                                                 log.warn(
256                                                                 "Exception for {}={}: {}",
257                                                                 record.key(),
258                                                                 record.value(),
259                                                                 e.toString());
260                                         }
261                                 });
262                         }
263                 }
264         }
265
266         ProducerRecord<String, Bytes> toRecord(int partition, String key, Bytes value, String type)
267         {
268                 ProducerRecord<String, Bytes> record =
269                                 new ProducerRecord<>(TOPIC, partition, key, value);
270                 record.headers().add("__TypeId__", type.getBytes());
271                 return record;
272         }
273
274         Bytes serializeClientMessage(String key, Long value)
275         {
276                 TestClientMessage message = new TestClientMessage(key, value.toString());
277                 return new Bytes(valueSerializer.serialize(TOPIC, message));
278         }
279
280         Bytes serializeGreeting(String key, Long value)
281         {
282                 TestGreeting message = new TestGreeting(key, LocalDateTime.now());
283                 return new Bytes(valueSerializer.serialize(TOPIC, message));
284         }
285
286         Bytes serializeFooMessage(String key, Long value)
287         {
288                 TestFooMessage message = new TestFooMessage(key, value);
289                 return new Bytes(valueSerializer.serialize(TOPIC, message));
290         }
291
292         @BeforeEach
293         public void init()
294         {
295                 testHandler = record -> {} ;
296
297                 oldOffsets = new HashMap<>();
298                 newOffsets = new HashMap<>();
299                 receivedRecords = new HashSet<>();
300
301                 doForCurrentOffsets((tp, offset) ->
302                 {
303                         oldOffsets.put(tp, offset - 1);
304                         newOffsets.put(tp, offset - 1);
305                 });
306
307                 Consumer<ConsumerRecord<String, ValidMessage>> captureOffsetAndExecuteTestHandler =
308                                 record ->
309                                 {
310                                         newOffsets.put(
311                                                         new TopicPartition(record.topic(), record.partition()),
312                                                         record.offset());
313                                         receivedRecords.add(record);
314                                         testHandler.accept(record);
315                                 };
316
317                 endlessConsumer =
318                                 new EndlessConsumer<>(
319                                                 executor,
320                                                 properties.getClientId(),
321                                                 properties.getTopic(),
322                                                 kafkaConsumer,
323                                                 captureOffsetAndExecuteTestHandler);
324
325                 endlessConsumer.start();
326         }
327
328         @AfterEach
329         public void deinit()
330         {
331                 try
332                 {
333                         endlessConsumer.stop();
334                 }
335                 catch (Exception e)
336                 {
337                         log.info("Exception while stopping the consumer: {}", e.toString());
338                 }
339         }
340
341
342         @TestConfiguration
343         @Import(ApplicationConfiguration.class)
344         public static class Configuration
345         {
346                 @Bean
347                 Serializer<ValidMessage> serializer()
348                 {
349                         return new JsonSerializer<>();
350                 }
351
352                 @Bean
353                 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
354                 {
355                         Properties props = new Properties();
356                         props.put("bootstrap.servers", properties.getBootstrapServer());
357                         props.put("linger.ms", 100);
358                         props.put("key.serializer", StringSerializer.class.getName());
359                         props.put("value.serializer", BytesSerializer.class.getName());
360
361                         return new KafkaProducer<>(props);
362                 }
363
364                 @Bean
365                 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
366                 {
367                         Properties props = new Properties();
368                         props.put("bootstrap.servers", properties.getBootstrapServer());
369                         props.put("client.id", "OFFSET-CONSUMER");
370                         props.put("group.id", properties.getGroupId());
371                         props.put("key.deserializer", BytesDeserializer.class.getName());
372                         props.put("value.deserializer", BytesDeserializer.class.getName());
373
374                         return new KafkaConsumer<>(props);
375                 }
376         }
377 }