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<K, 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 Serializer<K> keySerializer;
66 final RecordGenerator<K> recordGenerator;
67 final Consumer<ProducerRecord<K, Bytes>> messageSender;
69 public GenericApplicationTest(
70 Serializer<K> keySerializer,
71 RecordGenerator<K> recordGenerator)
73 this.keySerializer = keySerializer;
74 this.recordGenerator = recordGenerator;
75 this.messageSender = (record) -> sendMessage(record);
82 void commitsCurrentOffsetsOnSuccess()
84 recordGenerator.generate(100, Set.of(), messageSender);
86 await("100 records received")
87 .atMost(Duration.ofSeconds(30))
88 .pollInterval(Duration.ofSeconds(1))
89 .until(() -> receivedRecords.size() >= 100);
91 await("Offsets committed")
92 .atMost(Duration.ofSeconds(10))
93 .pollInterval(Duration.ofSeconds(1))
96 checkSeenOffsetsForProgress();
97 compareToCommitedOffsets(newOffsets);
100 assertThatExceptionOfType(IllegalStateException.class)
101 .isThrownBy(() -> endlessConsumer.exitStatus())
102 .describedAs("Consumer should still be running");
106 void commitsOffsetOfErrorForReprocessingOnDeserializationError()
108 recordGenerator.generate(100, Set.of(77), messageSender);
110 await("Consumer failed")
111 .atMost(Duration.ofSeconds(30))
112 .pollInterval(Duration.ofSeconds(1))
113 .until(() -> !endlessConsumer.running());
115 checkSeenOffsetsForProgress();
116 compareToCommitedOffsets(newOffsets);
118 endlessConsumer.start();
119 await("Consumer failed")
120 .atMost(Duration.ofSeconds(30))
121 .pollInterval(Duration.ofSeconds(1))
122 .until(() -> !endlessConsumer.running());
124 checkSeenOffsetsForProgress();
125 compareToCommitedOffsets(newOffsets);
126 assertThat(receivedRecords.size())
127 .describedAs("Received not all sent events")
130 assertThatNoException()
131 .describedAs("Consumer should not be running")
132 .isThrownBy(() -> endlessConsumer.exitStatus());
133 assertThat(endlessConsumer.exitStatus())
134 .describedAs("Consumer should have exited abnormally")
135 .containsInstanceOf(RecordDeserializationException.class);
139 /** Helper methods for the verification of expectations */
141 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
143 doForCurrentOffsets((tp, offset) ->
145 Long expected = offsetsToCheck.get(tp) + 1;
146 log.debug("Checking, if the offset for {} is {}", tp, expected);
148 .describedAs("Committed offset corresponds to the offset of the consumer")
149 .isEqualTo(expected);
153 void checkSeenOffsetsForProgress()
155 // Be sure, that some messages were consumed...!
156 Set<TopicPartition> withProgress = new HashSet<>();
157 partitions().forEach(tp ->
159 Long oldOffset = oldOffsets.get(tp) + 1;
160 Long newOffset = newOffsets.get(tp) + 1;
161 if (!oldOffset.equals(newOffset))
163 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
164 withProgress.add(tp);
167 assertThat(withProgress)
168 .describedAs("Some offsets must have changed, compared to the old offset-positions")
173 /** Helper methods for setting up and running the tests */
177 offsetConsumer.assign(partitions());
178 offsetConsumer.seekToEnd(partitions());
179 partitions().forEach(tp ->
181 // seekToEnd() works lazily: it only takes effect on poll()/position()
182 Long offset = offsetConsumer.position(tp);
183 log.info("New position for {}: {}", tp, offset);
185 // The new positions must be commited!
186 offsetConsumer.commitSync();
187 offsetConsumer.unsubscribe();
190 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
192 offsetConsumer.assign(partitions());
193 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
194 offsetConsumer.unsubscribe();
197 List<TopicPartition> partitions()
201 .range(0, PARTITIONS)
202 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
203 .collect(Collectors.toList());
207 public interface RecordGenerator<K>
210 int numberOfMessagesToGenerate,
211 Set<Integer> poistionPills,
212 Consumer<ProducerRecord<K, Bytes>> messageSender);
215 void sendMessage(ProducerRecord<K, Bytes> record)
217 testRecordProducer.send(record, (metadata, e) ->
219 if (metadata != null)
223 metadata.partition(),
231 "Exception for {}={}: {}",
244 props = new Properties();
245 props.put("bootstrap.servers", properties.getBootstrapServer());
246 props.put("linger.ms", 100);
247 props.put("key.serializer", keySerializer.getClass().getName());
248 props.put("value.serializer", BytesSerializer.class.getName());
249 testRecordProducer = new KafkaProducer<>(props);
251 props = new Properties();
252 props.put("bootstrap.servers", properties.getBootstrapServer());
253 props.put("client.id", "OFFSET-CONSUMER");
254 props.put("group.id", properties.getGroupId());
255 props.put("key.deserializer", BytesDeserializer.class.getName());
256 props.put("value.deserializer", BytesDeserializer.class.getName());
257 offsetConsumer = new KafkaConsumer<>(props);
259 testHandler = record -> {} ;
263 oldOffsets = new HashMap<>();
264 newOffsets = new HashMap<>();
265 receivedRecords = new HashSet<>();
267 doForCurrentOffsets((tp, offset) ->
269 oldOffsets.put(tp, offset - 1);
270 newOffsets.put(tp, offset - 1);
273 Consumer<ConsumerRecord<K, V>> captureOffsetAndExecuteTestHandler =
277 new TopicPartition(record.topic(), record.partition()),
279 receivedRecords.add(record);
280 testHandler.accept(record);
284 new EndlessConsumer<>(
286 properties.getClientId(),
287 properties.getTopic(),
289 captureOffsetAndExecuteTestHandler);
291 endlessConsumer.start();
299 endlessConsumer.stop();
300 testRecordProducer.close();
301 offsetConsumer.close();
305 log.info("Exception while stopping the consumer: {}", e.toString());
311 @Import(ApplicationConfiguration.class)
312 public static class Configuration {}