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.*;
10 import org.apache.kafka.common.utils.Bytes;
11 import org.junit.jupiter.api.*;
12 import org.springframework.beans.factory.annotation.Autowired;
13 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
14 import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo;
15 import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
16 import org.springframework.boot.test.context.TestConfiguration;
17 import org.springframework.context.annotation.Bean;
18 import org.springframework.context.annotation.Import;
19 import org.springframework.kafka.test.context.EmbeddedKafka;
20 import org.springframework.test.context.TestPropertySource;
21 import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
23 import java.time.Clock;
24 import java.time.Duration;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.function.BiConsumer;
29 import java.util.function.Consumer;
30 import java.util.function.Function;
31 import java.util.stream.Collectors;
32 import java.util.stream.IntStream;
34 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
35 import static de.juplo.kafka.ApplicationTests.TOPIC;
36 import static org.assertj.core.api.Assertions.*;
37 import static org.awaitility.Awaitility.*;
40 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
41 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
44 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
45 "consumer.topic=" + TOPIC,
46 "consumer.commit-interval=1s",
47 "spring.mongodb.embedded.version=4.4.13" })
48 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
49 @EnableAutoConfiguration
50 @AutoConfigureDataMongo
52 class ApplicationTests
54 public static final String TOPIC = "FOO";
55 public static final int PARTITIONS = 10;
58 StringSerializer stringSerializer = new StringSerializer();
61 Serializer valueSerializer;
63 KafkaProducer<String, Bytes> kafkaProducer;
65 KafkaConsumer<String, String> kafkaConsumer;
67 PartitionStatisticsRepository partitionStatisticsRepository;
69 ApplicationProperties properties;
71 ExecutorService executor;
73 PartitionStatisticsRepository repository;
75 Consumer<ConsumerRecord<String, String>> testHandler;
76 EndlessConsumer<String, String> endlessConsumer;
77 Map<TopicPartition, Long> oldOffsets;
78 Map<TopicPartition, Long> newOffsets;
79 Set<ConsumerRecord<String, String>> receivedRecords;
85 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
87 send100Messages(i -> new Bytes(valueSerializer.serialize(TOPIC, i)));
89 await("100 records received")
90 .atMost(Duration.ofSeconds(30))
91 .until(() -> receivedRecords.size() >= 100);
93 await("Offsets committed")
94 .atMost(Duration.ofSeconds(10))
97 checkSeenOffsetsForProgress();
98 compareToCommitedOffsets(newOffsets);
101 assertThatExceptionOfType(IllegalStateException.class)
102 .isThrownBy(() -> endlessConsumer.exitStatus())
103 .describedAs("Consumer should still be running");
107 /** Helper methods for the verification of expectations */
109 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
111 doForCurrentOffsets((tp, offset) ->
113 Long expected = offsetsToCheck.get(tp) + 1;
114 log.debug("Checking, if the offset for {} is {}", tp, expected);
116 .describedAs("Committed offset corresponds to the offset of the consumer")
117 .isEqualTo(expected);
121 void checkSeenOffsetsForProgress()
123 // Be sure, that some messages were consumed...!
124 Set<TopicPartition> withProgress = new HashSet<>();
125 partitions().forEach(tp ->
127 Long oldOffset = oldOffsets.get(tp);
128 Long newOffset = newOffsets.get(tp);
129 if (!oldOffset.equals(newOffset))
131 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
132 withProgress.add(tp);
135 assertThat(withProgress)
136 .describedAs("Some offsets must have changed, compared to the old offset-positions")
141 /** Helper methods for setting up and running the tests */
143 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
145 partitions().forEach(tp ->
147 String partition = Integer.toString(tp.partition());
148 Optional<Long> offset = partitionStatisticsRepository.findById(partition).map(document -> document.offset);
149 consumer.accept(tp, offset.orElse(0l));
153 List<TopicPartition> partitions()
157 .range(0, PARTITIONS)
158 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
159 .collect(Collectors.toList());
163 void send100Messages(Function<Long, Bytes> messageGenerator)
167 for (int partition = 0; partition < 10; partition++)
169 for (int key = 0; key < 10; key++)
171 Bytes value = messageGenerator.apply(++i);
173 ProducerRecord<String, Bytes> record =
174 new ProducerRecord<>(
177 Integer.toString(key%2),
180 kafkaProducer.send(record, (metadata, e) ->
182 if (metadata != null)
186 metadata.partition(),
194 "Exception for {}={}: {}",
208 testHandler = record -> {} ;
210 oldOffsets = new HashMap<>();
211 newOffsets = new HashMap<>();
212 receivedRecords = new HashSet<>();
214 doForCurrentOffsets((tp, offset) ->
216 oldOffsets.put(tp, offset - 1);
217 newOffsets.put(tp, offset - 1);
220 Consumer<ConsumerRecord<String, String>> captureOffsetAndExecuteTestHandler =
224 new TopicPartition(record.topic(), record.partition()),
226 receivedRecords.add(record);
227 testHandler.accept(record);
231 new EndlessConsumer<>(
234 properties.getClientId(),
235 properties.getTopic(),
236 Clock.systemDefaultZone(),
237 properties.getCommitInterval(),
239 captureOffsetAndExecuteTestHandler);
241 endlessConsumer.start();
249 endlessConsumer.stop();
253 log.info("Exception while stopping the consumer: {}", e.toString());
259 @Import(ApplicationConfiguration.class)
260 public static class Configuration
263 Serializer<Long> serializer()
265 return new LongSerializer();
269 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
271 Properties props = new Properties();
272 props.put("bootstrap.servers", properties.getBootstrapServer());
273 props.put("linger.ms", 100);
274 props.put("key.serializer", StringSerializer.class.getName());
275 props.put("value.serializer", BytesSerializer.class.getName());
277 return new KafkaProducer<>(props);