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=1s" })
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> newOffsets;
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 compareToCommitedOffsets(newOffsets);
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 compareToCommitedOffsets(newOffsets);
120 endlessConsumer.start();
121 await("Consumer failed")
122 .atMost(Duration.ofSeconds(30))
123 .pollInterval(Duration.ofSeconds(1))
124 .until(() -> !endlessConsumer.running());
126 checkSeenOffsetsForProgress();
127 compareToCommitedOffsets(newOffsets);
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 compareToCommitedOffsets(oldOffsets);
157 endlessConsumer.start();
158 await("Consumer failed")
159 .atMost(Duration.ofSeconds(30))
160 .pollInterval(Duration.ofSeconds(1))
161 .until(() -> !endlessConsumer.running());
163 checkSeenOffsetsForProgress();
164 compareToCommitedOffsets(oldOffsets);
165 assertThat(receivedRecords.size())
166 .describedAs("Received not all sent events")
167 .isLessThan(numberOfGeneratedMessages);
169 assertThatNoException()
170 .describedAs("Consumer should not be running")
171 .isThrownBy(() -> endlessConsumer.exitStatus());
172 assertThat(endlessConsumer.exitStatus())
173 .describedAs("Consumer should have exited abnormally")
174 .containsInstanceOf(RuntimeException.class);
176 recordGenerator.assertBusinessLogic();
180 /** Helper methods for the verification of expectations */
182 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
184 doForCurrentOffsets((tp, offset) ->
186 Long expected = offsetsToCheck.get(tp) + 1;
187 log.debug("Checking, if the offset for {} is {}", tp, expected);
189 .describedAs("Committed offset corresponds to the offset of the consumer")
190 .isEqualTo(expected);
194 void checkSeenOffsetsForProgress()
196 // Be sure, that some messages were consumed...!
197 Set<TopicPartition> withProgress = new HashSet<>();
198 partitions().forEach(tp ->
200 Long oldOffset = oldOffsets.get(tp) + 1;
201 Long newOffset = newOffsets.get(tp) + 1;
202 if (!oldOffset.equals(newOffset))
204 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
205 withProgress.add(tp);
208 assertThat(withProgress)
209 .describedAs("Some offsets must have changed, compared to the old offset-positions")
214 /** Helper methods for setting up and running the tests */
218 offsetConsumer.assign(partitions());
219 offsetConsumer.seekToEnd(partitions());
220 partitions().forEach(tp ->
222 // seekToEnd() works lazily: it only takes effect on poll()/position()
223 Long offset = offsetConsumer.position(tp);
224 log.info("New position for {}: {}", tp, offset);
226 // The new positions must be commited!
227 offsetConsumer.commitSync();
228 offsetConsumer.unsubscribe();
231 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
233 offsetConsumer.assign(partitions());
234 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
235 offsetConsumer.unsubscribe();
238 List<TopicPartition> partitions()
242 .range(0, PARTITIONS)
243 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
244 .collect(Collectors.toList());
248 public interface RecordGenerator
253 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
255 default boolean canGeneratePoisonPill()
260 default boolean canGenerateLogicError()
265 default void assertBusinessLogic()
267 log.debug("No business-logic to assert");
271 void sendMessage(ProducerRecord<Bytes, Bytes> record)
273 testRecordProducer.send(record, (metadata, e) ->
275 if (metadata != null)
279 metadata.partition(),
287 "Exception for {}={}: {}",
300 props = new Properties();
301 props.put("bootstrap.servers", properties.getBootstrapServer());
302 props.put("linger.ms", 100);
303 props.put("key.serializer", BytesSerializer.class.getName());
304 props.put("value.serializer", BytesSerializer.class.getName());
305 testRecordProducer = new KafkaProducer<>(props);
307 props = new Properties();
308 props.put("bootstrap.servers", properties.getBootstrapServer());
309 props.put("client.id", "OFFSET-CONSUMER");
310 props.put("group.id", properties.getGroupId());
311 props.put("key.deserializer", BytesDeserializer.class.getName());
312 props.put("value.deserializer", BytesDeserializer.class.getName());
313 offsetConsumer = new KafkaConsumer<>(props);
317 oldOffsets = new HashMap<>();
318 newOffsets = new HashMap<>();
319 receivedRecords = new HashSet<>();
321 doForCurrentOffsets((tp, offset) ->
323 oldOffsets.put(tp, offset - 1);
324 newOffsets.put(tp, offset - 1);
327 Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
331 new TopicPartition(record.topic(), record.partition()),
333 receivedRecords.add(record);
334 consumer.accept(record);
338 new EndlessConsumer<>(
340 properties.getClientId(),
341 properties.getTopic(),
343 captureOffsetAndExecuteTestHandler);
345 endlessConsumer.start();
353 endlessConsumer.stop();
354 testRecordProducer.close();
355 offsetConsumer.close();
359 log.info("Exception while stopping the consumer: {}", e.toString());
365 @Import(ApplicationConfiguration.class)
366 public static class Configuration