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.GenericApplicationTest.PARTITIONS;
30 import static de.juplo.kafka.GenericApplicationTest.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 GenericApplicationTest<K, V>
45 public static final String TOPIC = "FOO";
46 public static final int PARTITIONS = 10;
50 KafkaConsumer<K, V> kafkaConsumer;
52 ApplicationProperties properties;
54 ExecutorService executor;
56 KafkaProducer<Bytes, Bytes> testRecordProducer;
57 KafkaConsumer<Bytes, Bytes> offsetConsumer;
58 Consumer<ConsumerRecord<K, V>> testHandler;
59 EndlessConsumer<K, V> endlessConsumer;
60 Map<TopicPartition, Long> oldOffsets;
61 Map<TopicPartition, Long> newOffsets;
62 Set<ConsumerRecord<K, V>> receivedRecords;
65 final RecordGenerator recordGenerator;
66 final Consumer<ProducerRecord<Bytes, Bytes>> messageSender;
68 public GenericApplicationTest(RecordGenerator recordGenerator)
70 this.recordGenerator = recordGenerator;
71 this.messageSender = (record) -> sendMessage(record);
78 void commitsCurrentOffsetsOnSuccess()
80 recordGenerator.generate(100, Set.of(), messageSender);
82 await("100 records received")
83 .atMost(Duration.ofSeconds(30))
84 .pollInterval(Duration.ofSeconds(1))
85 .until(() -> receivedRecords.size() >= 100);
87 await("Offsets committed")
88 .atMost(Duration.ofSeconds(10))
89 .pollInterval(Duration.ofSeconds(1))
92 checkSeenOffsetsForProgress();
93 compareToCommitedOffsets(newOffsets);
96 assertThatExceptionOfType(IllegalStateException.class)
97 .isThrownBy(() -> endlessConsumer.exitStatus())
98 .describedAs("Consumer should still be running");
102 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
104 recordGenerator.generate(100, Set.of(77), messageSender);
106 await("Consumer failed")
107 .atMost(Duration.ofSeconds(30))
108 .pollInterval(Duration.ofSeconds(1))
109 .until(() -> !endlessConsumer.running());
111 checkSeenOffsetsForProgress();
112 compareToCommitedOffsets(newOffsets);
114 endlessConsumer.start();
115 await("Consumer failed")
116 .atMost(Duration.ofSeconds(30))
117 .pollInterval(Duration.ofSeconds(1))
118 .until(() -> !endlessConsumer.running());
120 checkSeenOffsetsForProgress();
121 compareToCommitedOffsets(newOffsets);
122 assertThat(receivedRecords.size())
123 .describedAs("Received not all sent events")
126 assertThatNoException()
127 .describedAs("Consumer should not be running")
128 .isThrownBy(() -> endlessConsumer.exitStatus());
129 assertThat(endlessConsumer.exitStatus())
130 .describedAs("Consumer should have exited abnormally")
131 .containsInstanceOf(RecordDeserializationException.class);
135 /** Helper methods for the verification of expectations */
137 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
139 doForCurrentOffsets((tp, offset) ->
141 Long expected = offsetsToCheck.get(tp) + 1;
142 log.debug("Checking, if the offset for {} is {}", tp, expected);
144 .describedAs("Committed offset corresponds to the offset of the consumer")
145 .isEqualTo(expected);
149 void checkSeenOffsetsForProgress()
151 // Be sure, that some messages were consumed...!
152 Set<TopicPartition> withProgress = new HashSet<>();
153 partitions().forEach(tp ->
155 Long oldOffset = oldOffsets.get(tp) + 1;
156 Long newOffset = newOffsets.get(tp) + 1;
157 if (!oldOffset.equals(newOffset))
159 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
160 withProgress.add(tp);
163 assertThat(withProgress)
164 .describedAs("Some offsets must have changed, compared to the old offset-positions")
169 /** Helper methods for setting up and running the tests */
173 offsetConsumer.assign(partitions());
174 offsetConsumer.seekToEnd(partitions());
175 partitions().forEach(tp ->
177 // seekToEnd() works lazily: it only takes effect on poll()/position()
178 Long offset = offsetConsumer.position(tp);
179 log.info("New position for {}: {}", tp, offset);
181 // The new positions must be commited!
182 offsetConsumer.commitSync();
183 offsetConsumer.unsubscribe();
186 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
188 offsetConsumer.assign(partitions());
189 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
190 offsetConsumer.unsubscribe();
193 List<TopicPartition> partitions()
197 .range(0, PARTITIONS)
198 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
199 .collect(Collectors.toList());
203 public interface RecordGenerator
206 int numberOfMessagesToGenerate,
207 Set<Integer> poistionPills,
208 Consumer<ProducerRecord<Bytes, Bytes>> messageSender);
211 void sendMessage(ProducerRecord<Bytes, Bytes> record)
213 testRecordProducer.send(record, (metadata, e) ->
215 if (metadata != null)
219 metadata.partition(),
227 "Exception for {}={}: {}",
240 props = new Properties();
241 props.put("bootstrap.servers", properties.getBootstrapServer());
242 props.put("linger.ms", 100);
243 props.put("key.serializer", BytesSerializer.class.getName());
244 props.put("value.serializer", BytesSerializer.class.getName());
245 testRecordProducer = new KafkaProducer<>(props);
247 props = new Properties();
248 props.put("bootstrap.servers", properties.getBootstrapServer());
249 props.put("client.id", "OFFSET-CONSUMER");
250 props.put("group.id", properties.getGroupId());
251 props.put("key.deserializer", BytesDeserializer.class.getName());
252 props.put("value.deserializer", BytesDeserializer.class.getName());
253 offsetConsumer = new KafkaConsumer<>(props);
255 testHandler = record -> {} ;
259 oldOffsets = new HashMap<>();
260 newOffsets = new HashMap<>();
261 receivedRecords = new HashSet<>();
263 doForCurrentOffsets((tp, offset) ->
265 oldOffsets.put(tp, offset - 1);
266 newOffsets.put(tp, offset - 1);
269 Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
273 new TopicPartition(record.topic(), record.partition()),
275 receivedRecords.add(record);
276 testHandler.accept(record);
280 new EndlessConsumer<>(
282 properties.getClientId(),
283 properties.getTopic(),
285 captureOffsetAndExecuteTestHandler);
287 endlessConsumer.start();
295 endlessConsumer.stop();
296 testRecordProducer.close();
297 offsetConsumer.close();
301 log.info("Exception while stopping the consumer: {}", e.toString());
307 @Import(ApplicationConfiguration.class)
308 public static class Configuration {}