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.Function;
30 import java.util.stream.Collectors;
31 import java.util.stream.IntStream;
33 import static de.juplo.kafka.ApplicationTests.PARTITIONS;
34 import static de.juplo.kafka.ApplicationTests.TOPIC;
35 import static org.assertj.core.api.Assertions.*;
36 import static org.awaitility.Awaitility.*;
39 @SpringJUnitConfig(initializers = ConfigDataApplicationContextInitializer.class)
40 @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
43 "consumer.bootstrap-server=${spring.embedded.kafka.brokers}",
44 "consumer.topic=" + TOPIC,
45 "consumer.commit-interval=1s",
46 "spring.mongodb.embedded.version=4.4.13" })
47 @EmbeddedKafka(topics = TOPIC, partitions = PARTITIONS)
48 @EnableAutoConfiguration
49 @AutoConfigureDataMongo
51 class ApplicationTests
53 public static final String TOPIC = "FOO";
54 public static final int PARTITIONS = 10;
57 StringSerializer stringSerializer = new StringSerializer();
60 Serializer valueSerializer;
62 KafkaProducer<String, Bytes> kafkaProducer;
64 KafkaConsumer<String, String> kafkaConsumer;
66 PartitionStatisticsRepository partitionStatisticsRepository;
68 ApplicationProperties properties;
70 ExecutorService executor;
72 PartitionStatisticsRepository repository;
74 WordcountRecordHandler wordcountRecordHandler;
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 oldOffsets = new HashMap<>();
209 newOffsets = new HashMap<>();
210 receivedRecords = new HashSet<>();
212 doForCurrentOffsets((tp, offset) ->
214 oldOffsets.put(tp, offset - 1);
215 newOffsets.put(tp, offset - 1);
218 TestRecordHandler<String, String> captureOffsetAndExecuteTestHandler =
219 new TestRecordHandler<String, String>(wordcountRecordHandler) {
221 public void onNewRecord(ConsumerRecord<String, String> record)
224 new TopicPartition(record.topic(), record.partition()),
226 receivedRecords.add(record);
231 new EndlessConsumer<>(
233 properties.getClientId(),
234 properties.getTopic(),
236 captureOffsetAndExecuteTestHandler);
238 endlessConsumer.start();
246 endlessConsumer.stop();
250 log.info("Exception while stopping the consumer: {}", e.toString());
256 @Import(ApplicationConfiguration.class)
257 public static class Configuration
260 Serializer<Long> serializer()
262 return new LongSerializer();
266 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
268 Properties props = new Properties();
269 props.put("bootstrap.servers", properties.getBootstrapServer());
270 props.put("linger.ms", 100);
271 props.put("key.serializer", StringSerializer.class.getName());
272 props.put("value.serializer", BytesSerializer.class.getName());
274 return new KafkaProducer<>(props);