Springify: Konfiguration erfolgt über `KafkaProperties`
[demos/kafka/training] / src / test / java / de / juplo / kafka / GenericApplicationTests.java
1 package de.juplo.kafka;
2
3 import com.mongodb.client.MongoClient;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
6 import org.apache.kafka.clients.consumer.ConsumerRecord;
7 import org.apache.kafka.clients.consumer.KafkaConsumer;
8 import org.apache.kafka.clients.producer.KafkaProducer;
9 import org.apache.kafka.clients.producer.ProducerRecord;
10 import org.apache.kafka.common.TopicPartition;
11 import org.apache.kafka.common.errors.RecordDeserializationException;
12 import org.apache.kafka.common.serialization.*;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.*;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
17 import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
18 import org.springframework.boot.autoconfigure.mongo.MongoProperties;
19 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
20 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
21 import org.springframework.boot.test.context.TestConfiguration;
22 import org.springframework.context.annotation.Import;
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.ExecutorService;
30 import java.util.function.BiConsumer;
31 import java.util.function.Consumer;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
34
35 import static de.juplo.kafka.GenericApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.GenericApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.*;
38 import static org.awaitility.Awaitility.*;
39
40
41 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
42 @TestPropertySource(
43                 properties = {
44                                 "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}",
45                                 "sumup.adder.topic=" + TOPIC,
46                                 "spring.kafka.consumer.auto-commit-interval=500ms",
47                                 "spring.mongodb.embedded.version=4.4.13" })
48 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
49 @EnableAutoConfiguration
50 @AutoConfigureDataMongo
51 @Slf4j
52 abstract class GenericApplicationTests<K, V>
53 {
54         public static final String TOPIC = "FOO";
55         public static final int PARTITIONS = 10;
56
57
58         @Autowired
59         KafkaConsumer<K, V> kafkaConsumer;
60         @Autowired
61         Consumer<ConsumerRecord<K, V>> consumer;
62         @Autowired
63         ApplicationProperties applicationProperties;
64   @Autowired
65   KafkaProperties kafkaProperties;
66         @Autowired
67         ExecutorService executor;
68         @Autowired
69         MongoClient mongoClient;
70         @Autowired
71         MongoProperties mongoProperties;
72         @Autowired
73         ConsumerRebalanceListener rebalanceListener;
74         @Autowired
75         RecordHandler<K, V> recordHandler;
76
77         KafkaProducer<Bytes, Bytes> testRecordProducer;
78         KafkaConsumer<Bytes, Bytes> offsetConsumer;
79         EndlessConsumer<K, V> endlessConsumer;
80         Map<TopicPartition, Long> oldOffsets;
81         Map<TopicPartition, Long> seenOffsets;
82         Set<ConsumerRecord<K, V>> receivedRecords;
83
84
85         final RecordGenerator recordGenerator;
86         final Consumer<ProducerRecord<Bytes, Bytes>> messageSender;
87
88         public GenericApplicationTests(RecordGenerator recordGenerator)
89         {
90                 this.recordGenerator = recordGenerator;
91                 this.messageSender = (record) -> sendMessage(record);
92         }
93
94
95         /** Tests methods */
96
97         @Test
98         void commitsCurrentOffsetsOnSuccess() throws Exception
99         {
100                 int numberOfGeneratedMessages =
101                                 recordGenerator.generate(false, false, messageSender);
102
103                 await(numberOfGeneratedMessages + " records received")
104                                 .atMost(Duration.ofSeconds(30))
105                                 .pollInterval(Duration.ofSeconds(1))
106                                 .until(() -> receivedRecords.size() >= numberOfGeneratedMessages);
107
108                 await("Offsets committed")
109                                 .atMost(Duration.ofSeconds(10))
110                                 .pollInterval(Duration.ofSeconds(1))
111                                 .untilAsserted(() ->
112                                 {
113                                         checkSeenOffsetsForProgress();
114                                         assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
115                                 });
116
117                 assertThatExceptionOfType(IllegalStateException.class)
118                                 .isThrownBy(() -> endlessConsumer.exitStatus())
119                                 .describedAs("Consumer should still be running");
120
121                 endlessConsumer.stop();
122                 recordGenerator.assertBusinessLogic();
123         }
124
125         @Test
126         @SkipWhenErrorCannotBeGenerated(poisonPill = true)
127         void commitsOffsetOfErrorForReprocessingOnDeserializationError()
128         {
129                 int numberOfGeneratedMessages =
130                                 recordGenerator.generate(true, false, messageSender);
131
132                 await("Consumer failed")
133                                 .atMost(Duration.ofSeconds(30))
134                                 .pollInterval(Duration.ofSeconds(1))
135                                 .until(() -> !endlessConsumer.running());
136
137                 checkSeenOffsetsForProgress();
138                 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
139
140                 endlessConsumer.start();
141                 await("Consumer failed")
142                                 .atMost(Duration.ofSeconds(30))
143                                 .pollInterval(Duration.ofSeconds(1))
144                                 .until(() -> !endlessConsumer.running());
145
146                 checkSeenOffsetsForProgress();
147                 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
148                 assertThat(receivedRecords.size())
149                                 .describedAs("Received not all sent events")
150                                 .isLessThan(numberOfGeneratedMessages);
151
152                 assertThatNoException()
153                                 .describedAs("Consumer should not be running")
154                                 .isThrownBy(() -> endlessConsumer.exitStatus());
155                 assertThat(endlessConsumer.exitStatus())
156                                 .describedAs("Consumer should have exited abnormally")
157                                 .containsInstanceOf(RecordDeserializationException.class);
158
159                 recordGenerator.assertBusinessLogic();
160         }
161
162         @Test
163         @SkipWhenErrorCannotBeGenerated(logicError = true)
164         void doesNotCommitOffsetsOnLogicError()
165         {
166                 int numberOfGeneratedMessages =
167                                 recordGenerator.generate(false, true, messageSender);
168
169                 await("Consumer failed")
170                                 .atMost(Duration.ofSeconds(30))
171                                 .pollInterval(Duration.ofSeconds(1))
172                                 .until(() -> !endlessConsumer.running());
173
174                 checkSeenOffsetsForProgress();
175                 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
176
177                 endlessConsumer.start();
178                 await("Consumer failed")
179                                 .atMost(Duration.ofSeconds(30))
180                                 .pollInterval(Duration.ofSeconds(1))
181                                 .until(() -> !endlessConsumer.running());
182
183                 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
184
185                 assertThatNoException()
186                                 .describedAs("Consumer should not be running")
187                                 .isThrownBy(() -> endlessConsumer.exitStatus());
188                 assertThat(endlessConsumer.exitStatus())
189                                 .describedAs("Consumer should have exited abnormally")
190                                 .containsInstanceOf(RuntimeException.class);
191
192                 recordGenerator.assertBusinessLogic();
193         }
194
195
196         /** Helper methods for the verification of expectations */
197
198         void assertSeenOffsetsEqualCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
199         {
200                 doForCurrentOffsets((tp, offset) ->
201                 {
202                         Long expected = offsetsToCheck.get(tp) + 1;
203                         log.debug("Checking, if the offset {} for {} is exactly {}", offset, tp, expected);
204                         assertThat(offset)
205                                         .describedAs("Committed offset corresponds to the offset of the consumer")
206                                         .isEqualTo(expected);
207                 });
208         }
209
210         void assertSeenOffsetsAreBehindCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
211         {
212                 List<Boolean> isOffsetBehindSeen = new LinkedList<>();
213
214                 doForCurrentOffsets((tp, offset) ->
215                 {
216                         Long expected = offsetsToCheck.get(tp) + 1;
217                         log.debug("Checking, if the offset {} for {} is at most {}", offset, tp, expected);
218                         assertThat(offset)
219                                         .describedAs("Committed offset must be at most equal to the offset of the consumer")
220                                         .isLessThanOrEqualTo(expected);
221                         isOffsetBehindSeen.add(offset < expected);
222                 });
223
224                 assertThat(isOffsetBehindSeen.stream().reduce(false, (result, next) -> result | next))
225                                 .describedAs("Committed offsets are behind seen offsets")
226                                 .isTrue();
227         }
228
229         void checkSeenOffsetsForProgress()
230         {
231                 // Be sure, that some messages were consumed...!
232                 Set<TopicPartition> withProgress = new HashSet<>();
233                 partitions().forEach(tp ->
234                 {
235                         Long oldOffset = oldOffsets.get(tp) + 1;
236                         Long newOffset = seenOffsets.get(tp) + 1;
237                         if (!oldOffset.equals(newOffset))
238                         {
239                                 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
240                                 withProgress.add(tp);
241                         }
242                 });
243                 assertThat(withProgress)
244                                 .describedAs("Some offsets must have changed, compared to the old offset-positions")
245                                 .isNotEmpty();
246         }
247
248
249         /** Helper methods for setting up and running the tests */
250
251         void seekToEnd()
252         {
253                 offsetConsumer.assign(partitions());
254                 offsetConsumer.seekToEnd(partitions());
255                 partitions().forEach(tp ->
256                 {
257                         // seekToEnd() works lazily: it only takes effect on poll()/position()
258                         Long offset = offsetConsumer.position(tp);
259                         log.info("New position for {}: {}", tp, offset);
260                 });
261                 // The new positions must be commited!
262                 offsetConsumer.commitSync();
263                 offsetConsumer.unsubscribe();
264         }
265
266         void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
267         {
268                 offsetConsumer.assign(partitions());
269                 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
270                 offsetConsumer.unsubscribe();
271         }
272
273         List<TopicPartition> partitions()
274         {
275                 return
276                                 IntStream
277                                                 .range(0, PARTITIONS)
278                                                 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
279                                                 .collect(Collectors.toList());
280         }
281
282
283         public interface RecordGenerator
284         {
285                 int generate(
286                                 boolean poisonPills,
287                                 boolean logicErrors,
288                                 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
289
290                 default boolean canGeneratePoisonPill()
291                 {
292                         return true;
293                 }
294
295                 default boolean canGenerateLogicError()
296                 {
297                         return true;
298                 }
299
300                 default void assertBusinessLogic()
301                 {
302                         log.debug("No business-logic to assert");
303                 }
304         }
305
306         void sendMessage(ProducerRecord<Bytes, Bytes> record)
307         {
308                 testRecordProducer.send(record, (metadata, e) ->
309                 {
310                         if (metadata != null)
311                         {
312                                 log.debug(
313                                                 "{}|{} - {}={}",
314                                                 metadata.partition(),
315                                                 metadata.offset(),
316                                                 record.key(),
317                                                 record.value());
318                         }
319                         else
320                         {
321                                 log.warn(
322                                                 "Exception for {}={}: {}",
323                                                 record.key(),
324                                                 record.value(),
325                                                 e.toString());
326                         }
327                 });
328         }
329
330
331         @BeforeEach
332         public void init()
333         {
334                 Properties props;
335                 props = new Properties();
336                 props.put("bootstrap.servers", kafkaProperties.getBootstrapServers());
337                 props.put("linger.ms", 100);
338                 props.put("key.serializer", BytesSerializer.class.getName());
339                 props.put("value.serializer", BytesSerializer.class.getName());
340                 testRecordProducer = new KafkaProducer<>(props);
341
342                 props = new Properties();
343                 props.put("bootstrap.servers", kafkaProperties.getBootstrapServers());
344                 props.put("client.id", "OFFSET-CONSUMER");
345                 props.put("group.id", kafkaProperties.getConsumer().getGroupId());
346                 props.put("key.deserializer", BytesDeserializer.class.getName());
347                 props.put("value.deserializer", BytesDeserializer.class.getName());
348                 offsetConsumer = new KafkaConsumer<>(props);
349
350                 mongoClient.getDatabase(mongoProperties.getDatabase()).drop();
351                 seekToEnd();
352
353                 oldOffsets = new HashMap<>();
354                 seenOffsets = new HashMap<>();
355                 receivedRecords = new HashSet<>();
356
357                 doForCurrentOffsets((tp, offset) ->
358                 {
359                         oldOffsets.put(tp, offset - 1);
360                         seenOffsets.put(tp, offset - 1);
361                 });
362
363                 TestRecordHandler<K, V> captureOffsetAndExecuteTestHandler =
364                                 new TestRecordHandler<K, V>(recordHandler)
365                                 {
366                                         @Override
367                                         public void onNewRecord(ConsumerRecord<K, V> record)
368                                         {
369                                                 seenOffsets.put(
370                                                                 new TopicPartition(record.topic(), record.partition()),
371                                                                 record.offset());
372                                                 receivedRecords.add(record);
373                                         }
374                                 };
375
376                 endlessConsumer =
377                                 new EndlessConsumer<>(
378                                                 executor,
379                                                 kafkaProperties.getClientId(),
380                                                 applicationProperties.getTopic(),
381                                                 kafkaConsumer,
382                                                 rebalanceListener,
383                                                 captureOffsetAndExecuteTestHandler);
384
385                 endlessConsumer.start();
386         }
387
388         @AfterEach
389         public void deinit()
390         {
391                 try
392                 {
393                         testRecordProducer.close();
394                         offsetConsumer.close();
395                 }
396                 catch (Exception e)
397                 {
398                         log.info("Exception while stopping the consumer: {}", e.toString());
399                 }
400         }
401
402
403         @TestConfiguration
404         @Import(ApplicationConfiguration.class)
405         public static class Configuration
406         {
407         }
408 }