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.serialization.BytesDeserializer;
10 import org.apache.kafka.common.serialization.BytesSerializer;
11 import org.apache.kafka.common.serialization.LongSerializer;
12 import org.apache.kafka.common.serialization.StringSerializer;
13 import org.apache.kafka.common.utils.Bytes;
14 import org.junit.jupiter.api.*;
15 import org.springframework.beans.factory.annotation.Autowired;
16 import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
17 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
18 import org.springframework.boot.test.context.TestConfiguration;
19 import org.springframework.context.annotation.Bean;
20 import org.springframework.context.annotation.Import;
21 import org.springframework.context.annotation.Primary;
22 import org.springframework.kafka.test.context.EmbeddedKafka;
23 import org.springframework.test.context.TestPropertySource;
24 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26 import java.time.Duration;
28 import java.util.concurrent.ExecutionException;
29 import java.util.function.BiConsumer;
30 import java.util.function.Consumer;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import java.util.stream.IntStream;
35 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
36 import static de.juplo.kafka.ApplicationTests.TOPIC;
37 import static org.assertj.core.api.Assertions.assertThat;
38 import static org.awaitility.Awaitility.*;
42 initializers = ConfigDataApplicationContextInitializer.class,
44 EndlessConsumer.class,
45 KafkaAutoConfiguration.class,
46 ApplicationTests.Configuration.class })
47 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
50 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
51 "consumer.topic=" + TOPIC })
52 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
54 class ApplicationTests
56 public static final String TOPIC = "FOO";
57 public static final int PARTITIONS = 10;
60 StringSerializer stringSerializer = new StringSerializer();
61 LongSerializer longSerializer = new LongSerializer();
64 KafkaProducer<String, Bytes> kafkaProducer;
66 KafkaConsumer<Bytes, Bytes> offsetConsumer;
68 ApplicationProperties properties;
70 EndlessConsumer endlessConsumer;
72 RecordHandler recordHandler;
74 Map<TopicPartition, Long> oldOffsets;
75 Map<TopicPartition, Long> newOffsets;
76 Set<ConsumerRecord<String, Long>> receivedRecords;
82 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
83 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
85 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
87 await("100 records received")
88 .atMost(Duration.ofSeconds(30))
89 .until(() -> receivedRecords.size() >= 100);
91 await("Offsets committed")
92 .atMost(Duration.ofSeconds(10))
95 checkSeenOffsetsForProgress();
96 compareToCommitedOffsets(newOffsets);
102 void commitsOffsetOfErrorForReprocessingOnError()
104 send100Messages(counter ->
106 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
107 : new Bytes(longSerializer.serialize(TOPIC, counter)));
109 await("Consumer failed")
110 .atMost(Duration.ofSeconds(30))
111 .untilAsserted(() -> checkSeenOffsetsForProgress());
113 compareToCommitedOffsets(newOffsets);
114 assertThat(receivedRecords.size())
115 .describedAs("Received not all sent events")
120 /** Helper methods for the verification of expectations */
122 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
124 doForCurrentOffsets((tp, offset) ->
126 Long expected = offsetsToCheck.get(tp) + 1;
127 log.debug("Checking, if the offset for {} is {}", tp, expected);
129 .describedAs("Committed offset corresponds to the offset of the consumer")
130 .isEqualTo(expected);
134 void checkSeenOffsetsForProgress()
136 // Be sure, that some messages were consumed...!
137 Set<TopicPartition> withProgress = new HashSet<>();
138 partitions().forEach(tp ->
140 Long oldOffset = oldOffsets.get(tp);
141 Long newOffset = newOffsets.get(tp);
142 if (!oldOffset.equals(newOffset))
144 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
145 withProgress.add(tp);
148 assertThat(withProgress)
149 .describedAs("Some offsets must have changed, compared to the old offset-positions")
154 /** Helper methods for setting up and running the tests */
156 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
158 offsetConsumer.assign(partitions());
159 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
160 offsetConsumer.unsubscribe();
163 List<TopicPartition> partitions()
167 .range(0, PARTITIONS)
168 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
169 .collect(Collectors.toList());
173 void send100Messages(Function<Long, Bytes> messageGenerator)
177 for (int partition = 0; partition < 10; partition++)
179 for (int key = 0; key < 10; key++)
181 Bytes value = messageGenerator.apply(++i);
183 ProducerRecord<String, Bytes> record =
184 new ProducerRecord<>(
187 Integer.toString(key%2),
190 kafkaProducer.send(record, (metadata, e) ->
192 if (metadata != null)
196 metadata.partition(),
204 "Exception for {}={}: {}",
218 recordHandler.testHandler = (record) -> {};
220 oldOffsets = new HashMap<>();
221 newOffsets = new HashMap<>();
222 receivedRecords = new HashSet<>();
224 doForCurrentOffsets((tp, offset) ->
226 oldOffsets.put(tp, offset - 1);
227 newOffsets.put(tp, offset - 1);
230 recordHandler.captureOffsets =
233 receivedRecords.add(record);
235 new TopicPartition(record.topic(), record.partition()),
239 endlessConsumer.start();
247 endlessConsumer.stop();
251 log.info("Exception while stopping the consumer: {}", e.toString());
255 public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
257 Consumer<ConsumerRecord<String, Long>> captureOffsets;
258 Consumer<ConsumerRecord<String, Long>> testHandler;
262 public void accept(ConsumerRecord<String, Long> record)
265 .andThen(testHandler)
271 @Import(ApplicationConfiguration.class)
272 public static class Configuration
276 public Consumer<ConsumerRecord<String, Long>> testHandler()
278 return new RecordHandler();
282 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
284 Properties props = new Properties();
285 props.put("bootstrap.servers", properties.getBootstrapServer());
286 props.put("linger.ms", 100);
287 props.put("key.serializer", StringSerializer.class.getName());
288 props.put("value.serializer", BytesSerializer.class.getName());
290 return new KafkaProducer<>(props);
294 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
296 Properties props = new Properties();
297 props.put("bootstrap.servers", properties.getBootstrapServer());
298 props.put("client.id", "OFFSET-CONSUMER");
299 props.put("group.id", properties.getGroupId());
300 props.put("key.deserializer", BytesDeserializer.class.getName());
301 props.put("value.deserializer", BytesDeserializer.class.getName());
303 return new KafkaConsumer<>(props);