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.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, Long> kafkaConsumer;
66 PartitionStatisticsRepository partitionStatisticsRepository;
68 ApplicationProperties properties;
70 ExecutorService executor;
72 PartitionStatisticsRepository repository;
74 KeyCountingRebalanceListener keyCountingRebalanceListener;
76 KeyCountingRecordHandler keyCountingRecordHandler;
78 EndlessConsumer<String, Long> endlessConsumer;
79 Map<TopicPartition, Long> oldOffsets;
80 Map<TopicPartition, Long> newOffsets;
81 Set<ConsumerRecord<String, Long>> receivedRecords;
87 @Order(1) // << The poistion pill is not skipped. Hence, this test must run first
88 void commitsCurrentOffsetsOnSuccess() throws ExecutionException, InterruptedException
90 send100Messages(i -> new Bytes(valueSerializer.serialize(TOPIC, i)));
92 await("100 records received")
93 .atMost(Duration.ofSeconds(30))
94 .until(() -> receivedRecords.size() >= 100);
96 await("Offsets committed")
97 .atMost(Duration.ofSeconds(10))
100 checkSeenOffsetsForProgress();
101 compareToCommitedOffsets(newOffsets);
104 assertThatExceptionOfType(IllegalStateException.class)
105 .isThrownBy(() -> endlessConsumer.exitStatus())
106 .describedAs("Consumer should still be running");
111 void commitsOffsetOfErrorForReprocessingOnError()
113 send100Messages(counter ->
115 ? new Bytes(stringSerializer.serialize(TOPIC, "BOOM!"))
116 : new Bytes(valueSerializer.serialize(TOPIC, counter)));
118 await("Consumer failed")
119 .atMost(Duration.ofSeconds(30))
120 .until(() -> !endlessConsumer.running());
122 checkSeenOffsetsForProgress();
123 compareToCommitedOffsets(newOffsets);
125 endlessConsumer.start();
126 await("Consumer failed")
127 .atMost(Duration.ofSeconds(30))
128 .until(() -> !endlessConsumer.running());
130 checkSeenOffsetsForProgress();
131 compareToCommitedOffsets(newOffsets);
132 assertThat(receivedRecords.size())
133 .describedAs("Received not all sent events")
136 assertThatNoException()
137 .describedAs("Consumer should not be running")
138 .isThrownBy(() -> endlessConsumer.exitStatus());
139 assertThat(endlessConsumer.exitStatus())
140 .describedAs("Consumer should have exited abnormally")
141 .containsInstanceOf(RecordDeserializationException.class);
145 /** Helper methods for the verification of expectations */
147 void compareToCommitedOffsets(Map<TopicPartition, Long> offsetsToCheck)
149 doForCurrentOffsets((tp, offset) ->
151 Long expected = offsetsToCheck.get(tp) + 1;
152 log.debug("Checking, if the offset for {} is {}", tp, expected);
154 .describedAs("Committed offset corresponds to the offset of the consumer")
155 .isEqualTo(expected);
159 void checkSeenOffsetsForProgress()
161 // Be sure, that some messages were consumed...!
162 Set<TopicPartition> withProgress = new HashSet<>();
163 partitions().forEach(tp ->
165 Long oldOffset = oldOffsets.get(tp);
166 Long newOffset = newOffsets.get(tp);
167 if (!oldOffset.equals(newOffset))
169 log.debug("Progress for {}: {} -> {}", tp, oldOffset, newOffset);
170 withProgress.add(tp);
173 assertThat(withProgress)
174 .describedAs("Some offsets must have changed, compared to the old offset-positions")
179 /** Helper methods for setting up and running the tests */
181 void doForCurrentOffsets(BiConsumer<TopicPartition, Long> consumer)
183 partitions().forEach(tp ->
185 String partition = Integer.toString(tp.partition());
186 Optional<Long> offset = partitionStatisticsRepository.findById(partition).map(document -> document.offset);
187 consumer.accept(tp, offset.orElse(0l));
191 List<TopicPartition> partitions()
195 .range(0, PARTITIONS)
196 .mapToObj(partition -> new TopicPartition(TOPIC, partition))
197 .collect(Collectors.toList());
201 void send100Messages(Function<Long, Bytes> messageGenerator)
205 for (int partition = 0; partition < 10; partition++)
207 for (int key = 0; key < 10; key++)
209 Bytes value = messageGenerator.apply(++i);
211 ProducerRecord<String, Bytes> record =
212 new ProducerRecord<>(
215 Integer.toString(key%2),
218 kafkaProducer.send(record, (metadata, e) ->
220 if (metadata != null)
224 metadata.partition(),
232 "Exception for {}={}: {}",
246 oldOffsets = new HashMap<>();
247 newOffsets = new HashMap<>();
248 receivedRecords = new HashSet<>();
250 doForCurrentOffsets((tp, offset) ->
252 oldOffsets.put(tp, offset - 1);
253 newOffsets.put(tp, offset - 1);
256 TestRecordHandler<String, Long> captureOffsetAndExecuteTestHandler =
257 new TestRecordHandler<String, Long>(keyCountingRecordHandler) {
259 public void onNewRecord(ConsumerRecord<String, Long> record)
262 new TopicPartition(record.topic(), record.partition()),
264 receivedRecords.add(record);
269 new EndlessConsumer<>(
271 properties.getClientId(),
272 properties.getTopic(),
274 keyCountingRebalanceListener,
275 captureOffsetAndExecuteTestHandler);
277 endlessConsumer.start();
285 endlessConsumer.stop();
289 log.info("Exception while stopping the consumer: {}", e.toString());
295 @Import(ApplicationConfiguration.class)
296 public static class Configuration
299 Serializer<Long> serializer()
301 return new LongSerializer();
305 KafkaProducer<String, Bytes> kafkaProducer(ApplicationProperties properties)
307 Properties props = new Properties();
308 props.put("bootstrap.servers", properties.getBootstrapServer());
309 props.put("linger.ms", 100);
310 props.put("key.serializer", StringSerializer.class.getName());
311 props.put("value.serializer", BytesSerializer.class.getName());
313 return new KafkaProducer<>(props);