1 package de.juplo.kafka;
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.Import;
17 import org.springframework.kafka.test.context.EmbeddedKafka;
18 import org.springframework.test.context.TestPropertySource;
19 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
21 import java.time.Duration;
23 import java.util.concurrent.ExecutorService;
24 import java.util.function.BiConsumer;
25 import java.util.function.Consumer;
26 import java.util.stream.Collectors;
27 import java.util.stream.IntStream;
29 import static de.juplo.kafka.GenericApplicationTests.PARTITIONS;
30 import static de.juplo.kafka.GenericApplicationTests.TOPIC;
31 import static org.assertj.core.api.Assertions.*;
32 import static org.awaitility.Awaitility.*;
35 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
38 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
39 "consumer.topic=" + TOPIC,
40 "consumer.commit-interval=500ms" })
41 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
43 abstract class GenericApplicationTests<K, V>
45 public static final String TOPIC = "FOO";
46 public static final int PARTITIONS = 10;
50 KafkaConsumer<K, V> kafkaConsumer;
52 Consumer<ConsumerRecord<K, V>> consumer;
54 ApplicationProperties properties;
56 ExecutorService executor;
58 KafkaProducer<Bytes, Bytes> testRecordProducer;
59 KafkaConsumer<Bytes, Bytes> offsetConsumer;
60 EndlessConsumer<K, V> endlessConsumer;
61 Map<TopicPartition, Long> oldOffsets;
62 Map<TopicPartition, Long> seenOffsets;
63 Set<ConsumerRecord<K, V>> receivedRecords;
66 final RecordGenerator recordGenerator;
67 final Consumer<ProducerRecord<Bytes, Bytes>> messageSender;
69 public GenericApplicationTests(RecordGenerator recordGenerator)
71 this.recordGenerator = recordGenerator;
72 this.messageSender = (record) -> sendMessage(record);
79 void commitsCurrentOffsetsOnSuccess()
81 int numberOfGeneratedMessages =
82 recordGenerator.generate(false, false, messageSender);
84 await(numberOfGeneratedMessages + " records received")
85 .atMost(Duration.ofSeconds(30))
86 .pollInterval(Duration.ofSeconds(1))
87 .until(() -> receivedRecords.size() >= numberOfGeneratedMessages);
89 await("Offsets committed")
90 .atMost(Duration.ofSeconds(10))
91 .pollInterval(Duration.ofSeconds(1))
94 checkSeenOffsetsForProgress();
95 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
98 assertThatExceptionOfType(IllegalStateException.class)
99 .isThrownBy(() -> endlessConsumer.exitStatus())
100 .describedAs("Consumer should still be running");
102 recordGenerator.assertBusinessLogic();
106 @SkipWhenErrorCannotBeGenerated(poisonPill = true)
107 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
109 int numberOfGeneratedMessages =
110 recordGenerator.generate(true, false, messageSender);
112 await("Consumer failed")
113 .atMost(Duration.ofSeconds(30))
114 .pollInterval(Duration.ofSeconds(1))
115 .until(() -> !endlessConsumer.running());
117 checkSeenOffsetsForProgress();
118 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
120 endlessConsumer.start();
121 await("Consumer failed")
122 .atMost(Duration.ofSeconds(30))
123 .pollInterval(Duration.ofSeconds(1))
124 .until(() -> !endlessConsumer.running());
126 checkSeenOffsetsForProgress();
127 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
128 assertThat(receivedRecords.size())
129 .describedAs("Received not all sent events")
130 .isLessThan(numberOfGeneratedMessages);
132 assertThatNoException()
133 .describedAs("Consumer should not be running")
134 .isThrownBy(() -> endlessConsumer.exitStatus());
135 assertThat(endlessConsumer.exitStatus())
136 .describedAs("Consumer should have exited abnormally")
137 .containsInstanceOf(RecordDeserializationException.class);
139 recordGenerator.assertBusinessLogic();
143 @SkipWhenErrorCannotBeGenerated(logicError = true)
144 void doesNotCommitOffsetsOnLogicError()
146 int numberOfGeneratedMessages =
147 recordGenerator.generate(false, true, messageSender);
149 await("Consumer failed")
150 .atMost(Duration.ofSeconds(30))
151 .pollInterval(Duration.ofSeconds(1))
152 .until(() -> !endlessConsumer.running());
154 checkSeenOffsetsForProgress();
155 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
157 endlessConsumer.start();
158 await("Consumer failed")
159 .atMost(Duration.ofSeconds(30))
160 .pollInterval(Duration.ofSeconds(1))
161 .until(() -> !endlessConsumer.running());
163 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
165 assertThatNoException()
166 .describedAs("Consumer should not be running")
167 .isThrownBy(() -> endlessConsumer.exitStatus());
168 assertThat(endlessConsumer.exitStatus())
169 .describedAs("Consumer should have exited abnormally")
170 .containsInstanceOf(RuntimeException.class);
172 recordGenerator.assertBusinessLogic();
176 /** Helper methods for the verification of expectations */
178 void assertSeenOffsetsEqualCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
180 doForCurrentOffsets((tp, offset) ->
182 Long expected = offsetsToCheck.get(tp) + 1;
183 log.debug("Checking, if the offset {} for {} is exactly {}", offset, tp, expected);
185 .describedAs("Committed offset corresponds to the offset of the consumer")
186 .isEqualTo(expected);
190 void assertSeenOffsetsAreBehindCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
192 List<Boolean> isOffsetBehindSeen = new LinkedList<>();
194 doForCurrentOffsets((tp, offset) ->
196 Long expected = offsetsToCheck.get(tp) + 1;
197 log.debug("Checking, if the offset {} for {} is at most {}", offset, tp, expected);
199 .describedAs("Committed offset corresponds to the offset of the consumer")
200 .isLessThanOrEqualTo(expected);
201 isOffsetBehindSeen.add(offset < expected);
204 assertThat(isOffsetBehindSeen.stream().reduce(false, (result, next) -> result | next))
205 .describedAs("Committed offsets are behind seen offsets")
209 void checkSeenOffsetsForProgress()
211 // Be sure, that some messages were consumed...!
212 Set<TopicPartition> withProgress = new HashSet<>();
213 partitions().forEach(tp ->
215 Long oldOffset = oldOffsets.get(tp) + 1;
216 Long newOffset = seenOffsets.get(tp) + 1;
217 if (!oldOffset.equals(newOffset))
219 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
220 withProgress.add(tp);
223 assertThat(withProgress)
224 .describedAs("Some offsets must have changed, compared to the old offset-positions")
229 /** Helper methods for setting up and running the tests */
233 offsetConsumer.assign(partitions());
234 offsetConsumer.seekToEnd(partitions());
235 partitions().forEach(tp ->
237 // seekToEnd() works lazily: it only takes effect on poll()/position()
238 Long offset = offsetConsumer.position(tp);
239 log.info("New position for {}: {}", tp, offset);
241 // The new positions must be commited!
242 offsetConsumer.commitSync();
243 offsetConsumer.unsubscribe();
246 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
248 offsetConsumer.assign(partitions());
249 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
250 offsetConsumer.unsubscribe();
253 List<TopicPartition> partitions()
257 .range(0, PARTITIONS)
258 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
259 .collect(Collectors.toList());
263 public interface RecordGenerator
268 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
270 default boolean canGeneratePoisonPill()
275 default boolean canGenerateLogicError()
280 default void assertBusinessLogic()
282 log.debug("No business-logic to assert");
286 void sendMessage(ProducerRecord<Bytes, Bytes> record)
288 testRecordProducer.send(record, (metadata, e) ->
290 if (metadata != null)
294 metadata.partition(),
302 "Exception for {}={}: {}",
315 props = new Properties();
316 props.put("bootstrap.servers", properties.getBootstrapServer());
317 props.put("linger.ms", 100);
318 props.put("key.serializer", BytesSerializer.class.getName());
319 props.put("value.serializer", BytesSerializer.class.getName());
320 testRecordProducer = new KafkaProducer<>(props);
322 props = new Properties();
323 props.put("bootstrap.servers", properties.getBootstrapServer());
324 props.put("client.id", "OFFSET-CONSUMER");
325 props.put("group.id", properties.getGroupId());
326 props.put("key.deserializer", BytesDeserializer.class.getName());
327 props.put("value.deserializer", BytesDeserializer.class.getName());
328 offsetConsumer = new KafkaConsumer<>(props);
332 oldOffsets = new HashMap<>();
333 seenOffsets = new HashMap<>();
334 receivedRecords = new HashSet<>();
336 doForCurrentOffsets((tp, offset) ->
338 oldOffsets.put(tp, offset - 1);
339 seenOffsets.put(tp, offset - 1);
342 Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
346 new TopicPartition(record.topic(), record.partition()),
348 receivedRecords.add(record);
349 consumer.accept(record);
353 new EndlessConsumer<>(
355 properties.getClientId(),
356 properties.getTopic(),
358 captureOffsetAndExecuteTestHandler);
360 endlessConsumer.start();
368 endlessConsumer.stop();
369 testRecordProducer.close();
370 offsetConsumer.close();
374 log.info("Exception while stopping the consumer: {}", e.toString());
380 @Import(ApplicationConfiguration.class)
381 public static class Configuration