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;
68 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
69 void commitsCurrentOffsetsOnSuccess()
71 send100Messages(i -> new Bytes(longSerializer.serialize(TOPIC, i)));
73 Map<TopicPartition, Long> oldOffsets = new HashMap<>();
74 doForCurrentOffsets((tp, offset) -> oldOffsets.put(tp, offset -1));
75 Set<ConsumerRecord<String, Long>> received = new HashSet<>();
76 Map<TopicPartition, Long> newOffsets = runEndlessConsumer(record ->
79 if (received.size() == 100)
80 throw new WakeupException();
83 Set<TopicPartition> withProgress = new HashSet<>();
84 partitions().forEach(tp ->
86 Long oldOffset = oldOffsets.get(tp);
87 Long newOffset = newOffsets.get(tp);
88 if (!oldOffset.equals(newOffset))
90 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
94 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
101 void commitsNoOffsetsOnError()
103 send100Messages(counter ->
105 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
106 : new Bytes(longSerializer.serialize(TOPIC, counter)));
108 Map<TopicPartition, Long> oldOffsets = new HashMap<>();
109 doForCurrentOffsets((tp, offset) -> oldOffsets.put(tp, offset -1));
110 Map<TopicPartition, Long> newOffsets = runEndlessConsumer((record) -> {});
112 Set<TopicPartition> withProgress = new HashSet<>();
113 partitions().forEach(tp ->
115 Long oldOffset = oldOffsets.get(tp);
116 Long newOffset = newOffsets.get(tp);
117 if (!oldOffset.equals(newOffset))
119 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
120 withProgress.add(tp);
123 assertThat(withProgress).isNotEmpty().describedAs("Found no partitions with any offset-progress");
129 void send100Messages(Function<Long, Bytes> messageGenerator)
133 for (int partition = 0; partition < 10; partition++)
135 for (int key = 0; key < 10; key++)
137 Bytes value = messageGenerator.apply(++i);
139 ProducerRecord<String, Bytes> record =
140 new ProducerRecord<>(
143 Integer.toString(key%2),
146 kafkaProducer.send(record, (metadata, e) ->
148 if (metadata != null)
152 metadata.partition(),
160 "Exception for {}={}: {}",
170 Map<TopicPartition, Long> runEndlessConsumer(Consumer<ConsumerRecord<String, Long>> consumer)
172 Map<TopicPartition, Long> offsets = new HashMap<>();
173 doForCurrentOffsets((tp, offset) -> offsets.put(tp, offset -1));
174 Consumer<ConsumerRecord<String, Long>> captureOffset =
177 new TopicPartition(record.topic(), record.partition()),
179 EndlessConsumer<String, Long> endlessConsumer =
180 new EndlessConsumer<>(
182 properties.getClientId(),
183 properties.getTopic(),
185 captureOffset.andThen(consumer));
187 endlessConsumer.run();
192 List<TopicPartition> partitions()
196 .range(0, PARTITIONS)
197 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
198 .collect(Collectors.toList());
201 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
203 kafkaConsumer.assign(partitions());
204 partitions().forEach(tp -> consumer.accept(tp, kafkaConsumer.position(tp)));
205 kafkaConsumer.unsubscribe();
208 void check(Map<TopicPartition, Long> offsets)
210 doForCurrentOffsets((tp, offset) ->
212 Long expected = offsets.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);