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.RecordDeserializationException;
10 import org.apache.kafka.common.serialization.*;
11 import org.apache.kafka.common.utils.Bytes;
12 import org.junit.jupiter.api.*;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
15 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
16 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
17 import org.springframework.boot.test.context.TestConfiguration;
18 import org.springframework.context.annotation.Bean;
19 import org.springframework.context.annotation.Import;
20 import org.springframework.kafka.test.context.EmbeddedKafka;
21 import org.springframework.test.context.TestPropertySource;
22 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
24 import java.time.Clock;
25 import java.time.Duration;
27 import java.util.concurrent.ExecutionException;
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.*;
38 import static org.awaitility.Awaitility.*;
41 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
42 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
45 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
46 "consumer.topic=" + TOPIC,
47 "consumer.commit-interval=1s",
48 "spring.mongodb.embedded.version=4.4.13" })
49 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
50 @EnableAutoConfiguration
51 @AutoConfigureDataMongo
53 class ApplicationTests
55 public static final String TOPIC = "FOO";
56 public static final int PARTITIONS = 10;
59 StringSerializer stringSerializer = new StringSerializer();
62 Serializer valueSerializer;
64 KafkaProducer<String, Bytes> kafkaProducer;
66 KafkaConsumer<String, Long> kafkaConsumer;
68 PartitionStatisticsRepository partitionStatisticsRepository;
70 ApplicationProperties properties;
72 ExecutorService executor;
74 PartitionStatisticsRepository repository;
76 Consumer<ConsumerRecord<String, Long>> testHandler;
77 EndlessConsumer<String, Long> endlessConsumer;
78 Map<TopicPartition, Long> oldOffsets;
79 Map<TopicPartition, Long> newOffsets;
80 Set<ConsumerRecord<String, Long>> receivedRecords;
86 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
87 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
89 send100Messages(i -> new Bytes(valueSerializer.serialize(TOPIC, i)));
91 await("100 records received")
92 .atMost(Duration.ofSeconds(30))
93 .until(() -> receivedRecords.size() >= 100);
95 await("Offsets committed")
96 .atMost(Duration.ofSeconds(10))
99 checkSeenOffsetsForProgress();
100 compareToCommitedOffsets(newOffsets);
103 assertThatExceptionOfType(IllegalStateException.class)
104 .isThrownBy(() -> endlessConsumer.exitStatus())
105 .describedAs("Consumer should still be running");
110 void commitsOffsetOfErrorForReprocessingOnError()
112 send100Messages(counter ->
114 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
115 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
117 await("Consumer failed")
118 .atMost(Duration.ofSeconds(30))
119 .until(() -> !endlessConsumer.running());
121 checkSeenOffsetsForProgress();
122 compareToCommitedOffsets(newOffsets);
124 endlessConsumer.start();
125 await("Consumer failed")
126 .atMost(Duration.ofSeconds(30))
127 .until(() -> !endlessConsumer.running());
129 checkSeenOffsetsForProgress();
130 compareToCommitedOffsets(newOffsets);
131 assertThat(receivedRecords.size())
132 .describedAs("Received not all sent events")
135 assertThatNoException()
136 .describedAs("Consumer should not be running")
137 .isThrownBy(() -> endlessConsumer.exitStatus());
138 assertThat(endlessConsumer.exitStatus())
139 .describedAs("Consumer should have exited abnormally")
140 .containsInstanceOf(RecordDeserializationException.class);
144 /** Helper methods for the verification of expectations */
146 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
148 doForCurrentOffsets((tp, offset) ->
150 Long expected = offsetsToCheck.get(tp) + 1;
151 log.debug("Checking, if the offset for {} is {}", tp, expected);
153 .describedAs("Committed offset corresponds to the offset of the consumer")
154 .isEqualTo(expected);
158 void checkSeenOffsetsForProgress()
160 // Be sure, that some messages were consumed...!
161 Set<TopicPartition> withProgress = new HashSet<>();
162 partitions().forEach(tp ->
164 Long oldOffset = oldOffsets.get(tp);
165 Long newOffset = newOffsets.get(tp);
166 if (!oldOffset.equals(newOffset))
168 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
169 withProgress.add(tp);
172 assertThat(withProgress)
173 .describedAs("Some offsets must have changed, compared to the old offset-positions")
178 /** Helper methods for setting up and running the tests */
180 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
182 partitions().forEach(tp ->
184 String partition = Integer.toString(tp.partition());
185 Optional<Long> offset = partitionStatisticsRepository.findById(partition).map(document -> document.offset);
186 consumer.accept(tp, offset.orElse(0l));
190 List<TopicPartition> partitions()
194 .range(0, PARTITIONS)
195 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
196 .collect(Collectors.toList());
200 void send100Messages(Function<Long, Bytes> messageGenerator)
204 for (int partition = 0; partition < 10; partition++)
206 for (int key = 0; key < 10; key++)
208 Bytes value = messageGenerator.apply(++i);
210 ProducerRecord<String, Bytes> record =
211 new ProducerRecord<>(
214 Integer.toString(key%2),
217 kafkaProducer.send(record, (metadata, e) ->
219 if (metadata != null)
223 metadata.partition(),
231 "Exception for {}={}: {}",
245 testHandler = record -> {} ;
247 oldOffsets = new HashMap<>();
248 newOffsets = new HashMap<>();
249 receivedRecords = new HashSet<>();
251 doForCurrentOffsets((tp, offset) ->
253 oldOffsets.put(tp, offset - 1);
254 newOffsets.put(tp, offset - 1);
257 Consumer<ConsumerRecord<String, Long>> captureOffsetAndExecuteTestHandler =
261 new TopicPartition(record.topic(), record.partition()),
263 receivedRecords.add(record);
264 testHandler.accept(record);
268 new EndlessConsumer<>(
271 properties.getClientId(),
272 properties.getTopic(),
273 Clock.systemDefaultZone(),
274 properties.getCommitInterval(),
276 captureOffsetAndExecuteTestHandler);
278 endlessConsumer.start();
286 endlessConsumer.stop();
290 log.info("Exception while stopping the consumer: {}", e.toString());
296 @Import(ApplicationConfiguration.class)
297 public static class Configuration
300 Serializer<Long> serializer()
302 return new LongSerializer();
306 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
308 Properties props = new Properties();
309 props.put("bootstrap.servers", properties.getBootstrapServer());
310 props.put("linger.ms", 100);
311 props.put("key.serializer", StringSerializer.class.getName());
312 props.put("value.serializer", BytesSerializer.class.getName());
314 return new KafkaProducer<>(props);