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;
81 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
82 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
84 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
86 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
87 recordHandler.testHandler = record -> received.add(record);
89 await("100 records received")
90 .atMost(Duration.ofSeconds(30))
91 .until(() -> received.size() >= 100);
93 await("Offsets committed")
94 .atMost(Duration.ofSeconds(10))
97 checkSeenOffsetsForProgress();
98 compareToCommitedOffsets(newOffsets);
104 void commitsOffsetOfErrorForReprocessingOnError()
106 send100Messages(counter ->
108 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
109 : new Bytes(longSerializer.serialize(TOPIC, counter)));
111 await("Consumer failed")
112 .atMost(Duration.ofSeconds(30))
113 .untilAsserted(() -> checkSeenOffsetsForProgress());
115 compareToCommitedOffsets(newOffsets);
119 /** Helper methods for the verification of expectations */
121 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
123 doForCurrentOffsets((tp, offset) ->
125 Long expected = offsetsToCheck.get(tp) + 1;
126 log.debug("Checking, if the offset for {} is {}", tp, expected);
127 assertThat(offset).isEqualTo(expected);
131 void checkSeenOffsetsForProgress()
133 // Be sure, that some messages were consumed...!
134 Set<TopicPartition> withProgress = new HashSet<>();
135 partitions().forEach(tp ->
137 Long oldOffset = oldOffsets.get(tp);
138 Long newOffset = newOffsets.get(tp);
139 if (!oldOffset.equals(newOffset))
141 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
142 withProgress.add(tp);
145 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
149 /** Helper methods for setting up and running the tests */
151 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
153 offsetConsumer.assign(partitions());
154 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
155 offsetConsumer.unsubscribe();
158 List<TopicPartition> partitions()
162 .range(0, PARTITIONS)
163 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
164 .collect(Collectors.toList());
168 void send100Messages(Function<Long, Bytes> messageGenerator)
172 for (int partition = 0; partition < 10; partition++)
174 for (int key = 0; key < 10; key++)
176 Bytes value = messageGenerator.apply(++i);
178 ProducerRecord<String, Bytes> record =
179 new ProducerRecord<>(
182 Integer.toString(key%2),
185 kafkaProducer.send(record, (metadata, e) ->
187 if (metadata != null)
191 metadata.partition(),
199 "Exception for {}={}: {}",
213 recordHandler.testHandler = (record) -> {};
215 oldOffsets = new HashMap<>();
216 newOffsets = new HashMap<>();
218 doForCurrentOffsets((tp, offset) ->
220 oldOffsets.put(tp, offset - 1);
221 newOffsets.put(tp, offset - 1);
224 recordHandler.captureOffsets =
227 new TopicPartition(record.topic(), record.partition()),
230 endlessConsumer.start();
238 endlessConsumer.stop();
242 log.info("Exception while stopping the consumer: {}", e.toString());
246 public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
248 Consumer<ConsumerRecord<String, Long>> captureOffsets;
249 Consumer<ConsumerRecord<String, Long>> testHandler;
253 public void accept(ConsumerRecord<String, Long> record)
256 .andThen(testHandler)
262 @Import(ApplicationConfiguration.class)
263 public static class Configuration
267 public Consumer<ConsumerRecord<String, Long>> testHandler()
269 return new RecordHandler();
273 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
275 Properties props = new Properties();
276 props.put("bootstrap.servers", properties.getBootstrapServer());
277 props.put("linger.ms", 100);
278 props.put("key.serializer", StringSerializer.class.getName());
279 props.put("value.serializer", BytesSerializer.class.getName());
281 return new KafkaProducer<>(props);
285 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
287 Properties props = new Properties();
288 props.put("bootstrap.servers", properties.getBootstrapServer());
289 props.put("client.id", "OFFSET-CONSUMER");
290 props.put("group.id", properties.getGroupId());
291 props.put("key.deserializer", BytesDeserializer.class.getName());
292 props.put("value.deserializer", BytesDeserializer.class.getName());
294 return new KafkaConsumer<>(props);