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.WakeupException;
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.MethodOrderer;
15 import org.junit.jupiter.api.Order;
16 import org.junit.jupiter.api.Test;
17 import org.junit.jupiter.api.TestMethodOrder;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
20 import org.springframework.boot.test.context.TestConfiguration;
21 import org.springframework.context.annotation.Bean;
22 import org.springframework.context.annotation.Import;
23 import org.springframework.kafka.test.context.EmbeddedKafka;
24 import org.springframework.test.context.TestPropertySource;
25 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
28 import java.util.concurrent.ExecutorService;
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;
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
44 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45 "consumer.topic=" + TOPIC })
46 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
48 class ApplicationTests
50 public static final String TOPIC = "FOO";
51 public static final int PARTITIONS = 10;
54 StringSerializer stringSerializer = new StringSerializer();
55 LongSerializer longSerializer = new LongSerializer();
58 KafkaProducer<String, Bytes> kafkaProducer;
60 KafkaConsumer<String, Long> kafkaConsumer;
62 ApplicationProperties properties;
64 ExecutorService executor;
66 Map<TopicPartition, Long> oldOffsets;
67 Map<TopicPartition, Long> newOffsets;
71 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
72 void commitsCurrentOffsetsOnSuccess()
74 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
76 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
77 runEndlessConsumer(record ->
80 if (received.size() == 100)
81 throw new WakeupException();
84 checkSeenOffsetsForProgress();
85 compareToCommitedOffsets(newOffsets);
90 void commitsNoOffsetsOnError()
92 send100Messages(counter ->
94 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
95 : new Bytes(longSerializer.serialize(TOPIC, counter)));
97 runEndlessConsumer((record) -> {});
99 checkSeenOffsetsForProgress();
100 compareToCommitedOffsets(oldOffsets);
104 void send100Messages(Function<Long, Bytes> messageGenerator)
108 for (int partition = 0; partition < 10; partition++)
110 for (int key = 0; key < 10; key++)
112 Bytes value = messageGenerator.apply(++i);
114 ProducerRecord<String, Bytes> record =
115 new ProducerRecord<>(
118 Integer.toString(key%2),
121 kafkaProducer.send(record, (metadata, e) ->
123 if (metadata != null)
127 metadata.partition(),
135 "Exception for {}={}: {}",
145 EndlessConsumer<String, Long> runEndlessConsumer(Consumer<ConsumerRecord<String, Long>> consumer)
147 oldOffsets = new HashMap<>();
148 newOffsets = new HashMap<>();
150 doForCurrentOffsets((tp, offset) ->
152 oldOffsets.put(tp, offset - 1);
153 newOffsets.put(tp, offset - 1);
156 Consumer<ConsumerRecord<String, Long>> captureOffset =
159 new TopicPartition(record.topic(), record.partition()),
162 EndlessConsumer<String, Long> endlessConsumer =
163 new EndlessConsumer<>(
165 properties.getClientId(),
166 properties.getTopic(),
168 captureOffset.andThen(consumer));
170 endlessConsumer.run();
172 return endlessConsumer;
175 List<TopicPartition> partitions()
179 .range(0, PARTITIONS)
180 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
181 .collect(Collectors.toList());
184 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
186 kafkaConsumer.assign(partitions());
187 partitions().forEach(tp -> consumer.accept(tp, kafkaConsumer.position(tp)));
188 kafkaConsumer.unsubscribe();
191 void checkSeenOffsetsForProgress()
193 // Be sure, that some messages were consumed...!
194 Set<TopicPartition> withProgress = new HashSet<>();
195 partitions().forEach(tp ->
197 Long oldOffset = oldOffsets.get(tp);
198 Long newOffset = newOffsets.get(tp);
199 if (!oldOffset.equals(newOffset))
201 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
202 withProgress.add(tp);
205 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
208 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
210 doForCurrentOffsets((tp, offset) ->
212 Long expected = offsetsToCheck.get(tp) + 1;
213 log.debug("Checking, if the offset for {} is {}", tp, expected);
214 assertThat(offset).isEqualTo(expected);
220 @Import(ApplicationConfiguration.class)
221 public static class Configuration
224 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
226 Properties props = new Properties();
227 props.put("bootstrap.servers", properties.getBootstrapServer());
228 props.put("linger.ms", 100);
229 props.put("key.serializer", StringSerializer.class.getName());
230 props.put("value.serializer", BytesSerializer.class.getName());
232 return new KafkaProducer<>(props);