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 RecordHandler recordHandler;
72 Map<TopicPartition, Long> oldOffsets;
73 Map<TopicPartition, Long> newOffsets;
79 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
80 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
82 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
84 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
85 recordHandler.testHandler = record -> received.add(record);
87 await("100 records received")
88 .atMost(Duration.ofSeconds(30))
89 .until(() -> received.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);
117 /** Helper methods for the verification of expectations */
119 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
121 doForCurrentOffsets((tp, offset) ->
123 Long expected = offsetsToCheck.get(tp) + 1;
124 log.debug("Checking, if the offset for {} is {}", tp, expected);
125 assertThat(offset).isEqualTo(expected);
129 void checkSeenOffsetsForProgress()
131 // Be sure, that some messages were consumed...!
132 Set<TopicPartition> withProgress = new HashSet<>();
133 partitions().forEach(tp ->
135 Long oldOffset = oldOffsets.get(tp);
136 Long newOffset = newOffsets.get(tp);
137 if (!oldOffset.equals(newOffset))
139 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
140 withProgress.add(tp);
143 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
147 /** Helper methods for setting up and running the tests */
149 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
151 offsetConsumer.assign(partitions());
152 partitions().forEach(tp -> consumer.accept(tp, offsetConsumer.position(tp)));
153 offsetConsumer.unsubscribe();
156 List<TopicPartition> partitions()
160 .range(0, PARTITIONS)
161 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
162 .collect(Collectors.toList());
166 void send100Messages(Function<Long, Bytes> messageGenerator)
170 for (int partition = 0; partition < 10; partition++)
172 for (int key = 0; key < 10; key++)
174 Bytes value = messageGenerator.apply(++i);
176 ProducerRecord<String, Bytes> record =
177 new ProducerRecord<>(
180 Integer.toString(key%2),
183 kafkaProducer.send(record, (metadata, e) ->
185 if (metadata != null)
189 metadata.partition(),
197 "Exception for {}={}: {}",
211 recordHandler.testHandler = (record) -> {};
213 oldOffsets = new HashMap<>();
214 newOffsets = new HashMap<>();
216 doForCurrentOffsets((tp, offset) ->
218 oldOffsets.put(tp, offset - 1);
219 newOffsets.put(tp, offset - 1);
222 recordHandler.captureOffsets =
225 new TopicPartition(record.topic(), record.partition()),
230 public static class RecordHandler implements Consumer<ConsumerRecord<String, Long>>
232 Consumer<ConsumerRecord<String, Long>> captureOffsets;
233 Consumer<ConsumerRecord<String, Long>> testHandler;
237 public void accept(ConsumerRecord<String, Long> record)
240 .andThen(testHandler)
246 @Import(ApplicationConfiguration.class)
247 public static class Configuration
251 public Consumer<ConsumerRecord<String, Long>> testHandler()
253 return new RecordHandler();
257 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
259 Properties props = new Properties();
260 props.put("bootstrap.servers", properties.getBootstrapServer());
261 props.put("linger.ms", 100);
262 props.put("key.serializer", StringSerializer.class.getName());
263 props.put("value.serializer", BytesSerializer.class.getName());
265 return new KafkaProducer<>(props);
269 KafkaConsumer<Bytes, Bytes> offsetConsumer(ApplicationProperties properties)
271 Properties props = new Properties();
272 props.put("bootstrap.servers", properties.getBootstrapServer());
273 props.put("client.id", "OFFSET-CONSUMER");
274 props.put("group.id", properties.getGroupId());
275 props.put("key.deserializer", BytesDeserializer.class.getName());
276 props.put("value.deserializer", BytesDeserializer.class.getName());
278 return new KafkaConsumer<>(props);