1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
6 import org.apache.kafka.clients.consumer.KafkaConsumer;
7 import org.apache.kafka.clients.producer.KafkaProducer;
8 import org.apache.kafka.clients.producer.ProducerRecord;
9 import org.apache.kafka.common.TopicPartition;
10 import org.apache.kafka.common.errors.RecordDeserializationException;
11 import org.apache.kafka.common.serialization.*;
12 import org.apache.kafka.common.utils.Bytes;
13 import org.junit.jupiter.api.*;
14 import org.springframework.beans.factory.annotation.Autowired;
15 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Import;
18 import org.springframework.kafka.test.context.EmbeddedKafka;
19 import org.springframework.test.context.TestPropertySource;
20 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
22 import java.time.Duration;
24 import java.util.concurrent.ExecutorService;
25 import java.util.function.BiConsumer;
26 import java.util.function.Consumer;
27 import java.util.stream.Collectors;
28 import java.util.stream.IntStream;
30 import static de.juplo.kafka.GenericApplicationTests.PARTITIONS;
31 import static de.juplo.kafka.GenericApplicationTests.TOPIC;
32 import static org.assertj.core.api.Assertions.*;
33 import static org.awaitility.Awaitility.*;
36 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
39 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
40 "consumer.topic=" + TOPIC,
41 "consumer.commit-interval=500ms" })
42 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
44 abstract class GenericApplicationTests<K, V>
46 public static final String TOPIC = "FOO";
47 public static final int PARTITIONS = 10;
51 org.apache.kafka.clients.consumer.Consumer<K, V> kafkaConsumer;
53 Consumer<ConsumerRecord<K, V>> consumer;
55 ApplicationProperties applicationProperties;
57 ExecutorService executor;
59 ConsumerRebalanceListener rebalanceListener;
61 RecordHandler<K, V> recordHandler;
63 KafkaProducer<Bytes, Bytes> testRecordProducer;
64 KafkaConsumer<Bytes, Bytes> offsetConsumer;
65 EndlessConsumer<K, V> endlessConsumer;
66 Map<TopicPartition, Long> oldOffsets;
67 Map<TopicPartition, Long> seenOffsets;
68 Set<ConsumerRecord<K, V>> receivedRecords;
71 final RecordGenerator recordGenerator;
72 final Consumer<ProducerRecord<Bytes, Bytes>> messageSender;
74 public GenericApplicationTests(RecordGenerator recordGenerator)
76 this.recordGenerator = recordGenerator;
77 this.messageSender = (record) -> sendMessage(record);
84 void commitsCurrentOffsetsOnSuccess() throws Exception
86 int numberOfGeneratedMessages =
87 recordGenerator.generate(false, false, messageSender);
89 await(numberOfGeneratedMessages + " records received")
90 .atMost(Duration.ofSeconds(30))
91 .pollInterval(Duration.ofSeconds(1))
92 .until(() -> receivedRecords.size() >= numberOfGeneratedMessages);
94 await("Offsets committed")
95 .atMost(Duration.ofSeconds(10))
96 .pollInterval(Duration.ofSeconds(1))
99 checkSeenOffsetsForProgress();
100 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
103 assertThatExceptionOfType(IllegalStateException.class)
104 .isThrownBy(() -> endlessConsumer.exitStatus())
105 .describedAs("Consumer should still be running");
107 endlessConsumer.stop();
108 recordGenerator.assertBusinessLogic();
112 @SkipWhenErrorCannotBeGenerated(poisonPill = true)
113 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
115 int numberOfGeneratedMessages =
116 recordGenerator.generate(true, false, messageSender);
118 await("Consumer failed")
119 .atMost(Duration.ofSeconds(30))
120 .pollInterval(Duration.ofSeconds(1))
121 .until(() -> !endlessConsumer.running());
123 checkSeenOffsetsForProgress();
124 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
126 endlessConsumer.start();
127 await("Consumer failed")
128 .atMost(Duration.ofSeconds(30))
129 .pollInterval(Duration.ofSeconds(1))
130 .until(() -> !endlessConsumer.running());
132 checkSeenOffsetsForProgress();
133 assertSeenOffsetsEqualCommittedOffsets(seenOffsets);
134 assertThat(receivedRecords.size())
135 .describedAs("Received not all sent events")
136 .isLessThan(numberOfGeneratedMessages);
138 assertThatNoException()
139 .describedAs("Consumer should not be running")
140 .isThrownBy(() -> endlessConsumer.exitStatus());
141 assertThat(endlessConsumer.exitStatus())
142 .describedAs("Consumer should have exited abnormally")
143 .containsInstanceOf(RecordDeserializationException.class);
145 recordGenerator.assertBusinessLogic();
149 @SkipWhenErrorCannotBeGenerated(logicError = true)
150 void doesNotCommitOffsetsOnLogicError()
152 int numberOfGeneratedMessages =
153 recordGenerator.generate(false, true, messageSender);
155 await("Consumer failed")
156 .atMost(Duration.ofSeconds(30))
157 .pollInterval(Duration.ofSeconds(1))
158 .until(() -> !endlessConsumer.running());
160 checkSeenOffsetsForProgress();
161 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
163 endlessConsumer.start();
164 await("Consumer failed")
165 .atMost(Duration.ofSeconds(30))
166 .pollInterval(Duration.ofSeconds(1))
167 .until(() -> !endlessConsumer.running());
169 assertSeenOffsetsAreBehindCommittedOffsets(seenOffsets);
171 assertThatNoException()
172 .describedAs("Consumer should not be running")
173 .isThrownBy(() -> endlessConsumer.exitStatus());
174 assertThat(endlessConsumer.exitStatus())
175 .describedAs("Consumer should have exited abnormally")
176 .containsInstanceOf(RuntimeException.class);
178 recordGenerator.assertBusinessLogic();
182 /** Helper methods for the verification of expectations */
184 void assertSeenOffsetsEqualCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
186 doForCurrentOffsets((tp, offset) ->
188 Long expected = offsetsToCheck.get(tp) + 1;
189 log.debug("Checking, if the offset {} for {} is exactly {}", offset, tp, expected);
191 .describedAs("Committed offset corresponds to the offset of the consumer")
192 .isEqualTo(expected);
196 void assertSeenOffsetsAreBehindCommittedOffsets(Map<TopicPartition, Long> offsetsToCheck)
198 List<Boolean> isOffsetBehindSeen = new LinkedList<>();
200 doForCurrentOffsets((tp, offset) ->
202 Long expected = offsetsToCheck.get(tp) + 1;
203 log.debug("Checking, if the offset {} for {} is at most {}", offset, tp, expected);
205 .describedAs("Committed offset must be at most equal to the offset of the consumer")
206 .isLessThanOrEqualTo(expected);
207 isOffsetBehindSeen.add(offset < expected);
210 assertThat(isOffsetBehindSeen.stream().reduce(false, (result, next) -> result | next))
211 .describedAs("Committed offsets are behind seen offsets")
215 void checkSeenOffsetsForProgress()
217 // Be sure, that some messages were consumed...!
218 Set<TopicPartition> withProgress = new HashSet<>();
219 partitions().forEach(tp ->
221 Long oldOffset = oldOffsets.get(tp) + 1;
222 Long newOffset = seenOffsets.get(tp) + 1;
223 if (!oldOffset.equals(newOffset))
225 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
226 withProgress.add(tp);
229 assertThat(withProgress)
230 .describedAs("Some offsets must have changed, compared to the old offset-positions")
235 /** Helper methods for setting up and running the tests */
239 offsetConsumer.assign(partitions());
240 offsetConsumer.seekToEnd(partitions());
241 partitions().forEach(tp ->
243 // seekToEnd() works lazily: it only takes effect on poll()/position()
244 Long offset = offsetConsumer.position(tp);
245 log.info("New position for {}: {}", tp, offset);
247 // The new positions must be commited!
248 offsetConsumer.commitSync();
249 offsetConsumer.unsubscribe();
252 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
254 offsetConsumer.assign(partitions());
255 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
256 offsetConsumer.unsubscribe();
259 List<TopicPartition> partitions()
263 .range(0, PARTITIONS)
264 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
265 .collect(Collectors.toList());
269 public interface RecordGenerator
274 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
276 default boolean canGeneratePoisonPill()
281 default boolean canGenerateLogicError()
286 default void assertBusinessLogic()
288 log.debug("No business-logic to assert");
292 void sendMessage(ProducerRecord<Bytes, Bytes> record)
294 testRecordProducer.send(record, (metadata, e) ->
296 if (metadata != null)
300 metadata.partition(),
308 "Exception for {}={}: {}",
321 props = new Properties();
322 props.put("bootstrap.servers", applicationProperties.getBootstrapServer());
323 props.put("linger.ms", 100);
324 props.put("key.serializer", BytesSerializer.class.getName());
325 props.put("value.serializer", BytesSerializer.class.getName());
326 testRecordProducer = new KafkaProducer<>(props);
328 props = new Properties();
329 props.put("bootstrap.servers", applicationProperties.getBootstrapServer());
330 props.put("client.id", "OFFSET-CONSUMER");
331 props.put("group.id", applicationProperties.getGroupId());
332 props.put("key.deserializer", BytesDeserializer.class.getName());
333 props.put("value.deserializer", BytesDeserializer.class.getName());
334 offsetConsumer = new KafkaConsumer<>(props);
338 oldOffsets = new HashMap<>();
339 seenOffsets = new HashMap<>();
340 receivedRecords = new HashSet<>();
342 doForCurrentOffsets((tp, offset) ->
344 oldOffsets.put(tp, offset - 1);
345 seenOffsets.put(tp, offset - 1);
348 TestRecordHandler<K, V> captureOffsetAndExecuteTestHandler =
349 new TestRecordHandler<K, V>(recordHandler)
352 public void onNewRecord(ConsumerRecord<K, V> record)
355 new TopicPartition(record.topic(), record.partition()),
357 receivedRecords.add(record);
358 consumer.accept(record);
363 new EndlessConsumer<>(
365 applicationProperties.getClientId(),
366 applicationProperties.getTopic(),
368 captureOffsetAndExecuteTestHandler);
370 endlessConsumer.start();
378 testRecordProducer.close();
379 offsetConsumer.close();
383 log.info("Exception while stopping the consumer: {}", e.toString());
389 @Import(ApplicationConfiguration.class)
390 public static class Configuration