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