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 recordGenerator.generate(100, Set.of(), Set.of(), messageSender);
83 await("100 records received")
84 .atMost(Duration.ofSeconds(30))
85 .pollInterval(Duration.ofSeconds(1))
86 .until(() -> receivedRecords.size() >= 100);
88 await("Offsets committed")
89 .atMost(Duration.ofSeconds(10))
90 .pollInterval(Duration.ofSeconds(1))
93 checkSeenOffsetsForProgress();
94 compareToCommitedOffsets(newOffsets);
97 assertThatExceptionOfType(IllegalStateException.class)
98 .isThrownBy(() -> endlessConsumer.exitStatus())
99 .describedAs("Consumer should still be running");
103 @SkipWhenErrorCannotBeGenerated(poisonPill = true)
104 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
106 recordGenerator.generate(100, Set.of(77), Set.of(), messageSender);
108 await("Consumer failed")
109 .atMost(Duration.ofSeconds(30))
110 .pollInterval(Duration.ofSeconds(1))
111 .until(() -> !endlessConsumer.running());
113 checkSeenOffsetsForProgress();
114 compareToCommitedOffsets(newOffsets);
116 endlessConsumer.start();
117 await("Consumer failed")
118 .atMost(Duration.ofSeconds(30))
119 .pollInterval(Duration.ofSeconds(1))
120 .until(() -> !endlessConsumer.running());
122 checkSeenOffsetsForProgress();
123 compareToCommitedOffsets(newOffsets);
124 assertThat(receivedRecords.size())
125 .describedAs("Received not all sent events")
128 assertThatNoException()
129 .describedAs("Consumer should not be running")
130 .isThrownBy(() -> endlessConsumer.exitStatus());
131 assertThat(endlessConsumer.exitStatus())
132 .describedAs("Consumer should have exited abnormally")
133 .containsInstanceOf(RecordDeserializationException.class);
137 @SkipWhenErrorCannotBeGenerated(logicError = true)
138 void doesNotCommitOffsetsOnLogicError()
140 recordGenerator.generate(100, Set.of(), Set.of(77), messageSender);
142 await("Consumer failed")
143 .atMost(Duration.ofSeconds(30))
144 .pollInterval(Duration.ofSeconds(1))
145 .until(() -> !endlessConsumer.running());
147 checkSeenOffsetsForProgress();
148 compareToCommitedOffsets(oldOffsets);
150 endlessConsumer.start();
151 await("Consumer failed")
152 .atMost(Duration.ofSeconds(30))
153 .pollInterval(Duration.ofSeconds(1))
154 .until(() -> !endlessConsumer.running());
156 checkSeenOffsetsForProgress();
157 compareToCommitedOffsets(oldOffsets);
158 assertThat(receivedRecords.size())
159 .describedAs("Received not all sent events")
162 assertThatNoException()
163 .describedAs("Consumer should not be running")
164 .isThrownBy(() -> endlessConsumer.exitStatus());
165 assertThat(endlessConsumer.exitStatus())
166 .describedAs("Consumer should have exited abnormally")
167 .containsInstanceOf(RuntimeException.class);
171 /** Helper methods for the verification of expectations */
173 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
175 doForCurrentOffsets((tp, offset) ->
177 Long expected = offsetsToCheck.get(tp) + 1;
178 log.debug("Checking, if the offset for {} is {}", tp, expected);
180 .describedAs("Committed offset corresponds to the offset of the consumer")
181 .isEqualTo(expected);
185 void checkSeenOffsetsForProgress()
187 // Be sure, that some messages were consumed...!
188 Set<TopicPartition> withProgress = new HashSet<>();
189 partitions().forEach(tp ->
191 Long oldOffset = oldOffsets.get(tp) + 1;
192 Long newOffset = newOffsets.get(tp) + 1;
193 if (!oldOffset.equals(newOffset))
195 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
196 withProgress.add(tp);
199 assertThat(withProgress)
200 .describedAs("Some offsets must have changed, compared to the old offset-positions")
205 /** Helper methods for setting up and running the tests */
209 offsetConsumer.assign(partitions());
210 offsetConsumer.seekToEnd(partitions());
211 partitions().forEach(tp ->
213 // seekToEnd() works lazily: it only takes effect on poll()/position()
214 Long offset = offsetConsumer.position(tp);
215 log.info("New position for {}: {}", tp, offset);
217 // The new positions must be commited!
218 offsetConsumer.commitSync();
219 offsetConsumer.unsubscribe();
222 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
224 offsetConsumer.assign(partitions());
225 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
226 offsetConsumer.unsubscribe();
229 List<TopicPartition> partitions()
233 .range(0, PARTITIONS)
234 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
235 .collect(Collectors.toList());
239 public interface RecordGenerator
242 int numberOfMessagesToGenerate,
243 Set<Integer> poisonPills,
244 Set<Integer> logicErrors,
245 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
247 default boolean canGeneratePoisionPill()
252 default boolean canGenerateLogicError()
258 void sendMessage(ProducerRecord<Bytes, Bytes> record)
260 testRecordProducer.send(record, (metadata, e) ->
262 if (metadata != null)
266 metadata.partition(),
274 "Exception for {}={}: {}",
287 props = new Properties();
288 props.put("bootstrap.servers", properties.getBootstrapServer());
289 props.put("linger.ms", 100);
290 props.put("key.serializer", BytesSerializer.class.getName());
291 props.put("value.serializer", BytesSerializer.class.getName());
292 testRecordProducer = new KafkaProducer<>(props);
294 props = new Properties();
295 props.put("bootstrap.servers", properties.getBootstrapServer());
296 props.put("client.id", "OFFSET-CONSUMER");
297 props.put("group.id", properties.getGroupId());
298 props.put("key.deserializer", BytesDeserializer.class.getName());
299 props.put("value.deserializer", BytesDeserializer.class.getName());
300 offsetConsumer = new KafkaConsumer<>(props);
304 oldOffsets = new HashMap<>();
305 newOffsets = new HashMap<>();
306 receivedRecords = new HashSet<>();
308 doForCurrentOffsets((tp, offset) ->
310 oldOffsets.put(tp, offset - 1);
311 newOffsets.put(tp, offset - 1);
314 Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
318 new TopicPartition(record.topic(), record.partition()),
320 receivedRecords.add(record);
321 consumer.accept(record);
325 new EndlessConsumer<>(
327 properties.getClientId(),
328 properties.getTopic(),
330 captureOffsetAndExecuteTestHandler);
332 endlessConsumer.start();
340 endlessConsumer.stop();
341 testRecordProducer.close();
342 offsetConsumer.close();
346 log.info("Exception while stopping the consumer: {}", e.toString());
352 @Import(ApplicationConfiguration.class)
353 public static class Configuration