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